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 平面进行宽/多字节字符转换。

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

类型定义
filebufbasic_filebuf<char>
wfilebufbasic_filebuf<wchar_t>

 

公开成员函数

构造 basic_filebuf 对象

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

basic_filebuf();

(1)

basic_filebuf( const std::basic_filebuf& rhs ) = delete;

(2)(C++11 起)

basic_filebuf( std::basic_filebuf&& rhs );

(3)(C++11 起)

 构造新的 std::basic_filebuf 对象。

1) 构造 std::basic_filebuf 对象,以调用 std::basic_streambuf 的默认构造函数初始化基类。创建的 basic_filebuf 不与文件关联,而 is_open() 返回 false 。

2) 复制构造函数被删除; std::basic_filebuf可复制构造 (CopyConstructible) 。

3) 通过从另一 std::basic_filebuf 对象 rhs 移动所有内容,包含缓冲区、关联的文件、 locale 、打开模式、 is_open 变量和所有其他状态移动构造 std::basic_filebuf 对象。移动后, rhs 不与文件关联且 rhs.is_open()==false 。保证 rhs 的基类和 *this 的基类 std::basic_streambuf 的成员指针指向不同缓冲区,除非它们为空。

参数

rhs-另一 basic_filebuf

注意

典型地为 std::basic_fstream 的构造函数所调用。

析构 basic_filebuf 对象并且若打开则关闭文件

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

virtual ~basic_filebuf();

调用 close() 关闭关联文件,并销毁 basic_filebuf 的所有其他成员。若 close() 抛出异常,则捕获异常且不重抛。

参数

(无)

返回值

(无)

注意

典型地为 std::basic_fstream 析构函数所调用。

赋值 basic_filebuf 对象

std::basic_filebuf<CharT,Traits>::operator=

std::basic_filebuf& operator=( std::basic_filebuf&& rhs );

(C++11 起)

std::basic_filebuf& operator=( const std::basic_filebuf& rhs ) = delete;

赋值另一 basic_filebuf 对象。

1) 首先调用 close() 关闭关联文件,然后移动 rhs 的内容到 *this 中:获取与放置缓冲区、本地环境、打开模式、打开标志及任何其他状态。移动后, rhs 不与文件关联且 rhs.is_open() == false 。

2) 复制赋值运算符被删除; basic_filebuf可复制赋值 (CopyAssignable) 。

参数

rhs-将被移动的另一 basic_filebuf

返回值

*this

调用示例

#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'; // 输出

    *fin.rdbuf() = std::move(*fout.rdbuf());

    getline(fin, s);
    std::cout << s << '\n'; // 空行

    std::cout << std::boolalpha << fout.is_open() << '\n'; // 打印 "false"
    return 0;
}
 输出

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值