Append to File in C++

Append to a file in C++ with ios::app: add lines without erasing old data, see where the blank line comes from, then read the updated file back with getline.

BeginnerFile Handling ProgramsExample 3 of 6
append-to-file.cpp
1#include <iostream>
2#include <fstream>
3using namespace std;
4
5int main() {
6 // Open file in append mode
7 ofstream outFile("data.txt", ios::app);
8
9 if (outFile.is_open()) {
10 // Append data to existing file
11 outFile << "\nAppended line 1" << endl;
12 outFile << "Appended line 2" << endl;
13 outFile << "Appended line 3" << endl;
14
15 outFile.close();
16 cout << "Data appended to file successfully!" << endl;
17 } else {
18 cout << "Error: Unable to open file for appending." << endl;
19 }
20
21 // Read and display updated file
22 ifstream inFile("data.txt");
23 if (inFile.is_open()) {
24 string line;
25 cout << "\nUpdated file contents:" << endl;
26 while (getline(inFile, line)) {
27 cout << line << endl;
28 }
29 inFile.close();
30 }
31
32 return 0;
33}

Sample Output

(blank line)

The leading \n of the first append.

Appended line 3

The last line written in this run.

In this one

  • How ios::app keeps existing content
  • Why the leading \n creates a blank line
  • Why you close the writer before reading
  • How append mode behaves on repeated runs

How it works

  1. 1

    Open data.txt with ios::app.

  2. 2

    Write "\nAppended line 1" and two more lines.

  3. 3

    close() to flush.

  4. 4

    Reopen with ifstream and print every line.

Dry run: Append to File

Before: 4 lines, ending with "100 200 300

  1. 1."
  2. 2.Write "
  3. 3.Appended line 1
  4. 4." → an empty line, then line 1
  5. 5.Write "Appended line 2
  6. 6.", "Appended line 3
  7. 7."
  8. 8.After: 4 + 1 blank + 3 = 8 lines
Before: 4 lines, ending with "100 200 300
"
Write "
Appended line 1
" → an empty line, then line 1
Write "Appended line 2
", "Appended line 3
"
After: 4 + 1 blank + 3 = 8 lines

Edge cases

File does not exist

Delete data.txt first.

ios::app creates it, so the file starts with an empty line followed by the three appended lines.

Running repeatedly

Run three times.

Each run adds four more lines (a blank plus three). Nothing is ever removed.

What's going on

Appending adds new data to the end of a file and keeps what is already there. The only change from writing is the mode flag: ofstream outFile("data.txt", ios::app);.

With ios::app, every write goes to the end of the file, and the file is created if it does not exist. Without it, ofstream would wipe the file first.

The first appended string starts with `

. data.txt already ends with a newline (file-write used endl), so this extra

adds an empty line before "Appended line 1". You can see that blank line in the output after "100 200 300". If you do not want it, drop the leading

`.

After closing the writer, the program reopens the file with ifstream and prints it line by line with getline. That shows the four original lines, the blank line, and the three new ones.

Closing outFile before reading matters. Output is buffered, and until the buffer is flushed the reader might not see the new lines yet. close() flushes.

Each run appends three more lines. Run it twice and the file grows to fifteen lines (with two blank ones), which is the expected behaviour of append mode and an easy way to see the difference from file-write.

The sample output assumes file-write ran once just before. If data.txt did not exist, it would contain only the blank line and the three appended lines.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ofstream, ifstream). Leave one out and the compiler stops at the first name it does not recognize.

Understanding File Appending

Append Mode Concept:

Adds data to end of file
Preserves existing content
File pointer starts at end
Creates file if doesn't exist

File Modes:

ios::app: append mode (adds to end)
ios::out: write mode (overwrites, default)
ios::in: read mode
Can combine: ios::app | ios::out

Opening File in Append Mode

Using ios::app:

ofstream outFile("data.txt", ios::app);

What happens here:

Opens file in append mode
File pointer at end of file
New data added after existing
Creates file if doesn't exist

Checking Success:

if (outFile.is_open()) {

// File opened successfully

}

Appending Data

Writing in Append Mode:

outFile << "\nAppended line 1" << endl;

outFile << "Appended line 2" << endl;

What happens here:

Data written at end of file
Existing content preserved
Newlines separate additions
Sequential appending

Verifying Appended Content

Reading File:

ifstream inFile("data.txt");

string line;

while (getline(inFile, line)) {

cout << line << endl;

}

What happens here:

Read entire file
Shows original + appended content
Verifies append operation
Confirms data preservation

When to Use Append Mode

Good fits:

Logging events
Adding records
Preserving existing data
Building files incrementally
Appending to logs

Example Scenarios:

Event logging
Adding user data
Building reports
Appending to logs
Incremental data collection

Important Considerations

Append vs Write:

Append: adds to end (preserves data)
Write: overwrites (loses data)
Choose based on requirement
Be careful with mode selection

File Position:

Append mode: pointer at end
Write mode: pointer at beginning
New data always added at end in append
Cannot insert in middle

Newlines:

Add newlines between appends
Use endl or "\n"
Maintains file formatting
Prevents data concatenation

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which mode keeps old contents and writes at the end?

Pick an answer to check it.

Question 2

Why is there an empty line after "100 200 300"?

Pick an answer to check it.

Questions people ask

What is the difference between ios::app and ios::ate?

app forces every write to the end. ate only starts at the end; you can seek elsewhere and write there.

Can I append with fstream?

Yes: fstream f("data.txt", ios::in | ios::out | ios::app);

Is appending safe if two programs write at once?

Not with plain fstream; lines can interleave. Use one writer or file locking.