Alex Rivera | Logout

How can I find out how many bytes are available from a std::istream?

Asked 2011-07-12T15:40:13.507
10

If I wanted to read() the content of a std::istream in to a buffer, I would have to find out how much data was available first to know how big to make the buffer. And to get the number of available bytes from an istream, I am currently doing something like this:

std::streamsize available( std::istream &is )
{
    std::streampos pos = is.tellg();
    is.seekg( 0, std::ios::end );
    std::streamsize len = is.tellg() - pos;
    is.seekg( pos );
    return len;
}

And similarly, since std::istream::eof() isn't a very useful fundtion AFAICT, to find out if the istream's get pointer is at the end of the stream, I'm doing this:

bool at_eof( std::istream &is )
{
    return available( is ) == 0;
}

My question:

Is there a better way of getting the number of available bytes from an istream? If not in the standard library, in boost, perhaps?

Edit
Report

1 Answer

3

Posting this as an answer, as it seems to be what the OP wants.

I would have to find out how much data was available first to know how big to make the buffer - not true. See this answer of mine (second part).

answered 2011-07-12T16:22:06.050

Your Answer