【发布时间】:2018-05-09 00:57:43
【问题描述】:
我正在尝试使用 C++ 在 Windows 中使用 FirstChangeNotification 查找文件是否被修改。我可以使用FileSystemWatcher 类来做同样的事情吗?如果可能的话,谁能为我提供两种方式的解决方案?我已经搜索并发现了我无法理解的 sn-ps,因为我是这些主题的初学者。
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
int main(int argc, char argv[])
{
DWORD dwWaitStatus;
HANDLE dwChangeHandles[2];
LPCWSTR DirName = L"F:\\myproject";
LPCWSTR DirName1 = L"F:\\";
dwChangeHandles[0] = FindFirstChangeNotification(
DirName,FALSE,FILE_NOTIFY_CHANGE_FILE_NAME);
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
ExitProcess(GetLastError());
else
printf("FindFirstChangeNotification() for file change is
OK.\n");
dwChangeHandles[1] = FindFirstChangeNotification(
DirName1,TRUE,FILE_NOTIFY_CHANGE_DIR_NAME);
if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
{
printf("Something wrong!\n");
ExitProcess(GetLastError());
}
else
printf("FindFirstChangeNotification() for directory change is
OK.\n");
if (dwChangeHandles[0] != INVALID_HANDLE_VALUE &&
dwChangeHandles[1] != INVALID_HANDLE_VALUE)
{
printf("\nI'm monitoring any file deletion/creation in %S
and\n", DirName);
printf("I'm monitoring any directory deletion/creation in
%S.\n", DirName1);
}
while (TRUE)
{
dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE,
INFINITE);
switch (dwWaitStatus)
{
case 0:
if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
{
printf("FindNextChangeNotification() not OK\n");
ExitProcess(GetLastError());
}
else
printf("File created/deleted in %S.\n", DirName);
break;
case 1:
if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)
ExitProcess(GetLastError());
else
printf("Directory was deleted/created in %S.\n",
DirName1);
break;
default:
printf("FindNextChangeNotification(): Invalid return
value.\n");
ExitProcess(GetLastError());
}
}
if(FindCloseChangeNotification(dwChangeHandles[0]) != 0)
printf("FindCloseChangeNotification() is OK\n");
if(FindCloseChangeNotification(dwChangeHandles[1]) != 0)
printf("FindCloseChangeNotification() is OK\n");
return 0;
}
上面的代码是用 C 编写的,我已将其更改为 C++ 并执行它。它适用于文件创建和删除。但是当我使用 FILE_NOTIFY_CHANGE_LAST_WRITE 而不是 FILE_NOTIFY_FILE_NAME 时,它会打印
声明两次。
【问题讨论】:
-
你可以在 python 中用一行来做到这一点...... C++ 对于这个任务可能是过度杀伤
-
你能帮我用c++吗..因为这是我要做的项目..
-
@user1767754 建议另一种语言是一种不好的做法。
-
@iBug 你能帮忙吗?
-
为什么你使用
FindFirstChangeNotification的多个句柄而不是ReadDirectoryChangesW的一个 句柄?为什么这是同步循环而不是异步回调?