windows上使用ReadDirectoryChangesW监控某个文件发生了改变。(这个api是阻塞的,最好放到一个线程中去使用)
#include <iostream>
#include <windows.h>
#include <string>
#include <atlstr.h>
#include <tchar.h>
using namespace std;
void fileWatcher()
{
DWORD cbBytes;
char file_name[1024] = ""; //设置文件名
char file_name2[1024] = ""; //设置文件重命名后的名字
char notify[1024] = "";
int count = 0; //文件数量。可能同时拷贝、删除多个文件,可以进行更友好的提示。
CString dir = "c:\\test"; //一定是个目录,不是文件
HANDLE dirHandle = CreateFile(dir, GENERIC_READ | GENERIC_WRITE | FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (dirHandle == INVALID_HANDLE_VALUE)
{
std::cout << "CreateFile error:" + GetLastError() << std::endl;
return;
}
FILE_NOTIFY_INFORMATION *pNotification = (FILE_NOTIFY_INFORMATION *)notify;
cout << "start...." << endl;
BOOL watch_state;
while (true)
{
watch_state = ReadDirectoryChangesW(dirHandle, ¬ify, 1024, true,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME
//| FILE_NOTIFY_CHANGE_CREATION
//| FILE_NOTIFY_CHANGE_LAST_WRITE
| FILE_NOTIFY_CHANGE_SIZE,
&cbBytes, NULL, NULL);
if(watch_state == FALSE)
{
DWORD dwErr = GetLastError();;
cout <<"文件监控失败!" << dwErr << endl;
break;
}
else if (GetLastError() == ERROR_INVALID_FUNCTION)
{
cout << "系统不支持" << endl;
break;
}
else if (GetLastError() == ERROR_NOTIFY_ENUM_DIR)
{
cout << "内存溢出" << endl;
continue;
}
else {
CString szFileName(pNotification->FileName, pNotification->FileNameLength / sizeof(wchar_t));//获取监控到的文件名
if (pNotification->Action == FILE_ACTION_ADDED)
{
cout <<"add file:" << szFileName << endl;
}
else if (pNotification->Action == FILE_ACTION_REMOVED)
{
cout << "del file:" << szFileName <<endl;
}
else if (pNotification->Action == FILE_ACTION_MODIFIED)
{
cout << "mod file:" << szFileName <<endl;
}
else if (pNotification->Action == FILE_ACTION_RENAMED_OLD_NAME)
{
cout << "rename file:" << szFileName << endl;
}
else if (pNotification->Action == FILE_ACTION_RENAMED_NEW_NAME) //还没出现过这种情况
{
cout << "rename2 file:" << szFileName << endl;
}
}
}
CloseHandle(dirHandle);
}
int main(int argc, char* argv[])
{
fileWatcher();
system("pause");
return 0;
}
网友评论