Clearing Contents of a File in C++ knowing only the FILE *
Is it possible to clear the contents (ie. set EOF to the beginning/reset the file) in C++ knowing just the FILE*? I'm writing to a temp file with wb+ access and wish to sometimes clear it and truncate it without adding the calls to fclose and fopen. I dont think it's possible... but if not, why not?
Thanks in advance!开发者_如何学运维
It will depend on your platform. The POSIX standard provides ftruncate()
, which requires a file descriptor, not a FILE
pointer, but it also provides fileno()
to get the file descriptor from the FILE
pointer.
The analogous facilities will be available in Windows environments - but under different names.
I don't believe this can be done using just the FILE*
. You can always write null data through the end of the file but that won't truncate it.
Alternately if you have access to the filename (I can't tell from the question) you could use freopen
which hides the close/open/truncate into a single function call.
#include <cstdio>
freopen(null, "w", filePtr);
see http://www.cplusplus.com/reference/clibrary/cstdio/freopen/ for more. espacialy the description for the parameter filename.
精彩评论