2009-10-29 56 views
1

我有程序等(从link textFGETS在C++重复最后一行

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 

它重复最后文件行两次。我在其他程序中也遇到了这个问题。

回答

7

使用feof()作为条件为一个循环从文件中几乎总是导致问题读取。标准方式看起来是这样的:

while (fgets(buffer, 100, infile)) 
    fputs(buffer, stdout); 
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); 
+0

Nooooo ..不要这样做。 – 2009-10-29 19:31:29

+0

标准模式(在所有porocedural语言)是把get语句作为条件的循环。如果失败,则永不输入循环。 – 2009-10-29 19:33:12

0

我喜欢本·罗素的回答。这是我的版本,以避免在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; 
} 

非常感谢, 海梅Daviu

0

之所以FEOF(inputfile_pointer)不是复制文件时检查终止正确的方法,是因为它不的两个工作以下情况:

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

证明:

  • 假设feoffgets()后检查,但fputs()之前。然后,它不适用于案例1.上面,因为任何字符fgets()在EOF之前读取,将不会使用fputs()
  • 假设feoffputs()之后检查,但在fgets()之前检查。然后它不起作用的情况2.上面,因为当fgets()最后遇到EOF,它不会覆盖任何新的缓冲区字符串,并且因为fputs()被允许运行一次,它会将输出文件放在相同的内容缓冲区字符串,如前一次迭代;因此在输出文件中重复最后一行。