定义于头文件 <fstream>
template< class CharT, |
std::basic_filebuf
是关联字符序列为文件的 std::basic_streambuf 。输入序列和输出序列都关联到同一文件,并为两种操作维护连接文件位置。
函数 underflow() 和 overflow()/sync() 进行文件和缓冲区的获取放置区之间的实际 I/O 。 CharT
不是 char 时,多数实现在文件存储多字节字符,并用 std::codecvt 平面进行宽/多字节字符转换。
亦为常用字符类型定义二个特化:
类型 | 定义 |
filebuf | basic_filebuf<char> |
wfilebuf | basic_filebuf<wchar_t> |
受保护成员函数
可选地提供可用于从文件输入的字符数
std::basic_filebuf<CharT,Traits>::showmanyc
protected: |
若实现,则返回从文件留待读取的字符数。
参数
(无)
返回值
可从文件读取的字符数,或若抵达文件尾则为 -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: |
读取更多数据到输入区中。
表现类似基类 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;
}
输出