title: Getting file size platform-independently (C)
body: <p>I am looking for some <strong>platform-independent</strong> C code to determine the size of a given file. First, I read the following answer:
  <a href="https://stackoverflow.com/a/238607">https://stackoverflow.com/a/238607</a></p>
  
  <p>The answer uses fseek with SEEK_END and ftell. Now, my problem is that I found the following C standard quotes.</p>
  
  <blockquote>
    <p>Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.</p>
  </blockquote>
  
  <p>and</p>
  
  <blockquote>
    <p>A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.</p>
  </blockquote>
  
  <p>So, it looks like I have a problem. Possibly, the following code, which counts the number of read bytes, is a workaround.</p>
  
  <pre><code>file = fopen(file_path, "rb");
  /* ... */
  while ( EOF != fgetc(file) ) {
    ret = size_t_inc(&amp;file_size_); /* essentially, this does ++file_size_ */
    /* ... */
  }
  ret = feof(file);
  /* ... */
  if (!ret) {
    return 1; /* Error! */
  }
  </code></pre>
  
  <p>(entire function here: <a href="https://github.com/630R6/bytelev/blob/8e3d0dd14042f16086f3ca4e9a33d49a0629630e/main.c#L138" rel="nofollow noreferrer">https://github.com/630R6/bytelev/blob/8e3d0dd14042f16086f3ca4e9a33d49a0629630e/main.c#L138</a>)</p>
  
  <p>Still, I am looking for a better solution.</p>
  
  <p>Thanks so much for your time!</p>