tags:

views:

89

answers:

3

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!

A: 

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.

Mark B
@Cenoc: "thought it was odd that they decided to give you power to expand, but not to shorten" - I recollect that the rationale for this is that there were (are?) systems that didn't have the capability to shorten files. Seems like there could have been a better alternative (return an error on those systems?), but then again, it might not even be true.
Michael Burr
+7  A: 

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.

Jonathan Leffler
(Additionally, `ftruncate` requires the file to be open for writing.)
stakx
@stakx: Since the file is open 'wb+', that is not an issue.
Jonathan Leffler
A: 
#include <cstdio>

freopen(null, "w", filePtr);

see http://www.cplusplus.com/reference/clibrary/cstdio/freopen/ for more. espacialy the description for the parameter filename.

M3t0r