title: Proper way to get file size in C
body: <p>I am working on an assignment in socket programming in which I have to send a file between sparc and linux machine. Before sending the file in char stream I have to get the file size and tell the client. Here are some of the ways I tried to get the size but I am not sure which one is the proper one.</p>
  
  <p>For testing purpose, I created a file with content " test" (space + (string)test)</p>
  
  <p><strong>Method 1 - Using fseeko() and ftello()</strong></p>
  
  <p>This is a method I found on <a href="https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file" rel="nofollow">https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file</a>
  While the fssek() has a problem of "Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream", fseeko() is said to have tackled this problem but it only works on POSIX system (which is fine because the environment I am using is sparc and linux)</p>
  
  <pre><code>fd = open(file_path, O_RDONLY);
  fp = fopen(file_path, "rb");
  /* Ensure that the file is a regular file */
  if ((fstat(fd, &amp;st) != 0) || (!S_ISREG(st.st_mode))) {
    /* Handle error */
  }
  if (fseeko(fp, 0 , SEEK_END) != 0) {
    /* Handle error */
  }
  file_size = ftello(fp);
  fseeko(fp, 0, SEEK_SET);
  printf("file size %zu\n", file_size);
  </code></pre>
  
  <p>This method works fine and get the size correctly. However, it is limited to regular files only. I tried to google the term "regular file" but I still not quite understand it thoroughly. And I do not know if this function is reliable for my project.</p>
  
  <p><strong>Method 2 - Using strlen()</strong></p>
  
  <p>Since the max. size of a file in my project is 4MB, so I can just calloc a 4MB buffer. After that, the file is read into the buffer, and I tried to use the strlen to get the file size (or more correctly the length of content). Since strlen() is portable, can I use this method instead? The code snippet is like this</p>
  
  <pre><code>fp = fopen(file_path, "rb");
  fread(file_buffer, 1024*1024*4, 1, fp);
  printf("strlen %zu\n", strlen(file_buffer));
  </code></pre>
  
  <p>This method works too and returns </p>
  
  <pre><code>strlen 8
  </code></pre>
  
  <p>However, I couldn't see any similar approach on the Internet using this method. So I am thinking maybe I have missed something or there are some limitations of this approach which I haven't realized.</p>