c++11 标准模板(STL)(std::basic_filebuf)(三)

定义于头文件 <fstream>

template<

    class CharT,
    class Traits = std::char_traits<CharT>

> class basic_filebuf : public std::basic_streambuf<CharT, Traits>

std::basic_filebuf 是关联字符序列为文件的 std::basic_streambuf 。输入序列和输出序列都关联到同一文件,并为两种操作维护连接文件位置。

函数 underflow() 和 overflow()/sync() 进行文件和缓冲区的获取放置区之间的实际 I/O 。 CharT 不是 char 时,多数实现在文件存储多字节字符,并用 std::codecvt 平面进行宽/多字节字符转换。

亦为常用字符类型定义二个特化:

类型 定义
filebuf basic_filebuf<char>
wfilebuf basic_filebuf<wchar_t>

公开成员函数

交换二个 basic_filebuf 对象

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

void swap( std::basic_filebuf& rhs );

(C++11 起)

交换 *this 与 rhs 的状态和内容。

参数

rhs - 另一 basic_filebuf

返回值

(无)

注意

在交换 std::fstream 对象时自动调用此函数,很少需要直接调用它。

调用示例

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

int main()
{
    std::ifstream fin("test.in"); // 只读
    std::ofstream fout("test.out"); // 只写

    std::string s;
    getline(fin, s);
    std::cout << s << '\n'; // 输出 test.in 的第一行

    fin.rdbuf()->swap(*fout.rdbuf()); // 交换底层缓冲

    getline(fin, s); // 失败:不能从只写 filebuf 读取
    std::cout << s << '\n'; // 打印空行
}

 输出

检查关联文件是否打开

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

bool is_open() const;

若最近到 open() 的调用成功且之后无到 close() 的调用则返回 true 。

参数

(无)

返回值

若关联文件打开则为 true ,否则为 false 。

注意

此函数典型地为 std::basic_fstream::is_open() 所调用。

调用示例

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream fs("test.txt");
    std::filebuf fb;
    fb.open("test.txt", std::ios_base::in);
    std::cout << std::boolalpha
              << "direct call: " << fb.is_open() << '\n'
              << "through streambuf: " << fs.rdbuf()->is_open() << '\n'
              << "through fstream: " << fs.is_open() << '\n';
}

 输出

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/131820176