C++ Fstream Library - Open Function


Opens the file identified by argument filename, associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode.


Following is the declaration for fstream::open.


void open (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out);


void open (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out);
void open (const string& filename,ios_base::openmode mode = ios_base::in | ios_base::out);


  • filename − String with the name of the file to open,Specifics about its format and validity depend on the library implementation and running environment.

  • mode − Flags describing the requested input/output mode for the file.

Return Value

  • none

  • If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).


  • Basic guarantee − if an exception is thrown, the stream is in a valid state.

  • It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state.

Data races

  • Modifies the fstream object.

  • Concurrent access to the same stream object introduce data races.


In below example explains about fstream open function.

#include <fstream>

int main () {

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

   fs << " more lorem ipsum";


   return 0;