2009-10-29 54 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()被允許運行一次,它會將輸出文件放在相同的內容緩衝區字符串,如前一次迭代;因此在輸出文件中重複最後一行。