std::basic_filebuf<CharT,Traits>::open

If the associated file was already open (is_open() != false), returns a null pointer right away.

# Declarations

basic_filebuf* open( const char* s, std::ios_base::openmode mode );
basic_filebuf* open( const std::string& str, std::ios_base::openmode mode );

(since C++11)

basic_filebuf* open( const std::filesystem::path& p,
std::ios_base::openmode mode );

(since C++17)

basic_filebuf* open( const std::filesystem::path::value_type* s,
std::ios_base::openmode mode );

(since C++17)

# Parameters

# Return value

this on success, a null pointer on failure.

# Notes

open() is typically called through the constructor or the open() member function of std::basic_fstream.

# Example

#include <fstream>
#include <iostream>
 
int main()
{
    std::string filename = "Test.b";
    std::filebuf fb;
 
    // prepare a file to read
    double d = 3.14;
    if (!fb.open(filename, std::ios::binary | std::ios::out))
    {
        std::cout << "Open file " << filename << " for write failed\n";
        return 1;
    } 
    fb.sputn(reinterpret_cast<char*>(&d), sizeof d);
    fb.close();
 
    // open file for reading
    double d2 = 0.0;
    if (!fb.open(filename, std::ios::binary | std::ios::in))
    {
        std::cout << "Open file " << filename << " for read failed\n";
        return 1;
    }
 
    auto got = fb.sgetn(reinterpret_cast<char*>(&d2), sizeof d2);
    if (sizeof(d2) != got)
        std::cout << "Read of " << filename << " failed\n";
    else
        std::cout << "Read back from file: " << d2 << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 596C++98open() could not open files in append modecan open in append mode

# See also