【问题标题】:Why doesn't this method of deleting files inside a folder work?为什么这种删除文件夹内文件的方法不起作用?
【发布时间】:2012-09-17 15:10:44
【问题描述】:
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 和 string 之间的转换有关,但我不确定。我有一个包含一些 .txt 文件的文件夹,我需要使用 C++ 删除所有这些文件。里面没有文件夹什么都没有。这有多难?

【问题讨论】:

  • 您是否尝试将inxmpath 设置为绝对文件夹路径?
  • .exe 和“文件夹”在同一个文件夹中。如果是这种情况,我不确定是否需要这样做。
  • “不起作用”没有帮助。您观察到什么与您的预期相比,您已经尝试解决什么问题?

标签: c++ winapi directory delete-file


【解决方案1】:

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

"在目录中搜索具有以下名称的文件或子目录 匹配特定名称(如果使用通配符,则匹配部分名称)。”

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

尝试寻找"folder\\*"

【讨论】:

  • 我会补充一点,FindFirstFile 在错误时返回 INVALID_HANDLE_VALUE,而不是像 OP 所期望的那样返回 0。
【解决方案2】:

我能看到的2个问题:

1) 如果您需要的话,我会只使用宽字符串。尝试改为调用DeleteFile(假设您的项目是UNICODE),您可以传递一个宽字符串。

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

【讨论】:

    【解决方案3】:

    试试这个:

    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 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多