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
Post a Comment