c++ open file with code example

Example 1: opening file in c++

/ fstream::open / fstream::close
#include <fstream>      // std::fstream

int main () {

  std::fstream fs;
  fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);

  fs << " more lorem ipsum";

  fs.close();

  return 0;
}

Example 2: file open cpp

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("file.txt");
  myfile << "Writing to a file.\n";
  myfile.close();
  return 0;
}

Tags:

Cpp Example