public member function
<fstream>

std::basic_filebuf::open

basic_filebuf* open (const char* filename,  ios_base::openmode mode);
basic_filebuf* open (const char* filename,  ios_base::openmode mode);basic_filebuf* open (const string filename, ios_base::openmode mode);
Open file
Opens the file identified by argument filename, associating its content with the file stream buffer object to perform input/output operations on it. The operations allowed and some operating details depend on parameter mode.

If the object is already associated with a file (i.e., it is already open), this function fails.

Parameters

filename
String with the name of the file to open.
mode
Flags describing the requested input/output mode for the file.
This is an object of the bitmask type ios_base::openmode that consists of a combination of the following constants:
valuestands foraccess
ios_base::ininputFile open for reading, supporting input operations.
ios_base::outoutputFile open for writing, supporting output operations.
ios_base::binarybinaryOperations are performed in binary mode rather than text.
ios_base::ateat endThe put pointer (pptr) starts at the end of the controlled output sequence.
ios_base::appappendAll output operations happen at the end of the file, appending to its existing contents.
ios_base::trunctruncateAny contents that existed in the file before it is open are discarded.
These flags can be combined with the bitwise OR operator (|).

If the mode has both ios_base::trunc and ios_base::app set, the opening operation fails. It also fails if either is set but ios_base::out is not, or if both ios_base::app and ios_base::in are set.
If the mode has both ios_base::trunc and ios_base::app set, the opening operation fails. It also fails if ios_base::trunc is set but ios_base::out is not.

Return Value

The function returns this if successful.
In case of failure, the file is not open, and a null pointer is returned.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// filebuf::open()
#include <iostream>
#include <fstream>

int main () {
  std::ifstream is;
  std::filebuf * fb = is.rdbuf();

  fb->open ("test.txt",std::ios::out|std::ios::app);

  // >> appending operations here <<

  fb->close();

  return 0;
}

Data races

Modifies the basic_filebuf object.
Concurrent access to the same file stream buffer object may introduce data races.

Exception safety

Basic guarantee: if an exception is thrown, the file stream buffer is in a valid state.

See also