![]() |
VOOZH | about |
Merging two files into a third file means copying the data of the two files and pasting them into the third file one after another. In this article, we will learn how to merge the contents of two files using a C program.
The simplest method to merge two files into a third file is by first reading the data from one file character by character using fgetc() and printing it to the third file using fputc(). Then reading the second file using the same method and print to the end of the third file.
Let's take a look at an example:
Assume that following is the content of the files:
file1.txt
This is the first file.
and its datafile2.txt
This is the second file and
its dataThen the merged.txt will be generated as:
This is the first file.
and its dataThis is the second file and
its dataOutput
Contents Merged SuccessfullyExplanation: The program opens file1.txt and file2.txt in read mode ("r") and merged.txt in write mode ("w"). It reads one character at a time from file1.txt using fgetc() and writes it to merged.txt using fputc(). After reaching the end of file1.txt, the same process is repeated for file2.txt.
The above method works well for text files, but it may break in some cases for binary files due to character conversions by fgetc() to fputc(). But C also provide methods to properly read and write binary data.
If first and second files are binary files, then fread() and fwrite() are more efficient as compared to fgetc() and fputc(). The whole process will remain same as the above.
Output
Contents Merged Successfully