Link to home
Start Free TrialLog in
Avatar of asavino
asavino

asked on

Deleting files from a directory using wildcards in a C++ App.

I am writing a function in Visual C++ 5.0  that should delete files from a directory  that begins with a certain prefix.  A related DOS command would be "C:\> del myfiles.*".   I have used the function DeleteFile() to delete files where I know the exact name, such as "DeleteFile("c:\\archive\\myfiles.001")".  But if I substitute the wildcard character "*"
for ".001" it does not work.  Can this function accomplish this task?  If so, please provide an example.  If it can't, what would you recommend?

Thank you.

I think this should be an easy question to answer but if you need more points, feel free
to take what you feel it is worth.
Avatar of asavino
asavino

ASKER

Edited text of question
Avatar of asavino

ASKER

Edited text of question
ASKER CERTIFIED SOLUTION
Avatar of piano_boxer
piano_boxer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, s argument to FindFirstFile should be replaced by lpszFile.
PMFJI, the open curly before the while should be a closing brace
HERE IS THE CORRECTED ANSWER
****************************

DeleteFile() does not support wildcards.
You need to Use FindFirstFile()/FindNextFile() instead.

I have written the following sample routine for you.
Plz note that you can include the path in the filename
(ex: WildDeleteFiles("c:\temp\*.*") which will delete all
file in the temp dir.

void WildDeleteFiles(LPCTSTR lpszFile)
{
    WIN32_FIND_DATA fd;
    HANDLE hFind;

    hFind = FindFirstFile(lpszFile, &fd);
    if(hFind == INVALID_HANDLE_VALUE)
        // No files found
        return;

    do
    {
        DeleteFile(fd.cFileName);
    }
    while(FindNextFile(hFind, &fd));
    FindClose(hFind)  // <<<<<<<<<<<<<<<<
}
Avatar of asavino

ASKER

Thank you for your help, problem is solved. One note though, I found that the file name returned does not include the directory path name where the file was found.  But, it was no big deal.  All I did was re-append the path name to the file name returned and then issued the 'DeleteFile()'.  Thank you again.