c - memory allocate string for fgets with null terminating char -


i'm sorry if question seems "easy" couldn't find answer anywhere. tried use fgets() read line file. make sure no space wasted, first of found line's length:

do     {         c= getc(file);         words++;     }while (c!=eof && c!='\n'); 

then allocated memory exacly number of words:

char* line = (char*)malloc(sizeof(char)*(words)); 

and then, use fgets() read line line buffer. problem is, working. thought should allocate memory null terminating char too. happened here?

you do need allocate space null terminator. fact working doesn't mean (at least in c).

plus, fgets returns \n character. need 2 characters. 1 \n , 1 \0.

i recommend approach though:

char buffer [1024]; if ( fgets (buffer, 1024, f) != null ) {    // buffer } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -