有两个磁盘文件A和B,各自存放一行字母,今要求把这两个文件中的信息合并(按字母顺序排序),输出到一个新文件C中去
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void file(char f[])
{
FILE *fp;
char ch,file[10];
printf("请输入文件的名字:");
scanf("%s",file);
getchar();
if((fp=fopen(file,"wb"))==NULL)
{
printf("can not open file\n");
exit(0);
}
printf("请输入一个准备储存到磁盘的字符串(以#结束):");
ch=getchar();
while(ch!='#')
{
fputc(ch,fp);
putchar(ch);
ch=getchar();
}
fclose(fp);
}
int main()
{
FILE *fp1,*fp2,*fp3;
char ch,t,filename1[10],filename2[10],filename3[10],c[200];
int a,b,i,j,n=0;
printf("Please enter the name of file:");
scanf("%s",filename1);
printf("Now is the %s file!\n",filename1);
file(filename1);
printf("\n");
printf("Please enter the name of file:");
scanf("%s",filename2);
printf("Now is the %s file!\n",filename2);
file(filename2);
if((fp1=fopen(filename1,"rb"))==NULL)
{
printf("can not open file\n");
exit(0);
}
printf("The data of %s is:",filename1);
for(i=0;(ch=fgetc(fp1))!=EOF;i++)
{
c[i]=ch;
putchar(c[i]);
n++;
}
fclose(fp1);
i=n;
if((fp2=fopen(filename2,"rb"))==NULL)
{
printf("can not open file\n");
exit(0);
}
printf("\n");
printf("The data of %s is:",filename2);
for(;(ch=fgetc(fp2))!=EOF;i++)
{
c[i]=ch;
putchar(c[i]);
}
fclose(fp2);
n=i;
//排序
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
a=c[i];
b=c[j];
if(a>b)
{
t=c[i];
c[i]=c[j];
c[j]=t;
}
}
}
printf("\n");
printf("Please enter the name of file:");
scanf("%s",filename3);
getchar();
printf("Now is the %s file!\n",filename3);
if((fp3=fopen(filename3,"wb"))==NULL)
{
printf("can not open file\n");
exit(0);
}
for(i=0;i<n;i++)
{
putc(c[i],fp3);
putchar(c[i]);
}
fclose(fp3);
return 0;
}
这是我自己在写这道题时的做法,我知道有很多的不足,希望可以帮到你一点,如果你有更好的办法,可以指出来哦!