Kub*_*ski 7 c++ inheritance fstream iostream c++17
我正在尝试制作一个自定义的 std::fstream,它会在读取时对数据进行编码/解码。
template <class T>
class _filebuf : public std::filebuf {
public:
using transform_type = T;
int_type underflow() override {
auto c = std::filebuf::underflow();
return c < 0 ? c : transform.decode(c);
}
int_type overflow(int_type c) override {
return c < 0 ? c : std::filebuf::overflow(transform.encode(c));
}
private:
transform_type transform;
};
template <class T>
class _fstream : public std::iostream {
public:
using buffer_type = _filebuf<T>;
explicit _fstream(const std::string& path, std::ios::openmode openmode)
: std::iostream(0)
{
this->init(&buffer);
buffer.open(path, openmode);
}
private:
buffer_type buffer;
};
Run Code Online (Sandbox Code Playgroud)
这是一个用法示例:
class _transform {
public:
template <class T>
T encode(T value) const {
return value - 1;
}
template <class T>
T decode(T value) const {
return value + 1;
}
};
int main() {
_fstream<_transform> ofs("test.txt", std::ios::out | std::ios::trunc);
ofs << "ABC"; // outputs "@BC" to the file (@ is 64 in ASCII, so only first character encoded properly)
_fstream<_transform> ifs("test.txt", std::ios::in);
std::string s;
ifs >> s; // inputs "ABC" when "@BC" was in the file so again only first character is decoded
// ...
};
Run Code Online (Sandbox Code Playgroud)
经过我自己的研究,我发现“溢出”函数在此过程中被调用了两次(使用65 和 -1,其中 -1 可能是 EOF),并且“下溢”也调用了两次(使用64 和 -1)。由于其他字符没有丢失,它们可能会在不调用这些函数的情况下以某种方式进行处理。
为什么会发生这种情况以及如何改变它?
std::streambuf<CharT,Traits>::underflow确保获取区域中至少有一个std::filebuf字符可用,有效的实现将始终尝试将整个缓冲区的字符读入获取区域。除非您寻求,否则流不会再次被调用,直到通过调用/或underflow清空获取区域sgetnxsgetnsbumpc
我认为您可能会比扩展文件缓冲区更成功地进行包装。
Boost iostreams使编写流过滤器变得更加简单。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |