I am having a program where
fscanf(fp,"%[^\n]s",line);
is used for reading a line.
If I put in a while loop,
while(!feof(fp))
fscanf(fp,"%[^\n]s",line);
the above code works for first line and for the rest, I am getting
line as NULL. ( line = “” )
My file contains many lines even many blank lines. How can I make the above code work?
First, the conversion specifier would be
%[^\n](noson the end).Secondly, you don’t want to use the
%[conversion specifier without an explicit size; otherwise you run the risk of a buffer overflow:Third, this will leave the newline in the input stream, potentially fouling up the next read.
Finally, you don’t want to use
feofas your loop condition, since it won’t return true until after you try to read past EOF, causing your loop to execute one too many times.Frankly, I think the better option is to use
fgets(); it will read everything up to and including the next newline or one less than the specified size. IOW, iflineis sized to hold 20 characters and the input line has 80 characters (including the newline),fgetswill read 19 characters and append the 0 terminator intoline. If the input line is 10 characters, it will read the whole input line intoline(including the newline).fgetswill return NULL on EOF or error, so you should structure your loop as