C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Merge two files into one

C Program: Merge two files into one

C

#include <stdio.h>

 

int main() {

    FILE *file1, *file2, *file3;

    char filename1[100], filename2[100], filename3[100];

    char ch;

 

    // Step 1: Get filenames from user

    printf("Enter name of first file: ");

    scanf("%s", filename1);

 

    printf("Enter name of second file: ");

    scanf("%s", filename2);

 

    printf("Enter name of output file: ");

    scanf("%s", filename3);

 

    // Step 2: Open first two files in read mode

    file1 = fopen(filename1, "r");

    file2 = fopen(filename2, "r");

 

    // Step 3: Open third file in write mode

    file3 = fopen(filename3, "w");

 

    // Step 4: Validate file opening

    if (file1 == NULL || file2 == NULL || file3 == NULL) {

        printf("Error opening files. Please check filenames.\n");

        return 1;

    }

 

    // Step 5: Copy contents of first file into output file

    while ((ch = fgetc(file1)) != EOF)

        fputc(ch, file3);

 

    // Step 6: Copy contents of second file into output file

    while ((ch = fgetc(file2)) != EOF)

        fputc(ch, file3);

 

    // Step 7: Close all files

    fclose(file1);

    fclose(file2);

    fclose(file3);

 

    printf("\nFiles '%s' and '%s' merged into '%s' successfully.\n", filename1, filename2, filename3);

 

    return 0;

}

Output

 
File 1  (a.txt) :
Hello,
This is File A.

File 2  (b.txt) : 
Welcome to File B.

Output File  (merged.txt) : 
Hello,
This is File A.
Welcome to File B.

Output Message:
Files 'a.txt' and 'b.txt' merged into 'merged.txt' successfully.

Explanation

Step

Description

1

Accepts names of two input files and one output file.

2

Opens input files in "r" (read) mode.

3

Opens output file in "w" (write) mode.

4

Uses fgetc() to read each character and fputc() to write it.

5

First copies all characters from file1, then from file2.

6

Closes all files properly.