2016-11-18 32 views
0

对于任务,我必须从2个文件逐行输入文本到第3个文件。因此,文件1行1将文件3行1和文件2行将文件3行2.我试图这样做,但似乎无法从每个文件的行交替。我只能分别从每个文件中获取行。请帮助任何建议。从备用文件逐行打印到c中的第三个文件

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

int main(int argc, char *argv[]) 
{ 
    FILE *file1, *file2, *file3; 
    char line [1000]; /* or other suitable maximum line size */ 

    // check to make sure that all the file names are entered 
    if (argc != 4) { 
     perror("Error: "); 
     printf("Not enough files were entered!\n"); 
     exit(0); 
    } 

    file1 = fopen(argv[1],"r");; 
    file2 = fopen(argv[2],"r"); 
    file3 = fopen(argv[3],"w"); 

    // check whether the file has been opened successfully 
    if (file1 == NULL) 
    { 
     perror("Error: "); 
     printf("Cannot open file1 %s!\n", argv[1]); 
     exit(-1); 
    } 
    // check whether the file has been opened successfully 
    if (file2 == NULL) 
    { 
     perror("Error: "); 
     printf("Cannot open file2 %s!\n", argv[2]); 
     exit(0); 
    } 
    // check whether the file has been opened successfully 
    if (file3 == NULL) 
    { 
     perror("Error: "); 
     printf("Cannot open file3 %s!\n", argv[3]); 
     exit(0); 
    } 
    int count = 0; 
    while (1) 
    { 
      if(fgets(line, sizeof line, file1) != NULL) 
      { 
       count+=1; 
       fprintf(file3, line); 
      } 
      else 
      { 
       break; 
      } 

      if(fgets(line, sizeof line, file2) != NULL) 
      { 
       count++; 
       fprintf(file3, line); 
      } 
      else 
      { 
       break; 
      } 
    } 

    fclose (file1); 
    fclose (file2); 
    fclose (file3); 
} 
+0

看起来你一直在修补你的程序。你很近。将'line'打印到'file3',而不是'linec',它应该可以工作。 –

+0

P.S.在编辑你的文章以摆脱'if(count%2 == 0)'条件之前,我发表了我的评论*。这种情况很好,我会把它留下。 –

+0

是的,现在它的工作。但是我需要改变它,以便即使其中一个文件完成复制行,它也能继续工作 –

回答

0

fprintf(FILE *, const char *format, ...)期望一个格式作为第二参数。

使用fprintf(file3, line);将调用未定义的行为(UB)应line包含'%',或者至少缺少%如果遇到"%%"

使用fputs()

// fprintf(file3, line); 
fputs(line, file3); 

先进的编码其他问题:

如果源文件中包含一个空字符,使用fgets()是不够的,因为它不报告读取的长度。其他方法包括使用fgetc(),fread()或非标准C getline()

如果输入文件没有以'\n'结尾,那么这个回合线可能看起来像是从另一个文件读取的行的预先修复。

正如OP指出的那样,线长约为1000+是一个问题。

源文件行结尾,如果它们不符合代码对行结束的理解可能会导致问题。

相关问题