C 实战练习题目99

题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件C中。

程序分析:你需要先创建 A.txt 与 B.txt。

A.txt文件内容:

123

B.txt文件内容:

456

程序源代码:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 int main()
 5 {
 6     FILE*fa,*fb,*fc;
 7     int i,j,k;
 8     char str[100],str1[100];
 9     char tem;
10     if((fa=fopen("A.txt","r"))==NULL) // A.txt 文件需要存在
11     {
12         printf("error: cannot open A file!\n");
13         exit(0);
14     }
15     fgets(str,99,fa);
16     fclose(fa);
17     if((fb=fopen("B.txt","r"))==NULL)  // B.txt 文件需要存在
18     {
19         printf("error: cannot open B file!\n");
20         exit(0);
21     }
22     fgets(str1,100,fb);
23     fclose(fb);
24     strcat(str,str1);
25     for(i=strlen(str)-1;i>1;i--)
26         for(j=0;j<i;j++)
27             if(str[j]>str[j+1])
28             {
29                 tem=str[j];
30                 str[j]=str[j+1];
31                 str[j+1]=tem;
32             }
33     
34     if((fc=fopen("C.txt","w"))==NULL)  // 合并为 C.txt
35     {
36         printf("error: cannot open C file!\n");
37         exit(0);
38     }
39     fputs(str,fc);
40     fclose(fc);
41     system("pause");
42     return 0;
43 }

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

123456

感谢你的阅读,请用心感悟!希望可以帮到爱学习的你!!分享也是一种快乐!!!请接力。。。

点击查看原文,谢谢!

posted @ 2020-08-13 21:41  C语言自学网  阅读(203)  评论(0编辑  收藏  举报