4.有两个磁盘文件A和B,各存放一行字母,今要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件C中去。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char a[100];
if((fp=fopen("A.txt","r"))==NULL)//打开test1文件
{
printf("can't open file!\n");
exit(0);
}
int i=0;
a[i]=fgetc(fp);//把fp所指向的文件test2中的第一个字符读入到数组a[0]
while(a[i]!=EOF)//若第一个字符不是结束符EOF,则继续把指针fp指向的文件test1中的字符逐个读入到数组a,直至遇到标识符EOF结束循环
{
putchar(a[i]);
i++;
a[i]=fgetc(fp);
}
putchar('\n');
fclose(fp);
if((fp=fopen("B.txt","r"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
a[i]=fgetc(fp);//继续把fp所指向的文件test2中的第一个字符读入到数组a[i]
while(a[i]!=EOF)//若第i个字符不是结束符EOF,则继续把指针fp指向的文件test2中的字符逐个读入到数组a,直至遇到标识符EOF结束循环
{
putchar(a[i]);
i++;
a[i]=fgetc(fp);
}
a[i]='\0';//此时数组a是test1文件和test2文件所有字符(包括text2文件中最后的结束符'\0')的组合
putchar('\n');
fclose(fp);
int n=i;//此时n为数组a的长度
int j,t;
for(i=0;i<n-1;i++)//对数组a进行直接选择排序
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
if((fp=fopen("C.txt","w"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
i=0;
while(i<n)
{
fputc(a[i],fp);//在循环里,这条语句把数组a的所有字符写到文件指针变量fp所指向的文件C.txt中
putchar(a[i]);//在循环里,这条语句把数组a的所有字符显示到屏幕上
i++;
}
fclose(fp);//关闭文件test3,防止它被误用
putchar('\n');
return 0;
}
在VS2019下,需将源文件的fopen做些修改:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fp;
char a[100];
fopen_s(&fp, "A.txt", "r");
if (fp == NULL)//打开test1文件
{
printf("can't open file!\n");
exit(0);
}
int i = 0;
a[i] = fgetc(fp);//把fp所指向的文件test2中的第一个字符读入到数组a[0]
while (a[i] != EOF)//若第一个字符不是结束符EOF,则继续把指针fp指向的文件test1中的字符逐个读入到数组a,直至遇到标识符EOF结束循环
{
putchar(a[i]);
i++;
a[i] = fgetc(fp);
}
putchar('\n');
fclose(fp);
fopen_s(&fp, "B.txt", "r");
if (fp== NULL)
{
printf("can't open file!\n");
exit(0);
}
a[i] = fgetc(fp);//继续把fp所指向的文件test2中的第一个字符读入到数组a[i]
while (a[i] != EOF)//若第i个字符不是结束符EOF,则继续把指针fp指向的文件test2中的字符逐个读入到数组a,直至遇到标识符EOF结束循环
{
putchar(a[i]);
i++;
a[i] = fgetc(fp);
}
a[i] = '\0';//此时数组a是test1文件和test2文件所有字符(包括text2文件中最后的结束符'\0')的组合
putchar('\n');
fclose(fp);
int n = i;//此时n为数组a的长度
int j,t;
for (i = 0; i < n - 1; i++)//对数组a进行直接选择排序
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
fopen_s(&fp, "C.txt", "w");
if (fp == NULL)
{
printf("can't open file!\n");
exit(0);
}
i = 0;
while (i < n)
{
fputc(a[i], fp);//在循环里,这条语句把数组a的所有字符写到文件指针变量fp所指向的文件C.txt中
putchar(a[i]);//在循环里,这条语句把数组a的所有字符显示到屏幕上
i++;
}
fclose(fp);//关闭文件test3,防止它被误用
putchar('\n');
return 0;
}