OPEN()

The open() function is used with file stream objects, such as ofstream, ifstream, or fstream, to associate the stream with a specific file. If the file does not already exist, it will be created automatically. You can also combine file modes with open(), such as ios::app for appending or ios::binary for binary files, to control how the file is accessed and written.

// For ofstream and fstream (writing)
void open(const char* filename, ios::openmode mode = ios::out);

// For ifstream and fstream (reading)
void open(const char* filename, ios::openmode mode = ios::in);
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
  string filename = "my_file.txt";
  ofstream file_stream;

  // Open the file in append mode
  file_stream.open(filename, ios::app);

  // Check if the file was opened successfully (like we always should!)
  if (file_stream.is_open()) {
    cout << "File opened for appending." << endl;

    // Write some new text to the end of the file
    file_stream << "This is some new text appended to the file.\n";
    file_stream << "Another line of appended text.\n";

    // Close the file (very important!)
    file_stream.close();
    cout << "File closed." << endl;
  } else {
    cout << "Unable to open file for appending." << endl;
  }

  return 0;
}

Last updated