title: Why doesn't the POSIX API have an end-of-file function?
body: <p>In the POSIX API, <code>read()</code> returns 0 to indicate that the end-of-file has been reached.  Why isn't there a separate function that tells you that <code>read()</code> would return zero -- without requiring you to actually call <code>read()</code>?</p>
  
  <hr>
  
  <p>Reason for asking: Since you have to call <code>read()</code> in order to discover that it will fail, this makes file reading algorithms more complicated and maybe slightly less efficient since they have to allocate a target buffer that may not be needed.</p>
  
  <p>What we might like to do...</p>
  
  <pre><code>while ( !eof )
     {
     allocate buffer
     read to buffer
     process buffer
     }
  </code></pre>
  
  <p>What we have to do instead...</p>
  
  <pre><code>while ( true )
     {
     allocate buffer
     read to buffer
     if ( eof ) release buffer, break;
     process buffer
     }
  </code></pre>
  
  <hr>
  
  <p>Additionally, it seems like this behavior propagates itself into higher-level APIs such as <code>fread()</code> and <code>feof()</code> in C -- and creates a lot of confusion about how to use <code>feof()</code> correctly:</p>
  
  <ul>
  <li>C: <a href="https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong">Why is “while ( !feof (file) )” always wrong?</a></li>
  <li>C++: <a href="https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong">Why is iostream::eof inside a loop condition considered wrong?</a></li>
  <li>Python: <a href="https://stackoverflow.com/questions/1752107/how-to-loop-until-eof-in-python">How to loop until EOF in Python?</a></li>
  </ul>