如何使用EOF在C中运行文本文件?

Tyl*_*eat 30 c file eof

我有一个文本文件,每行都有字符串.我想为文本文件中的每一行增加一个数字,但是当它到达文件的末尾时,它显然需要停止.我曾尝试对EOF进行一些研究,但无法真正理解如何正确使用它.

我假设我需要一个while循环,但我不知道该怎么做.

Joh*_*ode 80

如何检测EOF取决于您用于读取流的内容:

function                  result on EOF or error                    
--------                  ----------------------
fgets()                   NULL
fscanf()                  number of succesful conversions
                            less than expected
fgetc()                   EOF
fread()                   number of elements read
                            less than expected
Run Code Online (Sandbox Code Playgroud)

检查输入调用的结果是否有上述适当的条件,然后调用feof()以确定结果是否是由于击中EOF或其他一些错误.

使用fgets():

 char buffer[BUFFER_SIZE];
 while (fgets(buffer, sizeof buffer, stream) != NULL)
 {
   // process buffer
 }
 if (feof(stream))
 {
   // hit end of file
 }
 else
 {
   // some other error interrupted the read
 }
Run Code Online (Sandbox Code Playgroud)

使用fscanf():

char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
  // process buffer
}
if (feof(stream)) 
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}
Run Code Online (Sandbox Code Playgroud)

使用fgetc():

int c;
while ((c = fgetc(stream)) != EOF)
{
  // process c
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}
Run Code Online (Sandbox Code Playgroud)

使用fread():

char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                     // element of size
                                                     // BUFFER_SIZE
{
   // process buffer
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted read
}
Run Code Online (Sandbox Code Playgroud)

请注意,所有这些表单都是相同的:检查读取操作的结果; 如果失败,检查EOF.你会看到很多例子:

while(!feof(stream))
{
  fscanf(stream, "%s", buffer);
  ...
}
Run Code Online (Sandbox Code Playgroud)

此表单不像人们认为的那样工作,因为您尝试读取文件末尾之后feof()才会返回true .结果,循环执行一次太多,这可能会或可能不会让你感到悲伤.


CB *_*ley 12

一个可能的C循环是:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我会忽略feof和类似的功能.Exprience表明,在错误的时间调用它并且在认为尚未达到eof的情况下处理两次事情太容易了.

要避免的陷阱:char用于c的类型.getchar将下一个字符转换为a unsigned char然后再返回int.这意味着在大多数[理智]平台上EOF,有效" char"值的值c不会重叠,因此您不会意外地检测到EOF"正常" char.