C Exercise Example 99
100 cases of classic C language
Title: There are two disk files A and B, each store his letters, requested information from these two documents combined (in alphabetical order), output to a new file in C.
Program Analysis: You need to create A.txt and B.txt.
A.txt contents of the file:
123
B.txt contents of the file:
456
Source Code:
// Created by www.w3big.com on 15/11/9. // Copyright © 2015年 本教程. All rights reserved. // #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; }
After running the above example output, open C.txt reads as follows:
123456