问题描述
我可以开启
Can I open an ifstream (or set an existing one in any way) to only read part of a file? For example, I would like to have my ifstream read a file from byte 10 to 50. Seeking to position 0 would be position 10 in reality, reading past position 40 (50 in reality) would resualt in an EOF, etc. Is this possible in any way?
推荐答案
它可以通过实现一个过滤流缓冲区来完成:你将从 std :: streambuf 派生,并获取你想要公开的范围和底层流缓冲区(以及指向它的指针)作为参数。然后你会寻找到开始位置。重写的 underflow()函数将从底层流缓冲区读入其缓冲区,直到消耗了所需的字符数为止。这是一个有点粗糙和完全未经测试的版本:
It definetly can be done by implementing a filtering stream buffer: you would derive from std::streambuf and take the range you want to expose and the underlying stream buffer (well, a pointer to it) as arguments. Then you would seek to the start location. An overridden underflow() function would read from the underlying stream buffer into its buffer until has consumed as many characters as were desired. Here is a somewhat rough and entirely untested version:
#include <streambuf> struct rangebuf: std::streambuf { rangebuf(std::streampos start, size_t size, std::streambuf* sbuf): size_(size), sbuf_(sbuf) { sbuf->seekpos(start, std::ios_base::in); } int underflow() { size_t r(this->sbuf_->sgetn(this->buf_, std::min<size_t>(sizeof(this->buf_), this->size_)); this->size -= r; this->setg(this->buf_, this->buf_, this->buf_ + r); return this->gptr() == this->egptr() ? traits_type::eof() : traits_type::to_int_type(*this->gptr()); } size_t size_; std::streambuf* sbuf_; };
您可以使用指向此流缓冲区实例的指针来初始化 std :: istream 。如果这是一个反复的需要,你可能想要创建一个从 std :: istream 派生的类,而不是设置流缓冲。
You can use a pointer to an instance of this stream buffer to initialuze an std::istream. If this a recurring need, you might want to create a class derived from std::istream setting up the stream buffer instead.
这篇关于使用iostreams读取文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!