2012-07-28 108 views
0

程序應該查看每行file1,然後查看file2中是否存在完全相同的行。如果是,則將該行復制到名爲output的新文件。C文件處理:文本不附加在文件末尾

說,以下是文件(這可能是一句話,但爲了簡單起見,我已經把號碼)的內容 -

file1    file2 
    1     2 
    2     4 
    3     15 
    4     6 
    5     11 
    6     8 
    7 
    8 
    9 

然後output文件應該是這樣 -

(Expected) output 
       2 
       4 
       6 
       8 

內殼我可以看到printf按預期打印output,但fprintf顛倒了順序,我不明白爲什麼?這會打印輸出文件的輸出是 -

output 
    8 
    6 
    4 
    2 

下面的代碼 -

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    FILE *file1, *file2, *output; 
    int c; 

    /*Creating buffers where data will be stored for comparison*/ 
    char buffer1[999], buffer2[999]; 

    /*Settig the buffer characters array to 0*/ 
    memset(buffer1, 0, sizeof(buffer1)); 
    memset(buffer2, 0, sizeof(buffer2)); 

    /*Open output file in "w" so that it clears the file*/ 
    output = fopen("output", "w"); 
    /*Open file1 and then save the line inside buffer1 (within while loop)*/ 
    file1 = fopen("file1", "r"); 
    /*Read each character in file until End Of Line*/ 
    while((c = getc(file1)) != EOF) 
    { 
     int i = 0; 
     /*Save each new line of file1 in buffer1 for comparison*/ 
     while(c != '\n') 
     { 
      buffer1[i++] = c; 
      c = getc(file1); 
     } 

     /*Open file2 and then save it's line in buffer2 (withing while loop)*/  
     file2 = fopen("file2", "r"); 
     int ch; 

     while((ch = getc(file2)) != EOF) 
     { 
      i = 0; 
      while(ch != '\n') 
      { 
       buffer2[i++] = ch; 
       ch = getc(file2); 
      } 

      /*Compare lines of file1 against each line of file2*/ 
      if(strcmp(buffer1,buffer2) == 0) 
      { 
       /*Save similar lines in a file named output*/ 
       output = fopen("output", "a"); 
       fprintf(output,"%s\n", buffer2); 
       printf("%s\n", buffer2); 
       break; 
      } 
      /*Reset the buffer*/ 
      memset(buffer2, 0, sizeof(buffer2)); 
     } 

     memset(buffer1, 0, sizeof(buffer1)); 
    } 

    /*Close the output file if there were any comparison made i.e. if file was opened*/ 
    if(output != NULL) 
    { 
     fclose(output); 
    } 

    /*Close other files*/ 
    fclose(file1); 
    fclose(file2); 

    return 0; 
} 
+0

PS:我是初學者,仍然不確定我是否正確編寫代碼,請親切:) 謝謝。 – 2012-07-28 05:52:34

+0

不是「W」使用「W +」 – qrtt1 2012-07-28 05:55:46

回答

4

你在每一個差開放output只是一個時間在結束這是錯誤的,也許會導致你的問題。嘗試打開output一次,也許在循環之前。如果您沒有發現任何區別,可以將其刪除,以避免空文件。

+0

這是,非常感謝。我無法自己想清楚,對我來說這並不是很明顯,我需要每次關閉它。順便說一句,現在看,我覺得這不是最優雅的做法(寫每一行打開/關閉)。你認爲可以有更好的方法來處理它嗎? – 2012-07-28 06:13:15

+0

@GuravButola如果你打開和關閉一次,沒有理由打開每一次,然後寫:)如此打開的開始,寫你想要的時候,並在結束時關閉。 – 2012-07-28 06:22:15

+0

噢,好吧!這似乎工作,並給出了輸出,但給我一些錯誤,我運行它。 http://pastebin.com/s8SLD8PM – 2012-07-28 06:28:14