Xaqq
Xaqq

Reputation: 4386

ifstream operator >> and error handling

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,

Upvotes: 1

Views: 916

Answers (1)

James Kanze
James Kanze

Reputation: 153899

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> and streambuf for your binary streams): istream and ostream use a streambuf for the actual sourcing and sinking of the bytes. And streambuf normally buffer: the procedure 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 streambuf returns end of file, and that terminates the input; istream will memorize 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 are there. 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_base and (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.)

Upvotes: 1

Related Questions