I want to use ifstream to read data from a named piped. I would like to use its operator>> to read formatted data (typically, an int).
However, I am a bit confused in the way error handling works.
Imagine I want to read an int but only 3 bytes are available. Errors bits would be set, but what will happen to theses 3 bytes ? Will they “disappear”, will they be put back into the stream for later extraction ?
Thanks,
As has been pointed out, you can’t read binary data over an
istream.But concerning the number of available bytes issue (since you’ll
probably want to use
basic_ios<char>andstreambuffor your binarystreams):
istreamandostreamuse astreambuffor the actualsourcing and sinking of the bytes. And
streambufnormally buffer: theprocedure is: if a byte is in the buffer, return it, otherwise, try to
reload the buffer, waiting until the reloading has finished, or
definitively failed. In case of definitive failure, the
streambufreturns end of file, and that terminates the input;
istreamwillmemorize the end of file, and not attempt any more input. So if the
type you are reading needs four bytes, it will request four bytes from
the
streambuf, and will normally wait until those four bytes arethere. No error will be set (because there isn’t an error); you will
simply not return from the
operator>>until those four bytes arrive.If you implement your own binary streams, I would strongly recommend
using the same pattern; it will allow direct use of already existing
standard components like
std::ios_baseand (perhaps)std::filebuf,and will provide other programmers with an idiom they are familiar with.
If the blocking is a problem, the simplest solution is just to run the
input in a separate thread, communicating via a message queue or
something similar. (Boost has support for asynchronous IO. This avoids
threads, but is globally much more complicated, and doesn’t work well
with the classical stream idiom.)