Namespaces
Variants

std::basic_ofstream<CharT,Traits>:: basic_ofstream

From cppreference.net

basic_ofstream ( ) ;
(1)
explicit basic_ofstream ( const char * filename,

std:: ios_base :: openmode mode

= std:: ios_base :: out ) ;
(2)
explicit basic_ofstream ( const std :: filesystem :: path :: value_type * filename,

std:: ios_base :: openmode mode

= std:: ios_base :: out ) ;
(3) (自 C++17 起)
explicit basic_ofstream ( const std:: string & filename,

std:: ios_base :: openmode mode

= std:: ios_base :: out ) ;
(4) (自 C++11 起)
template < class FsPath >

explicit basic_ofstream ( const FsPath & filename,
std:: ios_base :: openmode mode

= std:: ios_base :: out ) ;
(5) (自 C++17 起)
basic_ofstream ( basic_ofstream && other ) ;
(6) (自 C++11 起)
basic_ofstream ( const basic_ofstream & rhs ) = delete ;
(7) (自 C++11 起)

构造新的文件流。

1) 默认构造函数:构造一个未关联文件的流:默认构造 std::basic_filebuf 成员,并以指向该默认构造的 std::basic_filebuf 成员的指针来构造基类。
2,3) 首先执行与默认构造函数相同的步骤,然后通过调用 rdbuf ( ) - > open ( filename, mode | std:: ios_base :: out ) 将流与文件关联(有关该调用效果的详细信息,请参见 std::basic_filebuf::open )。如果 open() 调用返回空指针,则设置 setstate ( failbit ) 仅当 std :: filesystem :: path :: value_type 不是 char 时才提供重载 (3) (C++17 起)
4,5) basic_ofstream ( filename. c_str ( ) , mode ) 相同。 (5) 仅当 FsPath std::filesystem::path 时参与重载决议。 (C++17 起) 注意:尽管默认模式为 out ,但其效果与 std::filebuf::open 中描述的 out | trunc 效果相同。
6) 移动构造函数。首先从 other 移动构造基类(这不会影响 rdbuf() 指针),然后移动构造 std::basic_filebuf 成员,最后调用 this - > set_rdbuf ( ) 将新的 basic_filebuf 安装为基类中的 rdbuf() 指针。
7) 复制构造函数被删除:此类不可复制。

目录

参数

filename - 要打开的文件名
mode - 指定流打开模式。可使用以下常量及其按位或组合:
常量 说明
app 每次写入前定位到流末尾
binary 二进制模式 打开
in 为读取打开
out 为写入打开
trunc 打开时清空流内容
ate 打开后立即定位到流末尾
noreplace (C++23) 以独占模式打开
other - 用作源的其他文件流

示例

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

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 3430 C++17 std::filesystem::path 重载导致非预期转换 通过改为模板实现避免

另请参阅

打开文件并将其与流关联
(公开成员函数)
打开文件并将其配置为关联的字符序列
( std::basic_filebuf<CharT,Traits> 的公开成员函数)
替换 rdbuf 但不清除其错误状态
(受保护成员函数)
构造对象
( std::basic_ostream<CharT,Traits> 的公开成员函数)