在我当前的项目中,我们需要检查文件是否仍在复制。
我们已经开发了一个库,它将在特定文件夹以及相应的文件路径上向我们提供诸如 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;
}
}
}