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.
Examples:
Input:
file1.text
This is line one in file1
Hello World.
file2.text
This is line one in file2
Programming is fun.
Output:
This is line one in file2
Programming is fun.
This is line one in file1
Hello World.
Approach:
- 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.
- Explicitly write a newline (“\n”) to the destination file to enhance readability.
- Write content from source file to destination file.
- Display the contents in file2.txt to console (stdout).
C
#include <stdio.h>
void appendFiles( char source[],
char destination[])
{
FILE *fp1, *fp2;
fp1 = fopen (source, "a+" );
fp2 = fopen (destination, "a+" );
if (!fp1 && !fp2) {
printf ( "Unable to open/"
"detect file(s)\n" );
return ;
}
char buf[100];
fprintf (fp2, "\n" );
while (! feof (fp1)) {
fgets (buf, sizeof (buf), fp1);
fprintf (fp2, "%s" , buf);
}
rewind (fp2);
while (! feof (fp2)) {
fgets (buf, sizeof (buf), fp2);
printf ( "%s" , buf);
}
}
int main()
{
char source[] = "file1.txt" ,
destination[] = "file2.txt" ;
appendFiles(source, destination);
return 0;
}
|
Output:
Below is the output of the above program:
Time Complexity: O(N)
Auxiliary Space Complexity: O(1)
Last Updated :
24 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...