Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 426
edam Avatar asked Jul 12 '11 15:07

edam


2 Answers

For std::cin you don't need to worry about buffering because it is buffered already --- and you can't predict how many keys the user strokes.

For opened binary std::ifstream, which are also buffered, you can call the seekg(0, std::ios:end) and tellg() methods to determine, how many bytes are there.

You can also call the gcount() method after reading:

char buffer[SIZE];

while (in.read(buffer,SIZE))
{
  std::streamsize num = in.gcount();
  // call your API with num bytes in buffer 
}

For text input reading via std::getline(inputstream, a_string) and analyzing that string afterwards can be useful.

like image 119
René Richter Avatar answered Nov 09 '22 12:11

René Richter


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).

like image 22
Björn Pollex Avatar answered Nov 09 '22 12:11

Björn Pollex