vc++ 监控指定路径下文件变化实现代码

时间:2021-05-19

参考MSDN文档

https://docs.microsoft.com/zh-cn/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw

https://docs.microsoft.com/zh-cn/windows/desktop/api/winnt/ns-winnt-_file_notify_information

具体看代码

# include < iostream > # include < windows.h > # include < process.h > # include < tchar.h > # include < string >using namespace std;typedef void( * CHANGESCALLBACK)(const std::wstring strFileName);void CheckFilesChanges(const std::wstring strDirPath, DWORD dwChangesType, CHANGESCALLBACK onCallBack);void PrintMsg(const std::wstring strFileName) { wprintf_s(L "new add File:\t %s\r\n", strFileName.c_str());}void CheckFilesChanges(const std::wstring strDirPath, DWORD dwChangesType, CHANGESCALLBACK onCallBack) { if (strDirPath.empty() || !onCallBack) return; HANDLE hDir = INVALID_HANDLE_VALUE; BYTE lpBuffer[1024]; ZeroMemory(lpBuffer, 1024); DWORD cbBytes = NULL; BOOL isOk = FALSE; FILE_NOTIFY_INFORMATION * pnotify = (FILE_NOTIFY_INFORMATION * )lpBuffer; FILE_NOTIFY_INFORMATION * tmp; ZeroMemory( & lpBuffer, sizeof(FILE_NOTIFY_INFORMATION)); hDir = CreateFile(strDirPath.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (INVALID_HANDLE_VALUE == hDir) return; while (true) { isOk = ReadDirectoryChangesW(hDir, & lpBuffer, sizeof(lpBuffer), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, & cbBytes, NULL, NULL); if (isOk) { tmp = pnotify; PWSTR fileName = nullptr; std::wstring strFileName; if (tmp->FileNameLength) { DWORD dwLength = tmp->FileNameLength + 1; fileName = new wchar_t[dwLength]; if (fileName) { memset(fileName, 0, dwLength * 2); memcpy(fileName, tmp->FileName, dwLength * 2); strFileName = fileName; } if (fileName) delete []fileName; } if (tmp->Action == dwChangesType) { onCallBack(strFileName); } ZeroMemory(tmp, 1024); } } CloseHandle(hDir);}unsigned int CALLBACK ThreadProc(void * arg) { CheckFilesChanges(_T("E:\\GoCode"), FILE_ACTION_ADDED, PrintMsg); return 0;}int main(int argc, char * argv[]) { HANDLE hThread = NULL; hThread = (HANDLE)::_beginthreadex(nullptr, NULL, ThreadProc, NULL, NULL, NULL); system("pause"); return 0;}

好了这篇文章就介绍到这了,需要的朋友可以参考一下。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章