繁体   English   中英

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

[英]Is it possible to use std::basic_ifstream and std::basic_ofstream with a custom buffer?

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

通过64KB大小的块读取文件并在内部检查该块的某些哈希值的输入文件流的实现有多复杂? 例如,如果散列无效,则抛出hash_exception。 输出文件流将块和哈希值写入该块之后。

我发现了一些创建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的组合。 流接口允许通过rdbuf()方法访问std::basic_streambuf 因此,您可以用另一个替换文件流流缓冲区。 但是,它与原始文件缓冲区没有任何关系。

由于您拥有的流缓冲区是过滤流缓冲区,因此用流构造它并让构造函数注入过滤器是合理的,例如,这样的事情(我省略了模板,因为这些模板与本次讨论无关,但可以轻松添加):

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) {
    ...
}

如果要自定义iostream的行为,最简单的方法是使用boost :: iostreams 您的用例可能实现为InputfilterOutputFilter ,可以使用basic_file_sourcebasic_file_sink读取和写入文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM