Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print the list of files of a director... >>
<< C program to replace the specified line in an exis...