ksm001
ksm001

Reputation: 4022

Why doesn't this method of deleting files inside a folder work?

std::wstring inxmpath ( L"folder" );
HANDLE hFind;
BOOL bContinue = TRUE;
WIN32_FIND_DATA data;
hFind = FindFirstFile(inxmpath.c_str(), &data); 
// If we have no error, loop through the files in this dir
int counter = 0;
while (hFind && bContinue) {
        std::wstring filename(data.cFileName);
        std::string fullpath = "folder/";
        fullpath += (const char* )filename.c_str();
        if(remove(fullpath.c_str())!=0) return error;
    bContinue = FindNextFile(hFind, &data);
    counter++;
}
FindClose(hFind); // Free the dir

I don't understand why it doesn't work, I think it has something to do with the conversions between wstring and string however I'm not sure about that. I have a folder which has some .txt files, I need to delete all of them using C++. There are no folders in it nothing. How hard can this be?

Upvotes: 3

Views: 966

Answers (3)

cli_hlt
cli_hlt

Reputation: 7164

Secondly, according to MSDN about the FindFirstFile function:

"Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used)."

I cannot see a wildcard in your input string, so I can only guess that FindFirstFile will look for files named "folder" in the current execution directory.

Try looking for "folder\\*".

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595497

Try this instead:

std::wstring inxmpath = L"c:\\path to\\folder\\"; 
std::wstring fullpath = inxmpath + L"*.*";

WIN32_FIND_DATA data; 
HANDLE hFind = FindFirstFileW(fullpath.c_str(), &data);  
if (hFind != INVALID_HANDLE_VALUE)
{
    // If we have no error, loop through the files in this dir 
    BOOL bContinue = TRUE; 
    int counter = 0; 
    do
    { 
        if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
        {
            fullpath = inxmpath + data.cFileName; 
            if (!DeleteFileW(fullpath.c_str()))
            {
                FindClose(hFind);
                return error; 
            }
            ++counter; 
            bContinue = FindNextFile(hFind, &data); 
        }
    }
    while (bContinue);
    FindClose(hFind); // Free the dir 
} 

Upvotes: 0

noelicus
noelicus

Reputation: 15055

2 problems I can see:

1) I'd stick to wide-strings only, if that's what you need. Try calling DeleteFile instead (assuming your project is UNICODE), which you can pass a wide-string.

2) You are using relative paths, where an absolute one would be more robust.

Upvotes: 0

Related Questions