Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 660
c00000fd Avatar asked Sep 15 '25 10:09

c00000fd


1 Answers

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.

like image 124
Mike Kinghan Avatar answered Sep 17 '25 00:09

Mike Kinghan