C++ code to delete all files in a folder with FindFirstFile/FindNextFile

c++, file, winapi, windows

Solution

Yes, you can safely delete files from a folder using a traversal on these lines, provided of course that you get the API and logic details right (e.g. Frerich Raabe's comment).

So your `FindFirstFile` will initialize a `WIN32_FIND_DATA` structure and your `FindNextFile` will refer to the same structure for its way-finding purposes. As long as you don't corrupt it you can delete files as you go.

Problem

My goal is to delete all files in a given folder but not to delete the folder itself. I was thinking of calling FindFirstFile followed by repeated calls to FindNextFile while doing deletion of each file found, using the following pseudo code: ``` if(FindFirstFile(FindFileData)) { do { DeleteFile(FindFileData.FileName); } while(FindNextFile(FindFileData)); FindClose(FindFileData); //EDIT for people who didn't see my pseudo-code remark } ``` But now I'm thinking, if I'm allowed to delete files while doing the enumeration in that folder? Or in other words, do I need to first cache all the file names found and then delete them, or is it OK to do it as I showed above?

Original source

Related problems