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

来自cppreference.com
< cpp‎ | io‎ | basic filebuf
 
 
 
 
basic_filebuf* open(constchar* s, std::ios_base::openmode mode );
(1)
basic_filebuf* open(conststd::string& str, std::ios_base::openmode mode );
(2) (C++11 起)
basic_filebuf* open(conststd::filesystem::path& p,
                     std::ios_base::openmode mode );
(3) (C++17 起)
basic_filebuf* open(const std::filesystem::path::value_type* s,
                     std::ios_base::openmode mode );
(4) (C++17 起)

如果关联文件已打开(is_open()!=false,则直接返回空指针。

否则,打开拥有给定名称(sp.c_str()(C++17 起)str.c_str(),取决于重载)的文件。std::ios_base::openmode 值可以写成例如 std::ios_base::out|std::ios_base::app 这样的形式。

只有在 std::filesystem::path::value_type 不是 char 时才会提供重载 (4)

(C++17 起)

如同通过以 mode & ~std::ios_base::ate 的结果按下列方式确定的第二实参 (文件访问模式) 调用 std::fopen 打开文件,open() 在结果不是以下标志位的组合之一的情况下会失败:

mode & ~std::ios_base::ate std::fopen 
访问模式
文件已存在时
的动作
文件不存在时
的动作
binaryinouttruncappnoreplace
(C++23 起)
- + - - - - "r"从头读取 打开失败
+ + - - - - "rb"
- + + - - - "r+"错误
+ + + - - - "r+b"
- - + - - - "w"销毁内容 创建新文件
- - + + - -
+ - + - - - "wb"
+ - + + - -
- + + + - - "w+"
+ + + + - - "w+b"
- - + - - + "wx"打开失败 创建新文件
- - + + - +
+ - + - - + "wbx"
+ - + + - +
- + + + - + "w+x"
+ + + + - + "w+bx"
- - + - + - "a"写入结尾 创建新文件
- - - - + -
+ - + - + - "ab"
+ - - - + -
- + + - + - "a+"
- + - - + -
+ + + - + - "a+b"
+ + - - + -

如果打开操作成功且 (openmode &std::ios_base::ate)!=0(设置了 ate 位),那么如同用调用 std::fseek(file, 0, SEEK_END) 重寻位文件位置到文件尾,其中 file 是调用 std::fopen 返回的指针。如果寻位失败,那么就会调用 close() 并返回空指针以指示失败。

目录

[编辑]参数

s, str, p - 要打开的文件名;s 必须指向空终止字符串
openmode - 文件打开模式,std::ios_base 模式的二进制或

[编辑]返回值

成功时返回 this,失败时返回空指针。

[编辑]注解

常由 std::basic_fstream 的构造函数或 open() 成员函数调用 open()

[编辑]示例

#include <fstream>#include <iostream>   int main(){std::string filename ="Test.b";std::filebuf fb;   // 准备文件以读取double d =3.14;if(!fb.open(filename, std::ios::binary| std::ios::out)){std::cout<<"为写入打开文件 "<< filename <<" 失败\n";return1;} fb.sputn(reinterpret_cast<char*>(&d), sizeof d); fb.close();   // 为读取打开文件double d2 =0.0;if(!fb.open(filename, std::ios::binary| std::ios::in)){std::cout<<"为读取打开文件 "<< filename <<" 失败\n";return1;}   auto got = fb.sgetn(reinterpret_cast<char*>(&d2), sizeof d2);if(sizeof(d2)!= got)std::cout<<"读取 "<< filename <<" 失败\n";elsestd::cout<<"从文件读回:"<< d2 <<'\n';}

输出:

从文件读回:3.14

[编辑]缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 596 C++98 open() 不能以追加模式打开文件 可以以追加模式打开

[编辑]参阅

检查关联文件是否打开
(公开成员函数)[编辑]
冲洗放置区缓冲区并关闭关联的文件
(公开成员函数)[编辑]
close