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>

受保护成员函数

可选地提供可用于从文件输入的字符数

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

protected:
virtual std::streamsize showmanyc()

若实现,则返回从文件留待读取的字符数。

参数

(无)

返回值

可从文件读取的字符数,或若抵达文件尾则为 -1 。

注意

此函数为可选。若不实现,则此函数返回 ​0​ (因为基类版本 std::basic_streambuf::showmanyc 得到调用)。

无论是否实现,若获取区为空,则此函数为 std::basic_streambuf::in_avail 所正常调用。

此函数的名称表示“流:多少字符?”,故它读作“ S how many C ”,而不是“ show many C ”。

调用示例

#include <fstream>
#include <iostream>

struct mybuf : std::filebuf
{
    using std::filebuf::showmanyc;
};

int main()
{
    mybuf fin;
    fin.open("test.txt", std::ios_base::in);
    if (!fin.is_open())
    {
        std::cout << "open error" << std::endl;
    }
    std::cout << "showmanyc() returns " << fin.showmanyc() << std::endl;
    return 0;
}
输出

 

从关联文件读取

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

protected:
virtual int_type underflow()

读取更多数据到输入区中。

表现类似基类 std::basic_streambuf::underflow ,除了要从关联字符序列(文件)读取数据到获取区中。首先从文件读取字符到临时缓冲区(分配所需大小),然后用感染的 locale 的 std::codecvt::in 转换外部(典型为多字节)表示为之后用于填充获取区的内部形式。若该 locale 的 std::codecvt::always_noconv 返回 true 则可以跳过转换。

参数

(无)

返回值

成功情况下为 Traits::to_int_type(*gptr()) (待处理序列的首字符),失败情况下为 Traits::eof() 。

调用示例

#include <fstream>
#include <iostream>

struct mybuf : std::filebuf
{
    int underflow()
    {
        std::cout << "Before underflow(): size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available\n";
        int rc = std::filebuf::underflow();
        std::cout << "underflow() returns " << rc << ".\nAfter the call, "
                  << "size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available\n";
        return rc;
    }
};

int main()
{
    mybuf buf;
    buf.open("test.txt", std::ios_base::in);
    std::istream stream(&buf);
    while (stream.get()) ;
    return 0;
}
输出

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值