title: Exiting out of file with feof function
body: <p>I am trying to make a photo extraction program stop when it detects it is at the end of the file to be extracted. I did this by placing an if condition:</p>
  <pre><code>if (feof(file))
  {
     return 2;
  }
  </code></pre>
  <p>After a fread function:</p>
  <pre><code>fread(array, 1, 512, file);
  </code></pre>
  <p>So that if fread reads to the end of the file, then feof will trigger and thereby end the program. This is my code:</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdbool.h&gt;
  
  int main(int argc, char *argv[])
  {
      if (argc != 2)
      {
          printf(&quot;Invalid entry.\n&quot;);
          return 0;
      }
  
      int counter = 1;
      FILE* images;
      char jpg_name[8];
  
      // Check if bytes are jpg. signatures.
      for (int n = 0; counter &lt; 51; n = n + 512)
      {
          // Open file for reading.
          FILE *file = fopen(argv[1], &quot;r&quot;);
          if (!file)
          {
              return 1;
          }
  
          unsigned char array[512];
          fseek(file, n, SEEK_SET);
          fread(array, 1, 512, file); // if EOF, won't have 512 to write into!!!
          if (feof(file))
          {
              return 2;
          }
          fclose(file);
  
          if (array[0] == 0xff &amp;&amp; array[1] == 0xd8 &amp;&amp; array[2] == 0xff &amp;&amp; (array[3] &amp; 0xf0) == 0xe0)
          {
              // Convert integer to string and store into jpg character array. Increment image number.
              sprintf(jpg_name, &quot;%03i.jpg&quot;, counter);
              counter++;
  
              // Open images file to write into, allocate memory to jpg file to write into, write 512 bytes from array into image file.
              images = fopen(jpg_name, &quot;a&quot;);
              fwrite(array, 1, 512, images);
              fclose(images);
          }
          else // If 1st 4 bytes aren't jpg signature.
          {
              if (counter &gt; 1)
              {
                  images = fopen(jpg_name, &quot;a&quot;);
                  fwrite(array, 1, 512, images);
                  fclose(images);
              }
          }
      }
  }
  </code></pre>
  <p>I have also tried placing the condition:</p>
  <pre><code>if (fread(array, 1, 512, file) == 512)
  </code></pre>
  <p>Into the program so that it stops running after it reads fewer than 512 bytes to stop automatically stop the program, but this also doesn't seem to be working.</p>
  <p>Any clarification or advice would be much appreciated, thank you!</p>