In this tutorial, we will write a C Program to merge the contents of two files into a third file. Before that, you may go through the following C topics.
Explanation: The program will ask for the two names of the file from where the content is copied and then ask for the third file name where both the files are concatenated and copied there. If the third file is not present then the program will automatically create a file with the entered name.
Lastly, check the third file which will be present in the same directory as the source code.
C Program to Merge Two Files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <stdio.h> #include <stdlib.h> int main() { FILE *fp1, *fp2, *fp3; char ch, file1[20], file2[20], file3[20]; printf("Enter the first file name: "); gets(file1); printf("Enter the second file name: "); gets(file2); printf("Enter the file name where you want ot store: "); gets(file3); fp1 = fopen(file1, "r"); fp2 = fopen(file2, "r"); if (fp1 == NULL || fp2 == NULL) { perror("Error "); exit(0); } // Opening in write mode fp3 = fopen(file3, "w"); if (fp3 == NULL) { perror("Error "); exit(0); } while ((ch = fgetc(fp1)) != EOF) fputc(ch, fp3); while ((ch = fgetc(fp2)) != EOF) fputc(ch, fp3); printf("\n%s and %s are merges to %s successfully.\n", file1, file2, file3); fclose(fp1); fclose(fp2); fclose(fp3); return 0; } |
Output:
Before and after the execution, all the files will look like following:
Before:
file1.txt:
Hello World!
file2.txt
This is simple2code.com.
After:
file3.txt
Hello World!
This is simple2code.com.
The above program to merge the content of two files in C is successfully tested in a machine.