gpt4 book ai didi

c++ - 如何防止我的函数在 RemoveDirectory() WINAPI 中延迟删除?

转载 作者:行者123 更新时间:2023-11-30 05:04:09 26 4
gpt4 key购买 nike

如何更正下面的代码使其正常工作?该函数的目的只是删除目录和目录内的文件。

因为当我运行这个函数时(即使在一个单独的线程中),它不会删除第一个参数中传递的文件夹,因为某些句柄存在(可能)。

Windows 在程序结束前不会删除该文件夹,请参见下面的代码。

如何在调用 RemoveDirectory 之前修复现有句柄?

我已经尝试在调用 RemoveDirectory 时将 HANDLE 变量(位于下面的函数内部)移出堆栈。

问题只是在延迟删除文件夹(不是其他文件,它们正常删除)。

int DeleteDirectory(const std::string &refcstrRootDirectory,
bool bDeleteSubdirectories = true)
{
bool bSubdirectory = false; // Flag, indicating whether
// subdirectories have been found
HANDLE hFile; // Handle to directory
std::string strFilePath; // Filepath
std::string strPattern; // Pattern
WIN32_FIND_DATA FileInformation; // File information


strPattern = refcstrRootDirectory + "\\*.*";
hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;

if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(bDeleteSubdirectories)
{
// Delete subdirectory
int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
if(iRC)
return iRC;
}
else
bSubdirectory = true;
}
else
{
// Set file attributes
if(::SetFileAttributes(strFilePath.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();

// Delete file
if(::DeleteFile(strFilePath.c_str()) == FALSE)
return ::GetLastError();
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);

// Close handle
::FindClose(hFile);

DWORD dwError = ::GetLastError();
if(dwError != ERROR_NO_MORE_FILES)
return dwError;
else
{
if(!bSubdirectory)
{
// Set directory attributes
if(::SetFileAttributes(refcstrRootDirectory.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();

// Delete directory
if(::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
return ::GetLastError();
}
}
}
return 0;
}

附注这段代码取自这里: How to delete a folder in C++?

最佳答案

首先,我很抱歉提出这样一个误导性的问题,但是......

我发现了我的错误,它不在我在问题中发布的功能中。

我有一个项目,我在其中使用了我的函数 DirectoryExists,并且标题“opendir”中有一个函数(它是适用于 Windows 的 linux 标题的可移植版本,其中可能有 WINAPI 句柄)。我打开目录后忘记关闭目录以检查它是否存在。

bool DirectoryExists(const std::string & path)
{
DIR *dir = opendir(path.c_str());
if (dir) {
return true;
}
else
return false;
}

我已经更正了错误:

bool DirectoryExists(const std::string & path)
{
DIR *dir = opendir(path.c_str());
closedir(dir);
if (dir) {
return true;
}
else
return false;
}

我希望这个问题可以帮助人们理解为什么 RemoveDirectory() 无法按预期工作。可能有一些您没有注意到的句柄,如果您不是专业的 Windows 程序员,则不是那么清楚。

关于c++ - 如何防止我的函数在 RemoveDirectory() WINAPI 中延迟删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com