| I/O manipulators | ||||
| Print functions(C++23) | ||||
| C-style I/O | ||||
| Buffers | ||||
(C++23) | ||||
(C++98/26*) | ||||
(C++20) | ||||
| Streams | ||||
| Abstractions | ||||
| File I/O | ||||
| String I/O | ||||
| Array I/O | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
(C++98/26*) | ||||
(C++98/26*) | ||||
(C++98/26*) | ||||
| Synchronized Output | ||||
(C++20) | ||||
| Types | ||||
| Error category interface | ||||
(C++11) | ||||
(C++11) |
| Member functions | ||||
basic_ofstream::basic_ofstream | ||||
(C++11) | ||||
(C++11) | ||||
| File operations | ||||
| Non-member functions | ||||
(C++11) |
basic_ofstream(); | (1) | |
explicit basic_ofstream(constchar* filename, =std::ios_base::out); | (2) | |
explicit basic_ofstream(const std::filesystem::path::value_type* filename, =std::ios_base::out); | (3) | (since C++17) |
explicit basic_ofstream(conststd::string& filename, =std::ios_base::out); | (4) | (since C++11) |
template<class FsPath> explicit basic_ofstream(const FsPath& filename, | (5) | (since C++17) |
basic_ofstream( basic_ofstream&& other); | (6) | (since C++11) |
basic_ofstream(const basic_ofstream& rhs)= delete; | (7) | (since C++11) |
Constructs new file stream.
open() call returns a null pointer, setssetstate(failbit).Overload(3) is only provided ifstd::filesystem::path::value_type is notchar.(since C++17)FsPath isstd::filesystem::path.(since C++17) Note that despite the default mode beingout, the effects are identical to the effects ofout | trunc as described instd::filebuf::openrdbuf() pointer), then move-constructs thestd::basic_filebuf member, then callsthis->set_rdbuf() to install the newbasic_filebuf as therdbuf() pointer in the base class.Contents |
| filename | - | the name of the file to be opened | ||||||||||||||||
| mode | - | specifies stream open mode. Following constants and bit-wise OR between them may be used:
| ||||||||||||||||
| other | - | another file stream to use as source |
#include <fstream>#include <string>#include <utility> int main(){std::ofstream f0;std::ofstream f1("test.bin", std::ios::binary);std::string name="example.txt";std::ofstream f2(name);std::ofstream f3(std::move(f1));}
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3430 | C++17 | std::filesystem::path overload led to unwanted conversions | avoided by making it a template |
| opens a file and associates it with the stream (public member function)[edit] | |
| opens a file and configures it as the associated character sequence (public member function of std::basic_filebuf<CharT,Traits>)[edit] | |
replaces therdbuf without clearing its error state(protected member function)[edit] | |
| constructs the object (public member function of std::basic_ostream<CharT,Traits>)[edit] |