为什么这种删除文件夹中文件的方法不起作用?
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
我不明白为什么它不起作用,我认为这与 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
}
相关文章:
- 基本加密和解密方法不起作用 C++ 11.
- 结构/方法不起作用
- 将字符数组设置为彼此相等的方法不起作用
- ConvertToReferencePoint 方法不起作用,获取作业参数的 NULL (HyperV 2016)
- 为什么方法不起作用?
- C boost :: bimap insert()方法不起作用
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 为什么这种交换方法不起作用
- Qt. 方法显示文本() 如果我在 QStyledItemDelegate 中定义了 paint() 方法不起作用
- 非递归二进制树插入()方法不起作用
- C++中的Friend方法不起作用
- 为什么这种删除文件夹中文件的方法不起作用?
- 二叉树递归插入方法不起作用
- CGI POST方法不起作用
- 为什么我的 pow 方法不起作用?
- 类方法不起作用
- 使用ctypes从Python调用C++方法不起作用
- C++虚拟方法不起作用
- 为什么用double&&初始化对象方法不起作用?
- 使用虚拟重写基类方法不起作用