Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why is it a bad idea to use the fscanf() function?

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?

like image 708
Rob Kam Avatar asked May 14 '09 19:05

Rob Kam


People also ask

What is fscanf used for?

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.

What does fscanf return if failed?

If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

Does fscanf read one line at a time?

Each call to fscanf() reads one line from the file.


1 Answers

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.

like image 182
Chris Arguin Avatar answered Oct 01 '22 07:10

Chris Arguin