当/为什么是一个坏主意,使用的fscanf()函数? [英] When/why is it a bad idea to use the fscanf() function?

查看:360
本文介绍了当/为什么是一个坏主意,使用的fscanf()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一个href=\"http://stackoverflow.com/questions/861793/trouble-reading-a-line-using-fscanf/861822#861822\">an答案有一个有趣的说法:这几乎的总是的一个坏主意,使用的fscanf()的功能,因为它可以离开你在一个未知地点文件指针上的失败。我preFER使用与fgets()来获取每一行,然后的sscanf()

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."

你能在何时/为什么它可能是更好的使用展开与fgets()的sscanf()来阅读一些文件?

Could you expand upon when/why it might be better to use fgets() and sscanf() to read some file?

推荐答案

试想一个文件,三行:

   1
   2b
   c

使用的fscanf()读整数,第一行就应该是好的,但在第二行的fscanf()将离开你在'b',不知道从那里做。你将需要一些机制来移动经过垃圾输入看到的第三行。

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.

如果你做了与fgets()的sscanf(),你能保证你的文件指针移动的同时,这是一个比较容易处理线。一般情况下,你仍然应该着眼于整个字符串它来报告任何奇怪的字符。

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.

我preFER后一种方法我自己,但我不会与该声明同意它几乎总是一个坏主意,用的fscanf()。 .. 的fscanf()是大多数事情完全没有问题。

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.

这篇关于当/为什么是一个坏主意,使用的fscanf()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆