从两个不同的文件获取输入 [英] Getting inputs from two different files
问题描述
我一直在研究这个问题:
I've been working on this problem:
C程序,它可以从2个文件&中合并行打印结果
C Program that Merges Lines Alternatively from 2 Files & Print Result
这是我编写的代码:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp;
FILE *fp1;
FILE *fp2;
fp=fopen ("sample4.txt","r");
fp1=fopen ("sample3.txt","r");
fp2= fopen ("output.txt","w");
char a[100];
char b[100];
while (fgets(a,100,fp1)!=NULL||fgets (b,100,fp)!=NULL){
printf("%s",a);
printf ("%s",b);
}
return 0;
}
但是我没有得到想要的输出.有人可以解释为什么吗?
However I am not getting desired output. Can someone explain why?
PS:还有另一个问题要求:如果一个文件的行数少于另一个文件,则应简单地打印较大文件中的其余行.
PS: There is another problem requirement: If one file has less number of lines than the other, the remaining lines from the larger file should be simply printed.
推荐答案
但是我没有得到想要的输出.有人可以解释为什么吗?
However I am not getting desired output. Can someone explain why?
fgets(a,100,fp1)!= NULL || fgets(b,100,fp)!= NULL
在以下情况下不评估第二个 fgets()
||
的左侧为true(由于成功读取).
fgets(a,100,fp1)!=NULL||fgets (b,100,fp)!=NULL
does not evaluate the 2nd fgets()
when the left-hand-side of the ||
is true (due to a successful read).
还有另一个问题要求:如果一个文件的行数少于另一个文件,则应简单地打印较大文件中的其余行.
There is another problem requirement: If one file has less number of lines than the other, the remaining lines from the larger file should be simply printed.
而不是尝试从已返回 NULL
的流中重新读取,而是考虑每个流的标志:
Rather than try to re-read from a stream that has already returned NULL
, consider a flag per stream:
// OP may want to stop before here if an fopen() failed.
bool ok_a = fp1; // Did file open OK?
bool ok_b = fp;
char a[100];
char b[100];
while (ok_a || ok_b) {
// OK to read and then set the flag per the read result.
if (ok_a && (ok_a = fgets(a, sizeof a, fp1)) {
printf("%s",a);
}
if (ok_b && (ok_b = fgets(b, sizeof b, fp)) { // ***
printf("%s",b);
}
}
// Optional
printf("a: EOF:%d, Error:%d\n", feof(fp1), ferror(fp1));
printf("b: EOF:%d, Error:%d\n", feof(fp) , ferror(fp));
// Good to close the files
// A fclose() should NOT get called if the FILE * pointer is NULL.
if (fp) fclose(fp);
if (fp1) fclose(fp1);
if (fp2) fclose(fp2);
OP可能希望附加代码来处理以下情况:由于行长,嵌入, fgets()
的结果不包含'\ n'
空字符或最后一行.
OP might want additional code to handle the cases when the result of fgets()
does not contain a '\n'
due to being a long line, an embedded null character or the last line.
***请注意,不需要第二个缓冲区,可以重新使用 a []
.
*** Note that a 2nd buffer is not needed, could re-use a[]
.
这篇关于从两个不同的文件获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!