C program to append content of one text file to another

Pre-requisite: File Handling in C

Given the source and destination text files, the task is to append the content from source file to destination file and then display the content of the destination file.


This is line one in file1
Hello World.
This is line one in file2
Programming is fun.

This is line one in file2
Programming is fun.
This is line one in file1
Hello World.


  1. Open file1.txt and file2.txt with “a+”(append and read) option, so that the previous content of the file is not deleted. If files don’t exist, they will be created.
  2. Explicitly write a newline (“\n”) to the destination file to enhance readability.
  3. Write content from source file to destination file.
  4. Display the contents in file2.txt to console (stdout). 






// C program to append the contents of
// source file to the destination file
// including header files
#include <stdio.h>
// Function that appends the contents
void appendFiles(char source[],
                 char destination[])
    // declaring file pointers
    FILE *fp1, *fp2;
    // opening files
    fp1 = fopen(source, "a+");
    fp2 = fopen(destination, "a+");
    // If file is not found then return.
    if (!fp1 && !fp2) {
        printf("Unable to open/"
               "detect file(s)\n");
    char buf[100];
    // explicitly writing "\n"
    // to the destination file
    // so to enhance readability.
    fprintf(fp2, "\n");
    // writing the contents of
    // source file to destination file.
    while (!feof(fp1)) {
        fgets(buf, sizeof(buf), fp1);
        fprintf(fp2, "%s", buf);
    // printing contents of
    // destination file to stdout.
    while (!feof(fp2)) {
        fgets(buf, sizeof(buf), fp2);
        printf("%s", buf);
// Driver Code
int main()
    char source[] = "file1.txt",
         destination[] = "file2.txt";
    // calling Function with file names.
    appendFiles(source, destination);
    return 0;



Below is the output of the above program: 


Time Complexity: O(N) 
Auxiliary Space Complexity: O(1) 


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : nidhi_biet

Article Tags :
Practice Tags :


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.