为什么这种删除文件夹中文件的方法不起作用?

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

本文关键字:方法 不起作用 文件 中文 删除 文件夹 为什么      更新时间:2023-10-16
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

我不明白为什么它不起作用,我认为这与 wstring 和字符串之间的转换有关,但我不确定。我有一个文件夹,其中包含一些.txt文件,我需要使用C++删除所有这些文件。里面没有文件夹。这能有多难?

其次,根据MSDN关于FindFirstFile函数:

"在目录中搜索名称为匹配特定名称(如果使用通配符,则匹配部分名称)。

我在您的输入字符串中看不到通配符,所以我只能猜测FindFirstFile将在当前执行目录中查找名为 "folder" 的文件。

尝试寻找"folder\*"

我可以看到的2个问题:

1)我只会坚持宽弦,如果这是你需要的。尝试改用 DeleteFile(假设您的项目是 UNICODE),您可以传递宽字符串。

2)您使用的是相对路径,其中绝对路径会更健壮。

试试这个:

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 
}