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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With