Appending to a file means adding new data at the end of an existing file without overwriting its current contents. In C++, file appending can be performed using the <fstream> library by opening a file in append mode (ios::app).
- ios::app ensures that all new data is written at the end of the file.
- Both ofstream and fstream can be used to append data to an existing file.
Suppose the file "Geeks for Geeks.txt" initially contains:
Geeks for Geeks
Append a String Using ofstream
The ofstream class is used for output file operations. Opening a file with the ios::app flag appends new data instead of replacing the existing content.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream of;
fstream f;
// Open file in append mode
of.open("Geeks for Geeks.txt", ios::app);
if (!of)
cout << "No such file found";
else {
of << " String";
cout << "Data appended successfully\n";
of.close();
string word;
// Read and display updated file
f.open("Geeks for Geeks.txt");
while (f >> word)
cout << word << " ";
f.close();
}
return 0;
}
Output
Data appended successfully String
Explanation
- ofstream opens the file in append mode using ios::app.
- The string " String" is added to the end of the file.
- The file is then reopened using fstream to display the updated contents.
Append a String Using fstream
The fstream class supports both input and output operations. It can also append data when opened with the ios::app flag.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
fstream f;
// Open file in append mode
f.open("Geeks for Geeks.txt", ios::app);
if (!f)
cout << "No such file found";
else {
f << " String_fstream";
cout << "Data appended successfully\n";
f.close();
string word;
// Read and display updated file
f.open("Geeks for Geeks.txt");
while (f >> word)
cout << word << " ";
f.close();
}
return 0;
}
Output
Data appended successfully String_fstream
Explanation
- fstream opens the file using the ios::app flag.
- The string " String_fstream" is appended to the existing file contents.
- The updated contents of the file are then displayed.
Difference Between ofstream and fstream
| Feature | ofstream | fstream |
|---|---|---|
| Purpose | Output operations only | Input and output operations |
| Supports append mode | Yes | Yes |
| Supports reading | No | Yes |
| Typical use case | Writing/appending data | Reading and writing the same file |