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]
(no s
on 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:
char line[132];
...
fscanf(fp, "%131[^\n]", line);
Third, this will leave the newline in the input stream, potentially fouling up the next read.
Finally, you don't want to use feof
as 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, if line
is sized to hold 20 characters and the input line has 80 characters (including the newline), fgets
will read 19 characters and append the 0 terminator into line
. If the input line is 10 characters, it will read the whole input line into line
(including the newline).
fgets
will return NULL on EOF or error, so you should structure your loop as
while (fgets(line, sizeof line, fp))
{
// do something with line
}
if (feof(fp))
// hit end of file
else
// error on read.
I'm pretty sure that \n is not allowed within a scanset. It would be helpful if you state what you're trying to code there.
If you want to read in entire lines, I'd strongly suggest you go for the fgets() library routine. With fgets() you're able to state, how much characters to read in at max, so you're able to avoid buffer overflows.
精彩评论