1

我有类似的程序(来自链接文本

FILE* soubor;
char buffer[100];
soubor = fopen("file","r");
string outp = "";
while (! feof(soubor))
{
        fgets(buffer,100,soubor);
        fputs (buffer , stdout);
}
fclose(soubor);

和文件一样

A
B
C
D
E

程序的输出是

A
B
C
D
E
E

它重复文件的最后一行两次。我在其他程序中也有这个问题。

4

4 回答 4

7

使用feof()循环从文件中读取的条件几乎总是会导致问题。标准方式如下所示:

while (fgets(buffer, 100, infile))
    fputs(buffer, stdout);
于 2009-10-29T17:48:22.610 回答
7

问题是对于最后一行, fgets 将失败。但是,您直到下一个循环才检查 feof,因此您仍然调用 fputs 它将打印缓冲区的内容,即上一行。

尝试这个:

FILE* soubor;
char buffer[100];
soubor = fopen("file","r");
string outp = "";
while (true)
{
  fgets(buffer,100,soubor);
  if (feof(soubor))
    break;
  fputs (buffer , stdout);
}
fclose(soubor);
于 2009-10-29T10:41:03.333 回答
0

我喜欢 Ben Russels 的回答。这是我的版本,以避免在 c 代码中重复最后一行。它有效,但我不明白为什么,因为 if (fgets != NULL)它应该做这个工作的条件。

int main ()
{
    FILE* pFile;
    char name[41] = "fileText04.txt";
    char text[81];
    int i;

    pFile = fopen("fileText04.txt", "wt");
    if (pFile == NULL)
    {
        printf("Error creating file \n");
        exit(1);
    }
    else
    {
        for (i=0; i<5; i++)
        {
            printf("Write a text: \n");
            fgets(text, 81, stdin);
            fputs(text, pFile);
        }
    }
    fclose (pFile);
    pFile = fopen(name, "rt");
    if (pFile == NULL)
    {
        printf("File not found. \n");
        exit(2);
    }
    while (! feof(pFile))
    {
        fgets(text, 80, pFile);
        if (feof(pFile))   // This condition is needed to avoid repeating last line.
            break;         // This condition is needed to avoid repeating last line.
        if (fgets != NULL)
            fputs(text, stdout);
    }
    fclose (pFile);
    return 0;
}

非常感谢,杰米·戴维

于 2014-05-27T12:56:51.470 回答
0

feof (inputfile_pointer) 不是在复制文件时检查终止的正确方法的原因是因为它在以下两种情况下都不起作用:

  1. 文件结束时没有换行符。
  2. 文件以换行符结尾。

证明:

  • 假设在feof之后fgets()但在 之前检查fputs()。然后它不适用于上面的情况 1。因为fgets()在 EOF 之前读取的任何字符都不会被fputs().
  • 假设feof在之后检查fputs(),但在之前fgets()。然后它不适用于上面的情况2。fgets()最后遇到EOF时,它不会用任何新内容覆盖缓冲区字符串,并且fputs()允许再运行一次,它将在输出文件中放入与缓冲区字符串相同的内容和之前的迭代一样;因此在输出文件中重复最后一行。
于 2017-10-29T16:40:54.623 回答