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

标签 c++

我想不通,是否可以将 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/

相关文章:

c++ - 在 C++ 中,删除对象时清除对对象的引用

c++ - C++ 中哪些类型被认为是可调用的?

c++ - 为什么 unordered_set 的元素对于自定义 equal_to 不是唯一的

c++ - MFC CEdit 控件添加到加速器后不处理按下的按键

c++ - std::map 的插入提示是否有任何位置限制?

c++ - 用C或C++读/写BMP/PNG灰度图像

C++-SDL : Limiting framerate issue

c++ - 删除 Deque 容器的元素

c++ 以 vector 为参数调用函数

c++ - 如果没有显式复制构造函数,是否可以禁止赋值? C++