title: C++ get the size of a file while it's being written to
body: <p>I have a recording application that is reading data from a network stream and writing it to file. It works very well, but I would like to display the file size as the data is being written. Every second the gui thread updates the status bar to update the displayed time of recording. At this point I would also like to display the current file size.</p>
  
  <p>I originally consulted <a href="https://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c">this question</a> and have tried both the <code>stat</code> method:</p>
  
  <pre><code>struct stat stat_buf;
  int rc = stat(recFilename.c_str(), &amp;stat_buf);
  std::cout &lt;&lt; recFilename &lt;&lt; " " &lt;&lt; stat_buf.st_size &lt;&lt; "\n";
  </code></pre>
  
  <p>(no error checking for simplicity) and the <code>fseek</code> method:</p>
  
  <pre><code>FILE *p_file = NULL;
  p_file = fopen(recFilename.c_str(),"rb");
  fseek(p_file,0,SEEK_END);
  int size = ftell(p_file);
  fclose(p_file);
  </code></pre>
  
  <p>but either way, I get 0 for the file size. When I go back and look at the file I write to, the data is there and the size is correct. The recording is happening on a separate thread.</p>
  
  <p>I know that bytes are being written because I can print the size of the data as it is written in conjunction with the output of the methods shown above.
  <a href="https://i.stack.imgur.com/pV3UP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pV3UP.png" alt="enter image description here"></a></p>
  
  <p>The filename plus the 0 is what I print out from the GUI thread. 'Bytes written x' is out of the recording thread.</p>