[英]Merging Two Ordered Text Files Into Another Without Breaking The Order in C
I have two text file as; 我有两个文本文件;
Andrew Hall
Arnold Price
Shelley Baker
and, 和,
Arnold Hill
Veronica Clay
As you can see they are ordered. 如您所见,它们是有序的。 I need to combine them into another text file which is ordered again.
我需要将它们合并到另一个再次订购的文本文件中。 So, expected output is;
因此,预期输出为:
Andrew Hall
Arnold Hill
Arnold Price
Shelley Baker
Veronica Clay
However, the output shows up as; 但是,输出显示为;
Andrew Hall
Arnold Hill
Arnold Price
I think somehow I am losing last lines of both files and both fsort1 and fsort2 reach end of their files. 我以某种方式失去了这两个文件的最后几行,并且fsort1和fsort2都到达了文件末尾。 How can I find a general solution?
如何找到一般解决方案? What am I doing wrong?
我究竟做错了什么?
My code is like that; 我的代码就是这样;
fgets(name1, 100, fsort1);
fgets(name2, 100, fsort2);
while(!feof(fsort1) || !feof(fsort2)){
if(strcmp(name1, name2)<0){
fprintf(foutput, "%s", name1);
fgets(name1, 100, fsort1);
}
else{
fprintf(foutput, "%s", name2);
fgets(name2, 100, fsort2);
}
}
Thank you. 谢谢。
I think somehow I am losing last lines of both files and both fsort1 and fsort2 reach end of their files.
我以某种方式失去了这两个文件的最后几行,并且fsort1和fsort2都到达了文件末尾。
Yes, you are. 是的,你是。 The comments already pointed out the wrong use of
feof
, but if your loop stops because only one of the file is ended, you are not continuing the read the other file. 注释已经指出了
feof
的错误使用 ,但是如果您的循环由于仅一个文件结束而停止,则您不会继续读取另一个文件。 You can use somthing like this: 您可以这样使用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *fsort1 = fopen("names1.txt", "r");
FILE *fsort2 = fopen("names2.txt", "r");
FILE *foutput = fopen("names_out.txt", "w");
if ( !fsort1 || !fsort2 || !foutput)
{
perror("Error openng files");
exit(EXIT_FAILURE);
}
char name1[256] = {'\0'};
char name2[256] = {'\0'};
char *r1 = fgets(name1, 256, fsort1);
char *r2 = fgets(name2, 256, fsort2);
while ( r1 && r2 )
{
if ( strcmp(name1, name2) < 0 ) {
fprintf(foutput, "%s", name1);
r1 = fgets(name1, 256, fsort1);
}
else {
fprintf(foutput, "%s", name2);
r2 = fgets(name2, 256, fsort2);
}
}
while ( r1 )
{
fprintf(foutput, "%s", name1);
r1 = fgets(name1, 256, fsort1);
}
while ( r2 )
{
fprintf(foutput, "%s", name2);
r2 = fgets(name2, 256, fsort2);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.