在我目前的項目中,我們需要檢查文件是否仍在複製。如何檢查文件是否仍然使用Windows API在cpp中複製?
我們已經開發了一個庫,它會給我們一個特定文件夾的操作系統通知,如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;
}
}
}
這不僅是獨佔訪問,可能會導致'的CreateFile()'失敗。只要該文件未打開進行讀取共享,由於此代碼正在請求它,那麼它將失敗。 –
@RemyLebeau對,以前用'FILE_SHARE_WRITE'打開的文件將導致'CreateFile()'在'isFileBeingCopied()'中失敗。 –
更準確地說,文件不是用'FILE_SHARE_READ'打開的。 –