Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is failbit set when eof is found on read?
    text
    copied!<p>I've read that <code>&lt;fstream&gt;</code> predates <code>&lt;exception&gt;</code>. Ignoring the fact that exceptions on <code>fstream</code> aren't very informative, I have the following question:</p> <p>It's possible to enable exceptions on file streams using the <code>exceptions()</code> method.</p> <pre><code>ifstream stream; stream.exceptions(ifstream::failbit | ifstream::badbit); stream.open(filename.c_str(), ios::binary); </code></pre> <p>Any attempt to open a nonexistent file, a file without the correct permissions, or any other I/O problem will results in exception. This is very good using an assertive programming style. The file was supposed to be there and be readable. If the conditions aren't met, we get an exception. If I wasn't sure whether the file could safely be opened, I could use other functions to test for it.</p> <p>But now suppose I try to read into a buffer, like this:</p> <pre><code>char buffer[10]; stream.read(buffer, sizeof(buffer)); </code></pre> <p>If the stream detects the end-of-file before filling the buffer, the stream decides to set the <code>failbit</code>, and an exception is fired if they were enabled. Why? What's the point of this? I could have verified that just testing <code>eof()</code> after the read:</p> <pre><code>char buffer[10]; stream.read(buffer, sizeof(buffer)); if (stream.eof()) // or stream.gcount() != sizeof(buffer) // handle eof myself </code></pre> <p>This design choice prevents me from using standard exceptions on streams and forces me to create my own exception handling on permissions or I/O errors. Or am I missing something? Is there any way out? For example, can I easily test if I can read <code>sizeof(buffer)</code> bytes on the stream before doing so?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload