Easy Tutorial
❮ C Examples Palindrome Number C Function Tanh ❯

C Exercise Example 99

C Language Classic 100 Examples

Title: There are two disk files, A and B, each containing a line of letters. The requirement is to merge the information from these two files (sorted alphabetically) and output it to a new file, C.

Program Analysis: You need to create A.txt and B.txt first.

Contents of A.txt:

123

Contents of B.txt:

456

Program Source Code:

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015年 tutorialpro.org. 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&lt;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)  // Merged 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 opening C.txt, the contents are as follows:

123456

C Language Classic 100 Examples

❮ C Examples Palindrome Number C Function Tanh ❯