gpt4 book ai didi

c++ - 是否可以将 std::basic_ifstream 和 std::basic_ofstream 与自定义缓冲区一起使用?

转载 作者:行者123 更新时间:2023-11-30 03:21:12 25 4
gpt4 key购买 nike

我想不通,是否可以将 std::basic_ifstream 和 std::basic_ofstream 与 std::basic_filebuf 的自定义实现一起使用?

按 64KB 大小的 block 读取文件并在内部检查 block 的某些哈希值的输入文件流的实现有多复杂?例如,如果哈希无效,它会抛出 corruption_exception。输出文件流在其后写入 block 和哈希值。

我找到了一些创建 std::ifstream 然后创建另一个从中读取并进行额外处理的流的示例:

std::ifstream infile("test.img");
decompress_stream in(infile, 288);
char data[144 * 128];
in.read(data, 144 * 128);
infile.close();

但起初我预计它应该是这样的(没有额外的流):

std::ifstrem in;
in.setbuffer(new MyBuffer());
in.read();

MyBuffer::underflow()
{
//read from original buffer
if (hash != calculated_sash) throw curruption_exception();
//return the data with omitted hash.
}

这可能吗?

最佳答案

文件流对象实际上是 std::basic_filebufstd::basic_[io]stream 的组合。流接口(interface)允许通过 rdbuf() 方法访问 std::basic_streambuf。因此,您可以用另一个替换文件流流缓冲区。但是,它与原始文件缓冲区没有任何关系。

由于您拥有的流缓冲区是一个过滤流缓冲区,因此使用流构造它并让构造函数注入(inject)过滤器可能是合理的,即像这样的东西(我省略了模板,因为这些与此无关讨论,但可以很容易地添加):

class filterbuf
: public std::streambuf {
std::istream* istream = nullptr;
std::ostream* ostream = nullptr;
std::streambuf * sbuf;

// override virtual functions as needed
public:
explicit filterbuf(std::istream& in)
: istream(&in)
, sbuf(istream->rdbuf(this)) {
}
explict filterbuf(std::ostream& out)
: ostream(&out)
, sbuf(ostream->rdbuf(this)) {
}
explicit filebuf(std::iostream& inout)
: istream(&inout)
, sbuf(istream->rdbuf(this)) {
}
~filebuf() {
istream && istream->rdbuf(sbuf);
ostream && ostream->rdbuf(sbuf);
}
};

在析构函数中恢复流缓冲区的要点是 std::ostream 析构函数调用对象上的 flush() 并且自定义流缓冲区消失了那个时候。

过滤器将像这样使用:

std::istream fin(“whatever”);
filterbuf buf(fin);
if (fin >> whatever) {
...
}

关于c++ - 是否可以将 std::basic_ifstream 和 std::basic_ofstream 与自定义缓冲区一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com