title: How could count number of data blocks that have a file?
body: <p>I have to make a program that extract images from a RAW file. It's specified that the system file is fat32 and blocks of data are 512 bytes. The below program works, at least with the file that is provided for testing, but when i try to use RAW files that I found on the internet, not works and yields a segmentation fault error. Valgrind report some bytes still reachable.</p>
  <p>I think I'm reading less or more bytes that the block size for data in the file, so:</p>
  <p>How could I know the size of each block data inside the file?</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdint.h&gt;
  
  typedef uint8_t BYTE;
  
  int main(int argc, char *argv[])
  {
      // Check for two arguments
      if (argc != 2)
      {
          printf(&quot;Usage: ./recover image\n&quot;);
          return 1;
      }
  
      // Open the forensic image
      FILE *file = fopen(argv[1], &quot;r&quot;);
  
      if (file == NULL)
      {
          fprintf(stderr, &quot;It's not possible open the file :(\n&quot;);
          return 2;
      }
  
      // Initialize values
      int count = 0;
      BYTE buffer[512];
      char filename[8];
      FILE *out = NULL;
  
      // Read blocks of data from forensic image
      while (fread(&amp;buffer, sizeof(BYTE), sizeof(buffer), file))
      {
          // Check if there is a JPG signature
          if (buffer[0] == 0xff &amp;&amp; buffer[1] == 0xd8
              &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3] &amp; 0xf0) == 0xe0)
          {
              // If isn't first loop, close previous output file
              if (count !=  0)
              {
                  fclose(out);
              }
  
              // Save name for current output file
              sprintf(filename, &quot;%03i.jpg&quot;, count++);
  
              // Open output file
              out = fopen(filename, &quot;w&quot;);
  
              // Check if file is right
              if (out == NULL)
              {
                  fprintf(stderr, &quot;File could not open :(\n&quot;);
                  return 3;
              }
  
              // Write data to output file
              fwrite(&amp;buffer, sizeof(BYTE), sizeof(buffer), out);
          }
          // If isn't first loop, write data
          else if (count != 0)
          {
              fwrite(&amp;buffer, sizeof(BYTE), sizeof(buffer), out);
          }
      }
  
      fclose(out);
      fclose(file);
  
  }
  </code></pre>