C program to append the content of one file to the end of another file

Here, we are going to learn how to append the content of one file to the end of another file using C program? By Nidhi Last updated : March 10, 2024

Problem statement

Given a file, we have to append the content of this existing file to the end of another exiting text file and then print the modified content of the file.

C program to append the content of one file to the end of another file

The source code to append the content of one file to the end of another file is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to append the content of one file
// to the end of another file

#include <stdio.h>
#include <string.h>
int main()
{
    FILE* fp1;
    FILE* fp2;
    char ch;

    fp1 = fopen("file1.txt", "r+");
    if (fp1 == NULL) {
        printf("\nUnable to open file\n");
        return -1;
    }

    fp2 = fopen("file2.txt", "r");
    if (fp2 == NULL) {
        printf("\nUnable to open file\n");
        return -1;
    }

    printf("\nContent of file1: \n");
    ch = getc(fp1);
    while (ch != EOF) {
        printf("%c", ch);
        ch = getc(fp1);
    }

    printf("\nContent of file2: \n");
    ch = getc(fp2);
    while (ch != EOF) {
        printf("%c", ch);
        ch = getc(fp2);
    }

    fseek(fp2, 0, SEEK_SET);

    ch = getc(fp2);
    while (ch != EOF) {
        putc(ch, fp1);
        ch = getc(fp2);
    }
    fclose(fp2);

    fseek(fp1, 0, SEEK_SET);
    printf("\nModified content of file1:\n");
    ch = getc(fp1);
    while (ch != EOF) {
        printf("%c", ch);
        ch = getc(fp1);
    }

    fclose(fp1);

    printf("\n");

    return 0;
}

Output

Content of file1: 
This is Line1 from file1
This is Line2 from file1
This is Line3 from file1

Content of file2: 
This is Line1 from file2
This is Line2 from file2
This is Line3 from file2


Modified content of file1:
This is Line1 from file1
This is Line2 from file1
This is Line3 from file1
This is Line1 from file2
This is Line2 from file2
This is Line3 from file2

Explanation

Here, we opened two existing files "file1.txt" and "file2.txt". Then copy the content of "file2.txt" to the end of "file1.txt". After that, we printed the content of the modified "file1.txt" on the console screen.

C File Handling Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.