My code currently looks something like this (these steps splitted into multiple functions):
/* open file */
FILE *file = fopen(filename, "r+");
if(!file) {
/* read the file */
/* modify the data */
/* truncate file (how does this work?)*/
/* write new data into file */
/* close file */
fclose(file);
}
I know I could open the file with in "w" mode, but I don’t want to do this in this case. I know there is a function ftruncate in unistd.h/sys/types.h, but I don’t want to use these functions my code should be highly portable (on windows too).
Is there a possibility to clear a file without closing/reopen it?
With standard C, the only way is to reopen the file in “w+” mode every time you need to truncate. You can use
freopen()for this. “w+” will continue to allow reading from it, so there’s no need to close and reopen yet again in “r+” mode. The semantics of “w+” are:(Taken from the fopen(3) man page.)
You can pass a NULL pointer as the filename parameter when using
freopen():If you don’t need to read from the file anymore at all, when “w” mode will also do just fine.