Mark As Completed Discussion

Appending to Files

When working with files in C++, you may often need to append data to an existing file. Appending means adding new data to the end of the file without overwriting the existing content.

To append data to a file in C++, you can use the ofstream class along with the ios::app flag. The ios::app flag is used to open the file in append mode.

Here's an example code that demonstrates how to append data to a file using ofstream:

TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3
4int main() {
5  std::ofstream file("example.txt", std::ios::app);
6
7  if (file.is_open()) {
8    file << "This is an appended line";
9    file.close();
10    std::cout << "Data appended to file." << std::endl;
11  } else {
12    std::cout << "Unable to open file" << std::endl;
13  }
14
15  return 0;
16}

In this code, we include the necessary libraries iostream and fstream. We then declare an ofstream object named file and pass the name of the file we want to append to as a parameter.

Using the ios::app flag in the file opening statement, we open the file in append mode. Then, we use the << operator to append the desired data, in this case, the string "This is an appended line".

Finally, we close the file using the close() function and print a success message to the console.

Appending to files can be useful when you want to add new data to an existing file without affecting the previously stored data.

Keep in mind that if the file does not exist, it will be created when opened in append mode.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment