如何在 C++ boost::iostreams 中更改 source/sink 设备的 read/write 方法?

How to change read/write method of source/sink device in C++ boost::iostreams?

我正在尝试熟悉 boost::iostream,因此在我正在编写的示例程序中,我想从文件中读取文本并将其写入文件。
我会使用从 file_source/file_sink 继承的 class 作为 read/write 的设备。在read方法中,我的class需要每个字符加一而write方法需要每个字符减一
首先,我想确保程序的读取部分能正常工作,这样你就可以看到如下代码:

#include <boost/iostreams/stream.hpp>
#include <fstream>
#include "MyFileSource.h"
#include <iostream>
using namespace std;
using namespace boost::iostreams;
int main()
{
    MyFileSource<char> fileSource("source.txt");
    stream<MyFileSource<char>> myStream(fileSource);
    std::cout << myStream.rdbuf();
    fileSource.close();
}  

而我继承的源设备代码如下:

template <typename charType>
class MyFileSource : public boost::iostreams::file_source
{
public:
    MyFileSource(const std::string& path) : boost::iostreams::file_source(path)
    {
        file_path = path;
        if (!is_open())
            open(path);
        seek(0, ios::end);
        sizeOfFile = seek(0, ios::cur);
        seek(0, ios::beg);
        buffer = new charType[sizeOfFile];
    }
    std::streamsize read(charType*, std::streamsize)
    {
        std::streamsize readCount = boost::iostreams::file_source::read(buffer, sizeOfFile);
        if (readCount > 0)
        {
            std::string result(buffer, readCount);
            for (char& c : result)
                c++;
            finalResult = result;
        }
        return readCount;
    }

private:
    string file_path;
    int sizeOfFile;
    charType* buffer;
    std::string finalResult;
};

不幸的是,如果我删除 MyFileSource class使用parent的read方法,结果是正确的。
任何帮助将不胜感激。

我解决了问题...

template <typename charType>
class MyFileSource : public boost::iostreams::file_source
{
public:
    MyFileSource(const std::string& path) : boost::iostreams::file_source(path)
    {
        if (!is_open())
            open(path);
    }
    std::streamsize read(charType* s, std::streamsize n)
    {
        std::streamsize readCount = boost::iostreams::file_source::read(s, n);
        if (readCount > 0)
        {
            std::string result(s, readCount);
            for (auto& c : result)
                c++;
            std::copy(result.begin(), result.end(), s);
        }
        return readCount;
    }
};

如您所见,通过删除附加缓冲区变量并将其替换为 s 来解决问题。