如何使用 EOF 在 C 中运行文本文件?
我有一个文本文件,每行都有字符串。我想为文本文件中的每一行增加一个数字,但是当它到达文件末尾时,它显然需要停止。我尝试对 EOF 进行一些研究,但无法真正理解如何正确使用它。
我假设我需要一个 while 循环,但我不知道该怎么做。
I have a text file that has strings on each line. I want to increment a number for each line in the text file, but when it reaches the end of the file it obviously needs to stop. I've tried doing some research on EOF, but couldn't really understand how to use it properly.
I'm assuming I need a while loop, but I'm not sure how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如何检测 EOF 取决于您用来读取流的内容:
检查输入调用的结果是否符合上述条件,然后调用
feof()
来确定结果是否是由于命中造成的EOF 或其他一些错误。使用
fgets()
:使用
fscanf()
:使用
fgetc()
:使用
fread()
:请注意它们的形式都是相同的:检查读操作的结果;如果失败,则检查 EOF。您会看到很多示例,例如:
此表单并不像人们想象的那样工作,因为
feof()
在您之后之前不会返回 true我试图读到文件末尾。结果,循环执行了太多次,这可能会也可能不会给您带来一些麻烦。How you detect EOF depends on what you're using to read the stream:
Check the result of the input call for the appropriate condition above, then call
feof()
to determine if the result was due to hitting EOF or some other error.Using
fgets()
:Using
fscanf()
:Using
fgetc()
:Using
fread()
:Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:
This form doesn't work the way people think it does, because
feof()
won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.一种可能的 C 循环是:
现在,我会忽略
feof
和类似的函数。经验表明,很容易在错误的时间调用它并在认为尚未达到 eof 的情况下处理某些内容两次。要避免的陷阱:使用
char
作为 c 的类型。getchar
将下一个字符转换为unsigned char
,然后转换为int
。这意味着在大多数 [sane] 平台上,EOF
的值和c
中的有效“char
”值不会重叠,因此您不会重叠永远不会意外检测到“正常”char
的EOF
。One possible C loop would be:
For now, I would ignore
feof
and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.Pitfall to avoid: using
char
for the type of c.getchar
returns the next character cast to anunsigned char
and then to anint
. This means that on most [sane] platforms the value ofEOF
and valid "char
" values inc
don't overlap so you won't ever accidentally detectEOF
for a 'normal'char
.从文件读取后,您应该检查 EOF。
You should check the EOF after reading from file.
我建议您使用 fseek-ftell 函数。
I would suggest you to use fseek-ftell functions.