Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How you detect EOF depends on what you're using to read the stream:</p> <pre><code>function result on EOF or error -------- ---------------------- fgets() NULL fscanf() number of succesful conversions less than expected fgetc() EOF fread() number of elements read less than expected </code></pre> <p>Check the result of the input call for the appropriate condition above, then call <code>feof()</code> to determine if the result was due to hitting EOF or some other error. </p> <p>Using <code>fgets()</code>:</p> <pre><code> char buffer[BUFFER_SIZE]; while (fgets(buffer, sizeof buffer, stream) != NULL) { // process buffer } if (feof(stream)) { // hit end of file } else { // some other error interrupted the read } </code></pre> <p>Using <code>fscanf()</code>:</p> <pre><code>char buffer[BUFFER_SIZE]; while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion { // process buffer } if (feof(stream)) { // hit end of file } else { // some other error interrupted the read } </code></pre> <p>Using <code>fgetc()</code>:</p> <pre><code>int c; while ((c = fgetc(stream)) != EOF) { // process c } if (feof(stream)) { // hit end of file } else { // some other error interrupted the read } </code></pre> <p>Using <code>fread()</code>:</p> <pre><code>char buffer[BUFFER_SIZE]; while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 // element of size // BUFFER_SIZE { // process buffer } if (feof(stream)) { // hit end of file } else { // some other error interrupted read } </code></pre> <p>Note that the form is the same for all of them: check the result of the read operation; if it failed, <em>then</em> check for EOF. You'll see a lot of examples like:</p> <pre><code>while(!feof(stream)) { fscanf(stream, "%s", buffer); ... } </code></pre> <p>This form doesn't work the way people think it does, because <code>feof()</code> won't return true until <em>after</em> you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief. </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