C Practice Example 99
Title:There are two disk files A and B, each storing a line of letters. The information in these two files is required to be merged (arranged in alphabetical order) and output to a new file C.
Program analysis:You need to create A.txt and B.txt first.
Contents of file A.txt:
123
Contents of file B.txt:
456
Program source code:
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. 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 file must exist
{
printf("error: cannot open A file!\n");
exit(0);
}
fgets(str,99,fa);
fclose(fa);
if((fb=fopen("B.txt","r"))==NULL) // B.txt file must exist
{
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) // Merge into 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 and generating the output, open C.txt and its contents are as follows:
123456other extensions