C++ program to append content of one text file to another
Last Updated :
23 Nov, 2022
Given source and destination text files. Append the content from the source file to the destination file and then display the content of the destination file.
Example :
Input : file.txt : "geeks", file2.txt : "geeks for"
Output: file2.txt : "geeks for geeks"
Method 1:
Approach:
- Open file.txt in inputstream and file2.txt in outputstream with the append option, so that the previous content of the file are not deleted.
- Check if there’s an error in opening or locating a file. If yes, then throw an error message.
- If both files are found, then write content from the source file to the destination file.
- Display the content of the destination file.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream file;
ifstream ifile( "file.txt" , ios::in);
ofstream ofile( "file2.txt" , ios::out | ios::app);
if (!ifile.is_open()) {
cout << "file not found" ;
}
else {
ofile << ifile.rdbuf();
}
string word;
file.open( "file2.txt" );
while (file >> word) {
cout << word << " " ;
}
return 0;
}
|
Method 2: We can do the same using different functions mentioned below:
- fopen(): Returns a pointer to the object that controls the opened file stream
- fprintf(): Writes the string pointed by format to the stream
- fclose(): Closes the file associated with the stream and disassociates it.
- fgetc(): Returns the character currently pointed by the internal file position indicator of the specified stream
Approach:
- Open source file in read mode and destination file in append mode using fopen()
- check if they exist
- Iterate every character of the source file using fgetc() and print it to the destination file using fprintf() with while loop
- Close both files using fclose()
- Open destination file in read mode
- print it
- close it
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
FILE * file = fopen ( "file.txt" , "r" );
FILE * file2 = fopen ( "file2.txt" , "a" );
if (file2 == NULL) {
cout << "file not found" ;
return 1;
}
else if (file == NULL) {
cout << "file not found" ;
return 1;
}
char ch = fgetc (file);
while (ch != EOF) {
fprintf (file2, "%c" , ch);
ch = fgetc (file);
}
fclose (file);
fclose (file2);
FILE * file3 = fopen ( "file2.txt" , "r" );
char ch2 = fgetc (file3);
while (ch2 != EOF) {
printf ( "%c" , ch2);
ch2 = fgetc (file3);
}
fclose (file3);
}
|
Share your thoughts in the comments
Please Login to comment...