1. 编程学习网 > 编程教程 > C语言教程 > C语言经典案例:有两个磁盘文件A和B,各存放一行字母,要求把这两

C语言经典案例:有两个磁盘文件A和B,各存放一行字母,要求把这两

需求描写:有两个磁盘文件A和B,各寄存一行字母,请求把这两个文件中的信息归并(按字母次序分列),输入到一个新文件C中。

C语言案例剖析:你须要先创立 A.txt 与 B.txt。

A.txt文件内容:

123

B.txt文件内容:

456

程序源代码:

实现代码如下:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

{

FILE*fa,*fb,*fc;

int i,j,k;

char str[100],str1[100];

char tem;

if((fa=fopen("A.txt","r"))==NULL) // A.txt 文件须要存在

{

printf("error: cannot open A file!\n");

exit(0);

}

fgets(str,99,fa);

fclose(fa);

if((fb=fopen("B.txt","r"))==NULL) // B.txt 文件须要存在

{

printf("error: cannot open B file!\n");

exit(0);

}

fgets(str1,100,fb);

fclose(fb);

strcat(str,str1);

for(i=strlen(str)-1;i>1;i--)

for(j=0;j<i;j++)

if(str[j]>str[j+1])

{

tem=str[j];

str[j]=str[j+1];

str[j+1]=tem;

}

if((fc=fopen("C.txt","w"))==NULL) // 归并为 C.txt

{

printf("error: cannot open C file!\n");

exit(0);

}

fputs(str,fc);

fclose(fc);

system("pause");

return 0;

}

以上实例运行输入结果后,翻开 C.txt 内容如下:

123456

本文由IT教学网整理发布,转载请注明出处:http://www.itjx.com/jiaocheng/cyuyan/968.html

联系我们

在线咨询:点击这里给我发消息

咨询电话:400-998-2681

工作时间:7*24小时无休