HMVC
HMVC

Reputation: 109

WINAPI - Empty a file?

I want to empty a file and i got 2 ways :

1) Using CreateFile function with dwCreationDisposition = TRUNCATE_EXISTING !

2) Opening the file ,setting the file pointer to the beginning of the file with SetFilePointerEx and then calling SetEndOfFile !

Is there any difference and which one should i use ?

Upvotes: 2

Views: 2062

Answers (2)

Jithin Pavithran
Jithin Pavithran

Reputation: 1351

Using CreateFile function with dwCreationDisposition = TRUNCATE_EXISTING !

  • This will open an existing file and discard the existing content, making file size 0.
  • This method will fail if the file does not exist already.
  • This can be understood as deleting the existing file and creating a fresh one, though it may not be technically correct.

Opening the file and setting the file pointer to the beginning of the file with SetFilePointerEx and then calling SetEndOfFile !

  • Open the file and keep the content of the file.
  • This method will work irrespective of if the file is existing or not.
    Whether the file is already existing or not is completely left to dwCreationDisposition flag.
  • Let's assume you open a file with following content:
    0123456789
    and write zxc, this is how file will now look like:
    zxc3456789

I strongly believe that they should allow combinations of TRUNCATE_EXISTING and OPEN_ALWAYS to tackle the specified case better.

Upvotes: -1

Mats Petersson
Mats Petersson

Reputation: 129374

In essence, both of these will achieve the same thing, and you would have to do a lot of "emptying" of files to be able to tell much difference in performannce - if files are large, freeing the no longer used blocks from the file allocation will be the main time taken anyway.

Of course, if you want more portable code, using ofstream of("myfile.ext"); will also achieve this, as will FILE *f = fopen("myfile.ext", "w"); (along with a few variations on the same theme).

There is very little difference between these variants in general, it's mostly a case of what makes most sense for the code you are currently working on. In other words, "what are you going to do next with the now empty file", and what kind of "handle" you may need for it.

Upvotes: 4

Related Questions