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

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

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

Boost - Users mailing list

I'm trying to get familiar with boost::iostream, so in a example program I'm writing, I want to read a text from a file and write it to file.
I would use my inherited class from file_source/file_sink as device to read/write. In the read method, my class needs to add each character with one and write method needs to subtract one from each character.
First of all, I want to make sure that the reading part of the program works properly so you can see the code as follow:

#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();
}  

and my inherited source device code is as follow:

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;
};

unfortunately, the result of std::cout << myStream.rdbuf() with above read method is nothing while if I delete the read method of MyFileSource class to use the read method of parent, the result will be correct.
Any help will be appreciated.


_______________________________________________
Boost-users mailing list
[hidden email]
https://lists.boost.org/mailman/listinfo.cgi/boost-users