How to Append to File in C++: Simple Guide with Examples
To append to a file in C++, open the file using
std::ofstream with the std::ios::app flag. This mode adds new content at the end of the file without deleting existing data.Syntax
Use std::ofstream with the std::ios::app flag to open a file for appending. This means new data will be added at the end of the file.
std::ofstream file;creates a file stream object.file.open("filename.txt", std::ios::app);opens the file in append mode.- Writing to
fileadds content at the end. file.close();closes the file when done.
cpp
std::ofstream file; file.open("filename.txt", std::ios::app); file << "Text to append"; file.close();
Example
This example opens a file named example.txt in append mode and adds a new line of text. If the file does not exist, it will be created.
cpp
#include <iostream> #include <fstream> int main() { std::ofstream file("example.txt", std::ios::app); if (!file) { std::cerr << "Error opening file." << std::endl; return 1; } file << "Appended line\n"; file.close(); std::cout << "Text appended successfully." << std::endl; return 0; }
Output
Text appended successfully.
Common Pitfalls
Common mistakes when appending to files include:
- Not using
std::ios::appmode, which overwrites the file instead of appending. - Forgetting to check if the file opened successfully.
- Not closing the file, which may cause data loss or corruption.
cpp
#include <fstream> // Wrong way: overwrites file instead of appending std::ofstream file_wrong("file.txt"); file_wrong << "This will overwrite existing content."; file_wrong.close(); // Right way: appends to file std::ofstream file_right("file.txt", std::ios::app); file_right << "This will add to the end."; file_right.close();
Quick Reference
| Action | Code Example |
|---|---|
| Open file for appending | std::ofstream file("file.txt", std::ios::app); |
| Write text | file << "New text"; |
| Close file | file.close(); |
| Check if file opened | if (!file) { /* handle error */ } |
Key Takeaways
Always open the file with std::ios::app to append without erasing existing content.
Check if the file opened successfully before writing to avoid errors.
Close the file after writing to ensure data is saved properly.
Appending creates the file if it does not exist.
Using std::ofstream without std::ios::app overwrites the file instead of appending.