0
0
CppHow-ToBeginner · 3 min read

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 file adds 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::app mode, 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

ActionCode Example
Open file for appendingstd::ofstream file("file.txt", std::ios::app);
Write textfile << "New text";
Close filefile.close();
Check if file openedif (!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.