FindFirstChangeNotification()函数只能监控到目录或是目录中的文件发生了哪种变化,但是更详细的变化信息是不能得到的。要得到更详细的信息,可以使用ReadDirectoryChangesW()函数,下次讲解这个函数的使用方法。
使用举例:
#include "stdafx.h"
void WatchDirectory(LPTSTR lpDir)
{
DWORD dwWaitStatus,dwRet(0);
HANDLE dwChangeHandles[3];
TCHAR lpDrive[4] = {0},lpFile[_MAX_FNAME] = {0},lpExt[_MAX_EXT] = {0};
_tsplitpath(lpDir, lpDrive,NULL, lpFile, lpExt);
lpDrive[2] = (TCHAR)'\\';
lpDrive[3] = (TCHAR)'\0';
//分别监控文件名,路径名,文件内容的修改
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir,
TRUE,
FILE_NOTIFY_CHANGE_FILE_NAME); //文件名
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE){
ExitProcess(GetLastError());
}
dwChangeHandles[1] = FindFirstChangeNotification(
lpDrive,
TRUE,
FILE_NOTIFY_CHANGE_DIR_NAME); //路径名
if (dwChangeHandles[1] == INVALID_HANDLE_VALUE){
ExitProcess(GetLastError());
}
dwChangeHandles[2] = FindFirstChangeNotification(
lpDir,
TRUE,
FILE_NOTIFY_CHANGE_LAST_WRITE); //文件内容/或者说最后保存时间
if (dwChangeHandles[2] == INVALID_HANDLE_VALUE){
ExitProcess(GetLastError());
}
//改变通知已经设置完成,现在只需等待这些通知被触发,然后做相应处理
while (TRUE)
{
dwWaitStatus= WaitForMultipleObjects(3, dwChangeHandles, FALSE, INFINITE);
switch(dwWaitStatus)
{
case WAIT_OBJECT_0:
printf("文件名发生了改变!\n");
if(FindNextChangeNotification(dwChangeHandles[0]) == FALSE ){
ExitProcess(GetLastError());
}
break;
case WAIT_OBJECT_0 + 1:
printf("目录名发生了改变!\n");
if(FindNextChangeNotification(dwChangeHandles[1]) == FALSE){
ExitProcess(GetLastError());
}
break;
case WAIT_OBJECT_0 + 2:
printf("最后保存时间发生了改变!\n");
if(FindNextChangeNotification(dwChangeHandles[2]) == FALSE){
ExitProcess(GetLastError());
}
break;
default:
ExitProcess(GetLastError());
break;
}
}
_endthread();
}
void MonitorThread(void* arg)
{
WatchDirectory("D:\\Data");
}
int _tmain(int argc, _TCHAR* argv[])
{
_beginthread(MonitorThread,10240,NULL);
while (TRUE)
{
Sleep(1000);
}
return 0;
}