romsky
romsky

Reputation: 884

How to read a file using boost::iostreams::file_descriptor_source?

I need to use boost::iostreams::file_descriptor::handle_type in my app. I try to read a file using following code, but it keeps looping in the while loop (in.readsome() returns 0 ).

using namespace boost::iostreams;

file_descriptor_source source( "data.bin", never_close_handle);
stream_buffer<file_descriptor_source> stream(source);
std::istream in(&stream);

char buffer[1025];
memset(buffer, 0, sizeof(buffer));

while ( !in.eof() )
{
    streamsize read = in.readsome(&buffer[0], sizeof(buffer) - 1);
}

Upvotes: 2

Views: 4043

Answers (2)

romsky
romsky

Reputation: 884

Following statement does NOT read anything from the stream.

streamsize read = in.readsome(&buffer[0], sizeof(buffer) - 1);

And ALWAYS returns 0, that's why it loops forever.

Something wrong in the initialization of "in" object. I do not know what is wrong.

Upvotes: 0

betabandido
betabandido

Reputation: 19704

Reaching the end-of-file is not the only condition you should check for, since there could be other cases that you must handle too. For instance you may:

  • check whether a non-recoverable error has occurred with bad().
  • check whether an error has occurred on the associated stream with fail().

It is better to check the health of stream itself, as shown below:

while (in) {
    streamsize read = in.readsome(buffer, sizeof(buffer) - 1);
    if (read > 0) {
        ...
    }
}

After exiting the loop, you could check the reason for exiting it with eof(), fail(), etc.

Upvotes: 1

Related Questions