In an answer there was an interesting statement: "It's almost always a bad idea to use the fscanf()
function as it can leave your file pointer in an unknown location on failure. I prefer to use fgets()
to get each line in and then sscanf()
that."
Could you expand upon when/why it might be better to use fgets()
and sscanf()
to read some file?
The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.
If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
Each call to fscanf() reads one line from the file.
Imagine a file with three lines:
1
2b
c
Using fscanf()
to read integers, the first line would read fine but on the second line fscanf()
would leave you at the 'b', not sure what to do from there. You would need some mechanism to move past the garbage input to see the third line.
If you do a fgets()
and sscanf()
, you can guarantee that your file pointer moves a line at a time, which is a little easier to deal with. In general, you should still be looking at the whole string to report any odd characters in it.
I prefer the latter approach myself, although I wouldn't agree with the statement that "it's almost always a bad idea to use fscanf()
"... fscanf()
is perfectly fine for most things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With