title: Is there a guaranteed and safe way to truncate a file from ANSI C FILE pointer?
body: <p>I know ANSI C defines fopen, fwrite, fread, fclose to modify a file's content. However, when it comes to truncating a file, we have to turn to OS specific function, e.g, <code>truncate()</code> on Linux, <code>_chsize_s_()</code> on Windows. But before we can call those OS specific functions, we have to obtain the file-handle from FILE pointer, by calling <code>fileno</code>, also an non-ANSI-C one.</p>
  
  <p><strong>My question is:</strong> Is it reliable to continue using <code>FILE*</code> after truncating the file? I mean, ANSI C <code>FILE</code> layer has its own buffer and does not know the file is truncated from beneath. In case the buffered bytes is beyond the truncated point, will the buffered content be flushed to the file when doing <code>fclose()</code> ?</p>
  
  <p>If no guarantee, what is the best practice of using file I/O functions accompanied with truncate operation when write a Windows-Linux portable program?</p>
  
  <p>Similar question: When querying file size from a file-handle returned by <code>fileno</code> , is it the accurate size when I later call <code>fclose()</code> -- without further <code>fwrite()</code>?</p>
  
  <p>[EDIT 2012-12-11]</p>
  
  <p>According to Joshua's suggestion. I conclude that current possible best practice is: Set the stream to unbuffered mode by calling <code>setbuf(stream, NULL);</code> , then <code>truncate()</code> or <code>_chsize_s()</code> can work peacefully with the stream.</p>
  
  <p>Anyhow, no official document seems to explicitly confirm this behavior, whether Microsoft CRT or GNU glibc.</p>