Scroll to navigation

std::basic_fstream::open(3) C++ Standard Libary std::basic_fstream::open(3)

NAME

std::basic_fstream::open - std::basic_fstream::open

Synopsis


void open( const char* filename,


std::ios_base::openmode mode (1)


= std::ios_base::in | std::ios_base::out );
void open( const std::filesystem::path::value_type* filename,


std::ios_base::openmode mode (2) (since C++17)


= std::ios_base::in | std::ios_base::out );
void open( const std::string& filename,


std::ios_base::openmode mode (3) (since C++11)


= std::ios_base::in | std::ios_base::out );
void open( const std::filesystem::path& filename,


std::ios_base::openmode mode (4) (since C++17)


= std::ios_base::in | std::ios_base::out );


Opens and associates the file with name filename with the file stream.


Calls clear() on success. Calls setstate(failbit) on failure.


1,2) Effectively calls rdbuf()->open(filename, mode) (see std::basic_filebuf::open
for the details on the effects of that call).
Overload (2) is only provided if std::filesystem::path::value_type is not char.
(since C++17)
3,4) Effectively calls (1,2) as if by open(filename.c_str(), mode).

Parameters


filename - the name of the file to be opened
specifies stream open mode. It is a BitmaskType, the following constants
are defined:


Constant Explanation
app seek to the end of stream before each write
mode - binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open
noreplace (C++23) open in exclusive mode

Return value


(none)

Example

// Run this code


#include <fstream>
#include <iostream>
#include <string>


int main()
{
std::string filename = "example.123";


std::fstream fs;
fs.open(filename);


if (!fs.is_open())
{
fs.clear();
fs.open(filename, std::ios::out); // create file
fs.close();
fs.open(filename);
}


std::cout << std::boolalpha;
std::cout << "fs.is_open() = " << fs.is_open() << '\n';
std::cout << "fs.good() = " << fs.good() << '\n';
}


Defect reports


The following behavior-changing defect reports were applied retroactively to
previously published C++ standards.


DR Applied to Behavior as published Correct behavior
LWG 22 C++98 it was unclear how error state changes upon a the error state is
successful open unchanged
LWG 409 C++98 the error state was unchanged upon a it is cleared^[1]
successful open
LWG 460 C++98 the default argument of mode in overload (1) added
was missing (it is present in the synopsis)


1. ↑ The resolution of LWG issue #22 is overriden.

See also


is_open checks if the stream has an associated file
(public member function)
close closes the associated file
(public member function)
open opens a file and configures it as the associated character sequence
(public member function of std::basic_filebuf<CharT,Traits>)

2024.06.10 http://cppreference.com