使用 fgets 从文件中读取
我正在读取以下格式的文件:
1 32 43 23
32 43
123 43 54 243
123 2222
2
这是我的代码片段。
string[100];
while(!feof(fp))
fgets(string,100,fp)
现在,当我把每个字符串放在最后一个字符串中时,我会得到重复和一些更多的歧义(就像其他东西也会被打印,比如 123 左右)。
如何解决这个问题呢?
I am reading from file of format
1 32 43 23
32 43
123 43 54 243
123 2222
2
Here is my code snippet.
string[100];
while(!feof(fp))
fgets(string,100,fp)
Now, when I put every string, in the last string I am getting repetition and some more ambiguities (like something else also gets printed say 123 or so).
How to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要检查fgets的返回值。如果读取成功,
fgets
将返回指向您传递给它的缓冲区的指针(即示例中的string
)。如果遇到文件结尾且未读取任何字符,fgets
将返回NULL
。试试这个:
You need to check the return value of fgets. If a read has been successful,
fgets
returns the pointer to the buffer that you passed to it (i.e.string
in your example). If the End-of-File is encountered and no characters have been read,fgets
returnsNULL
.Try this:
eof
仅在您尝试读取末尾的文件后才会到达。您必须使用fgets
的返回值(它在 eof 或错误时返回NULL
以及否则给出的指针):像这样检查返回值会导致您永远不要像另一个循环一样在循环体内击中 eof,而不是在条件中击中 eof。
The
eof
is only reached after you have attempted to read from a file that is at the end. You have to use the return value offgets
instead (which returnsNULL
on eof or error and the pointer it is given otherwise):Checking the return value like this will cause you never to hit the eof inside the body of the loop, like the other one, instead of in the condition.