在我当前的项目中,我们需要检查文件是否仍在复制。
我们已经开发了一个库,它将向我们提供操作系统通知,例如特定文件夹上的 file_added 、 file_removed 、 file_modified 、 file_renamed 以及相应的文件路径。
这里的问题是,假设您添加 1 GB 文件,它会在复制文件时发出多个通知,例如 file_added 、 file_modified 、 file_modified 。
现在我决定通过检查文件是否正在复制来超越这些通知。基于此我将忽略事件。
我用 C++ 编写了下面的函数,它告诉文件是否正在被复制,它以文件路径作为输入。 详细信息:- 基本上它使用 Windows API“CreateFile”来获取文件句柄。如果我们无法获取句柄,则确定文件正在被复制。
问题:- 对于一些较大的文件,例如 2 GB 的 .rar 和 .exe 格式,这不起作用。您能告诉我这是正确的方法吗?如果不欣赏其他方法。
bool isFileBeingCopied(const boost::filesystem::path &filePath)
{
//Log(INFO, "Checking if the given file is being copied or not for the file [%s]",filePath.string().c_str());
HANDLE hFile = ::CreateFile(filePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
DWORD dwLastError = GetLastError();
if(hFile == NULL && hFile == INVALID_HANDLE_VALUE)
{
Log(INFO, "Gained invalid handle on the file - hence determining it, as being copied file [%s]",filePath.string().c_str());
return true;
}
else
{
if(dwLastError == ERROR_SUCCESS )
{
CloseHandle(hFile);
Log(INFO, "Able to gain the handle on the file - hence determining it, as copied file [%s]",filePath.string().c_str());
return false;
}
else
{
Log(INFO, "Not able to gain the handle for the file - hence determining it, as being copied file [%s]",filePath.string().c_str());
return true;
}
}
}
最佳答案
除非您自己复制文件,否则无法从外部确定文件的复制状态。您可能必须使用计时器来检测文件修改事件何时停止发送给您。
关于c++ - 如何使用 Windows API 检查文件是否仍在 cpp 中复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12758406/