1

I'm studying boost::iostreams, and i am trying to write my own source device. I wrote two versions of boost::source. In the first version, I simply copy the time string to s, and it worked. But in the second version, I copy a specific string, it won't work, and when I make a breakpoint here, I found out that it's a circle.

struct mysource{
    typedef char                char_type;
    typedef io::source_tag      category;
    mysource(const char * echo):m_echo(echo){}
    std::streamsize read(char_type * s, std::streamsize n)
    {
        time_t tm;
        ::time(&tm);
        //return strlen(strncpy(s,ctime(&tm),n-1));  version 1  make a breakpoint here
        //return strlen(strncpy(s, m_echo, n-1));    version 2
    }
private:
    const char * m_echo;
};

Here is the test.

int main(int argc, char * argv[])
{
    string s;
    const char * echo = "Hello world";
    io::stream<mysource> in(echo);
    getline(in, s);
    cout << s << endl;
}

Version 1: output correctly, Version 2: a dead circle.

So I am really confused, what is the workflow inside the 'read' call?

I have skim the mannual of the boost::iostreams. And the examples I found there is a little bit complicate, what the examples does is in my eyes adding several members into the device class. And it seems not neccessary to the basic funtionnaity, since my version 1 is correctly running.

prehawk
  • 195
  • 12

1 Answers1

0

After some research on boost::iostreams and the circle mentioned above, I found out that I should implement a counter for the 'read' function. The counter would tell the system when to stop, since 'read' function will be called many times.

struct mysource{
    typedef char                char_type;
    typedef io::source_tag      category;
    mysource(const char * echo):m_echo(echo), pos_(0){}
    std::streamsize read(char_type * s, std::streamsize n)
    {
        int left = strlen(m_echo) - pos_;
        int len = std::min((int)n, left);
        if(len != 0){
            int ret = strlen(strncpy(s, m_echo + pos_, len));
            pos_ += ret;
            return ret;
        }
        else{
            return -1; //EOF
        }

    }
private:
    const char * m_echo;

private:
    std::streamsize pos_;
};

Now it's working.

prehawk
  • 195
  • 12
  • "an inside counter of char_types have read" - can you fix the wording so we can tell what you mean? – sehe Mar 08 '14 at 16:13