C++ Fstream Library - Open Function


Advertisements

Description

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.

Declaration

Following is the declaration for fstream::open.

C++98

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

C++11

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);

Parameters

  • 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).

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.

Example

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";

   fs.close();

   return 0;
}
fstream.htm
Advertisements