2009-12-02 46 views
23

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

我假设我需要一个while循环,但我不知道如何去做。

回答

67

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

​​

检查输入呼吁适当条件的结果上面,然后调用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 
} 

使用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 
} 

使用fgetc()

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

使用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 
} 

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

while(!feof(stream)) 
{ 
    fscanf(stream, "%s", buffer); 
    ... 
} 

这种形式不工作的人认为它的方式,因为feof()不会返回true,直到你已经尝试后读取过去的结束的文件。结果,循环执行一次太多,这可能会或可能不会导致你一些悲伤。

+0

不错,但这个受欢迎的答案的一些建议:1)“功能:fscanf()在EOF或错误:成功转换次数少于预期”等于输入“错误”与格式转换失败。 IMO。建议另一栏OTOH是一个复杂的功能2)拼写检查3)在'while(!feof(stream))'例子中建议“坏代码”注释。 – chux 2015-11-06 20:38:42

10

一个可能的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. 
     */ 
    } 
} 

现在,我会忽略feof和类似的功能。 Exprience表明,在相信eof尚未达成的情况下,在错误的时间调用它并处理两件事情非常容易。

避免的陷阱:使用char作为c的类型。 getchar将下一个字符转换为unsigned char,然后转换为int。这意味着在大多数[理性]平台上,EOF的值和c中的有效“char”值不会重叠,因此您不会意外检测到EOF的“正常”char

+0

thait将永远不会工作,你没有定义eof – streetparade 2009-12-02 21:56:00

+1

我''包括'stdio.h。 – 2009-12-02 21:56:38

+0

看到我的回答我定义了一个eof – streetparade 2009-12-02 21:56:53

0

您应该从文件中读取后检查EOF。

fscanf_s     // read from file 
while(condition)   // check EOF 
{ 
    fscanf_s    // read from file 
} 
相关问题