Concatenate Two Files in C Programming

In this tutorial, we shall learn to use File Pointers to concatenate two files. Often there could be situations when a single large file could not be sent over network or generated by a program, resulting in file parts. To merge these file parts, we can use C programming language.

Following is a list of high level steps that are applied in the C program to merge two files.

To concatenate two files in C Programming :

  • Open the files which we want to merge, using fopen()
  • Read the content of each file character by character using fgetc()
  • Store the read content in the output file using fputc()
  • At the end, content of two files will be merged and will be stored output file.

Example Concatenate Two Files

In the following program, we will concatenate two files file1 and file2, and store the result in file3.

C Program

#include <stdio.h>
#include <stdlib.h>

int main() {
	FILE *f1, *f2, *f3;

	char ch, file1[30], file2[30], file3[30];

	printf("Enter name of first file\n");
	gets(file1);

	printf("Enter name of second file\n");
	gets(file2);

	printf("Enter name of the output files\n");
	gets(file3);

	f1 = fopen(file1, "r");   //opening the file for reading.
	f2 = fopen(file2, "r");

	if(f1 == NULL || f2 == NULL) {
		perror("Error ");
		printf("Press any key to exit...\n");
		exit(EXIT_FAILURE);
	}

	f3 = fopen(file3, "w");          // Opening in write mode

	if(f3 == NULL) {
		perror("Error ");
		printf("Press any key to exit...\n");
		exit(EXIT_FAILURE);
	}

	while((ch = fgetc(f1)) != EOF)
		fputc(ch,f3);

	while((ch = fgetc(f2)) != EOF)
		fputc(ch,f3);

	printf("The two files were merged into %s file successfully.\n", file3);

	fclose(f1);
	fclose(f2);
	fclose(f3);

	return 0;
}

Conclusion

In this C Tutorial – we have learnt to concatenate two file using File Pointers of C Programming.