Error during copying stream in c++ using the rdbuf() and operator <<

Rani Source

The "standard" offered way to copy files, for example through c++ is.

ifstream ins;
ofstream out s;
// I've omitted the opening of those stream, since it is not important for the following question.

s << ins.rdbuf();

Now, the problem is that the above line may fail, and in some cases, especially the one I'll talk about, there is no way I found to know that something went wrong.

Assume the input stream is actually a large file sitting on remote NAS machine, for example. Now, there may be connetion errors which will cause the file handle to be invalid. Trying to simulate this, I used a large file, in debugger I stopped on this line, found the handle, then continued the debugger and then closed the file handle forcibly (through process-explorer of the sysinternals suite).

The result is: the line finished, the file is not being copied correctly, sometimes it is not copied at all, sometimes only part of the file is being closed. In contradiction to the documentation of the operator<<, and the rdbuf(), there is no setting of bad/fail state, and no exception is being thrown.

The only thing I could notice, is that when trying to close the input-stream, an exception is being raised.

Did anyone so the same phenomenon ?! Is there anyway to check/test this for correct completion ?

Regards,

c++filestream

Answers

answered 6 years ago James Kanze #1

Streams are notoriously bad with regards to error reporting. In this case, all you can do is check for badbit on the output stream; the standard requires the << operators to absorb all exceptions, setting the badbit if they occur. And obviously, this doesn't tell you whether the error was due to an error on input or an error on output.

Typically, if you're using the implementations which come with most compilers, there won't be an error reported on input anyway. For the most part, unless things have changed in recent years, implementations of filebuf treat errors on input exactly like end of file.

If you need better error reporting, I think you're stuck with implementing your own streambuf (not really very difficult), which keeps track of the various errors; you can then ask the streambuf after the transfer what errors it received.

comments powered by Disqus