c++11 标准模板(STL)(std::basic_ifstream)(二)

定义于头文件 <fstream>

template<

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

> class basic_ifstream : public std::basic_istream<CharT, Traits>

类模板 basic_ifstream 实现文件流上的高层输入操作。它将 std::basic_istream 的高层接口赋予基于文件的流缓冲( std::basic_filebuf )。

std::basic_ifstream 的典型实现仅保有一个非导出数据成员: std::basic_filebuf<CharT, Traits> 的实例。

 

亦定义二个对于常用字符类型的特化:

类型定义
ifstreambasic_ifstream<char>
wifstreambasic_ifstream<wchar_t>

成员函数

构造文件流

std::basic_ifstream<CharT,Traits>::basic_ifstream

basic_ifstream();

(1)

explicit basic_ifstream( const char* filename,
                std::ios_base::openmode mode = ios_base::in );

(2)

explicit basic_ifstream( const std::filesystem::path::value_type* filename,
                std::ios_base::openmode mode = ios_base::in );

(3)(C++17 起)

explicit basic_ifstream( const std::string& filename,
                std::ios_base::openmode mode = ios_base::in );

(4)(C++11 起)

explicit basic_ifstream( const std::filesystem::path& filename,
                std::ios_base::openmode mode = ios_base::in );

(5)(C++17 起)

basic_ifstream( basic_ifstream&& other );

(6)(C++11 起)

basic_ifstream( const basic_ifstream& rhs) = delete;

(7)(C++11 起)

 

构造新的文件流。

1) 默认构造函数:构造不关联到文件的流:默认构造 std::basic_filebuf 并构造拥有指向此默认构造的 std::basic_filebuf 成员的基类。

2-3) 首先,进行同默认构造函数的步骤,然后通过调用 rdbuf()->open(filename, mode | std::ios_base::in)(该调用效果上的细节见 std::basic_filebuf::open )关联流与文件。若 open() 调用返回空指针,则设置 setstate(failbit) 。仅若 std::filesystem::path::value_type 非 char 才提供重载 (3) 。 (C++17 起)

4-5) 同 basic_ifstream(filename.c_str(), mode) 。

6) 移动构造函数:首先,从 other 移动构造基类(这不影响 rdbuf() 指针),然后移动构造 std::basic_filebuf 成员,再调用 this->set_rdbuf() 安装新的 basic_filebuf 为基类中的 rdbuf() 指针。

7) 复制构造函数被删除:此类不可复制。

参数

filename-要打开的文件名
mode-指定打开模式。它是位掩码类型,定义下列常量:
常量解释
app每次写入前寻位到流结尾
binary以二进制模式打开
in为读打开
out为写打开
trunc在打开时舍弃流的内容
ate打开后立即寻位到流结尾
other-用作源的另一文件流

调用示例

#include <fstream>
#include <utility>
#include <string>

int main()
{
    std::ifstream f0;
    std::ifstream f1("test.bin", std::ios::binary);
    std::string name = "example.txt";
    std::ifstream f2(name);
    std::ifstream f3(std::move(f1));
    return 0;
}

 

析构 basic_ifstream 和关联的缓冲区,并关闭文件

basic_fstream默认生成的析构函数将通过调用basic_filebuf的析构,从而间接调用close方法。即,会在析构中自动关闭文件。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值