C语言文件合并中,文件末尾的问题,求大神解答
发布网友
发布时间:2022-05-12 16:30
我来回答
共2个回答
热心网友
时间:2023-08-03 13:28
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE*f1,*f2,*f;
f1=fopen("E:\\bc\\1.txt","r");
f2=fopen("E:\\bc\\2.txt","r");
f=fopen("E:\\bc\\3.txt","w");
int x,y,m=0;
while(!feof(f1)&&!feof(f2)) //改为while(x!=-1&&y!=-1)时是个死循环
{
if(m==0)
{
fscanf(f1,"%d",&x);
fscanf(f2,"%d",&y);
m=1;
continue;
}
if(x<y)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fscanf(f1,"%d",&x);
}
else
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fscanf(f2,"%d",&y);
}
}
while(!feof(f1))
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fscanf(f1,"%d",&x);
}
while(!feof(f2))
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fscanf(f2,"%d",&y);
}
fclose(f1);
fclose(f2);
fclose(f);
return 0;
}追问谢谢
热心网友
时间:2023-08-03 13:28
你的问题在于到达文件结尾的时候while退出,这时候x和y中都还保存着所在文件的最后一个值。但是你写文件的操作也是在while中进行的,所以这个最后的值就没法再写进去了,只需要在最后增加进去。
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE*f1,*f2,*f;
f1=fopen("E:\\bc\\1.txt","r");
f2=fopen("E:\\bc\\2.txt","r");
f=fopen("E:\\bc\\3.txt","w");
int x,y,m=0;
int flag_x = 0;
int flag_y = 0;
while(!feof(f1)&&!feof(f2)) //改为while(x!=-1&&y!=-1)时是个死循环
{
if(m==0)
{
fscanf(f1,"%d",&x);
fscanf(f2,"%d",&y);
m=1;
}
if(x<y)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fscanf(f1,"%d",&x);
}
else
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fscanf(f2,"%d",&y);
}
}
while(!feof(f1))
{
//这里还是要增加一个x和y的判断的,因为作为全局变量,y里仍然是有值的。
if(x<y)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fscanf(f1,"%d",&x);
}
else
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fscanf(f2,"%d",&y);
flag_y = 1;
}
}
while(!feof(f2))
{
if(x<y)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fscanf(f1,"%d",&x);
flag_x = 1;
}
else
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fscanf(f2,"%d",&y);
}
}
if(x && y)
{
if(x<y)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
}
else
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
}
}
else
{
if(flag_x == 0)
{
fprintf(f,"%d",x);
fprintf(f,"%c",' ');
}
if(flag_y == 0)
{
fprintf(f,"%d",y);
fprintf(f,"%c",' ');
}
}
fclose(f1);
fclose(f2);
fclose(f);
return 0;
}