我想做什么:监视给定文件夹及其所有子文件夹中文件内容(在Windows中使用C++)中的任何更改。观察文件夹更改的文件夹和子文件夹未检测到更改
我曾尝试:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
void WatchFileChanges(char *dir) {
while (true)
{
HANDLE dwChangeHandles[1];
dwChangeHandles[0] = FindFirstChangeNotification(
dir, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_LAST_WRITE); // watch file name changes
auto res = WaitForSingleObject(dwChangeHandles, INFINITE);
switch (res)
{
case WAIT_OBJECT_0: std::cout << "changed" << std::endl; break;
case WAIT_TIMEOUT: std::cout << "time's up" << std::endl; break;
}
}
}
int main()
{
WatchFileChanges("D:/myfolder");
return 0;
}
我运行上面的代码,并尝试做(和保存)更改文件的文件夹内,把那“d:/ MyFolder文件”。但是,我的程序中没有任何反应。根本没有显示任何消息,但我希望显示“更改”。
我在做什么错?
如果使用'bWatchSubtree:TRUE',会发生什么? – Dai
@Dai没有什么变化。它仍然没有抓住我所做的任何改变。 – Juddy
许多程序永远不会更改文件。例如,一个文本编辑器从来没有这样做,它太冒险了。您必须包含FILE_NOTIFY_CHANGE_FILE_NAME以查看重命名文件。 –