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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With