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

前端 未结 6 1013
忘掉有多难
忘掉有多难 2020-12-16 05:20

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

6条回答
  •  孤街浪徒
    2020-12-16 06:08

    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.

提交回复
热议问题