可能是以下原因导致ReadDirectoryChangesW无法
调用
回调
函数
:
使用异步IO时,未等待异步操作完成就退出了
应用
程序。
回调
函数
的参数不正确,使得回调
函数
无法执行。
枚举目录时,找不到目录或文件。
下面是一个示例代码,展示了如何正确使用ReadDirectoryChangesW和回调
函数
:
#include <Windows.h>
#include <iostream>
using namespace std;
void CALLBACK DirectoryCallback(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
cout << "Directory changed!" << endl;
// 重新等待目录变化通知
ReadDirectoryChangesW(reinterpret_cast<HANDLE>(lpOverlapped->hEvent), lpOverlapped->lpBuffer,
lpOverlapped->hEvent ? 1 : 0, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE, nullptr, lpOverlapped, DirectoryCallback);
int main()
WCHAR buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);
// 创建目录变化通知对象
HANDLE hDirectory = CreateFileW(L".", FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr);
if (hDirectory == INVALID_HANDLE_VALUE)
cerr << "Failed to create directory handle" << endl;
return -1;
// 开始等待目录变化通知
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
ReadDirectoryChangesW(hDirectory, buffer, MAX_PATH, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE, nullptr, &overlapped, DirectoryCallback);
// 循环等待回调函数被调用
while (true)
SleepEx(INFINITE, TRUE);
// 关闭目录变化通知对象
CloseHandle(hDirectory);
return 0;