Reputation: 109
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
Reputation: 1351
Using CreateFile function with
dwCreationDisposition = TRUNCATE_EXISTING
!
Opening the file and setting the file pointer to the beginning of the file with
SetFilePointerEx
and then callingSetEndOfFile
!
dwCreationDisposition
flag.0123456789
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
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