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);
}
看起来你一直在修补你的程序。你很近。将'line'打印到'file3',而不是'linec',它应该可以工作。 –
P.S.在编辑你的文章以摆脱'if(count%2 == 0)'条件之前,我发表了我的评论*。这种情况很好,我会把它留下。 –
是的,现在它的工作。但是我需要改变它,以便即使其中一个文件完成复制行,它也能继续工作 –