Search code examples
c++.netwindowstemp

Delete Files Efficiently Windows C++


I have a long running process that creates a small image (~1-2 kb) and loads it into memory. Because its created using an APK I have to save it to a file before loading it into memory. At that point I no longer need the file. The process can potentially creates many millions of these files.

I am using Visual C++.NET and this is a windows based application. I'd like to know the best way to go about this.

I could delete them as I go, by calling DeleteFile (http://msdn.microsoft.com/en-us/library/aa363915(v=vs.85).aspx) but I wonder if that operation has overhead and if I ought to do it every 10k or 100k files using a wildcard and a naming convention.

Is that worth the effort? Whats the trade offs here?


Solution

  • Use FILE_ATTRIBUTE_TEMPORARY and FILE_FLAG_DELETE_ON_CLOSE. Together they tell Windows exactly how you intend to use this file.

    The combination means that Windows will keep the file in file cache until you close its handle, at which point it's removed from memory. You don't even need DeleteFile! Since all the semantics are still that of an ordinary file, you don't need to change anything else.