Append to File
Appending Data to a File in C++
BeginnerTopic: File Handling Programs
C++ Append to File Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Open file in append mode
ofstream outFile("data.txt", ios::app);
if (outFile.is_open()) {
// Append data to existing file
outFile << "\nAppended line 1" << endl;
outFile << "Appended line 2" << endl;
outFile << "Appended line 3" << endl;
outFile.close();
cout << "Data appended to file successfully!" << endl;
} else {
cout << "Error: Unable to open file for appending." << endl;
}
// Read and display updated file
ifstream inFile("data.txt");
if (inFile.is_open()) {
string line;
cout << "\nUpdated file contents:" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;
}Output
Data appended to file successfully! Updated file contents: Hello, World! This is a C++ file handling program. Line 3: Learning file operations. 100 200 300 Appended line 1 Appended line 2 Appended line 3
Understanding Append to File
Appending to a file uses ios: :app mode flag with ofstream. This mode adds data to the end of the file without overwriting existing content. Use ios::app for append mode, ios::out for write mode (default), ios::in for read mode. Multiple flags can be combined using | operator.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.