2012-07-28 106 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