1. 程式人生 > >VC++檔案監控(一) ReadDirectoryChangesW

VC++檔案監控(一) ReadDirectoryChangesW

VC++實施檔案監控:例項和詳解

我這裡只介紹採用ReadDirectoryChangesW對檔案目錄實施監控

關鍵程式碼

?
CfgdsgDlg * dlg = (CfgdsgDlg*)lparam; HANDLE hDir; char notify[1024]; DWORD cbBytes,i; char AnsiChar[3]; wchar_t UnicodeChar[2]; CString path; FILE_NOTIFY_INFORMATION *pnotify=(FILE_NOTIFY_INFORMATION *)notify; FILE_NOTIFY_INFORMATION *tmp;
GetCurrentDirectory(MAX_PATH,path.GetBuffer(MAX_PATH+1)); hDir = CreateFile( path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (hDir == INVALID_HANDLE_VALUE) { dlg->m_edit.ReplaceSel(
"hDir:INVALID_HANDLE_VALUE\r\n"); return 0; } while (TRUE) { if(ReadDirectoryChangesW(hDir, &notify, sizeof(notify), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME| FILE_NOTIFY_CHANGE_LAST_WRITE, &cbBytes, NULL, NULL)) { tmp = pnotify; switch(tmp->Action) { case FILE_ACTION_ADDED: dlg->m_edit.ReplaceSel(
"Directory/File added (新增檔案)- \r\n"); break; case FILE_ACTION_REMOVED: dlg->m_edit.ReplaceSel("Directory/File removed (刪除檔案)- \r\n"); break; case FILE_ACTION_MODIFIED: dlg->m_edit.ReplaceSel("Directory/File modified (修改檔案內容)- \r\n"); break; case FILE_ACTION_RENAMED_OLD_NAME: dlg->m_edit.ReplaceSel("Directory/File old name (修改檔名字)- \r\n"); break; case FILE_ACTION_RENAMED_NEW_NAME: dlg->m_edit.ReplaceSel("Directory/File new name - \r\n"); break; default: break; } } }

FILE_NOTIFY_INFORMATION //可以確定是那個檔案進行的修改

typedef struct _FILE_NOTIFY_INFORMATION {
  DWORD NextEntryOffset;
  DWORD Action;//動作
  DWORD FileNameLength;//檔名字的長度
  WCHAR FileName[1];//檔名字
} FILE_NOTIFY_INFORMATION,
*PFILE_NOTIFY_INFORMATION;

ReadDirectoryChangesW 返回型別(見MSDN)

Value Meaning

FILE_ACTION_ADDED
0x00000001

The file was added to the directory.

FILE_ACTION_REMOVED
0x00000002

The file was removed from the directory.

FILE_ACTION_MODIFIED
0x00000003

The file was modified. This can be a change in the time stamp or attributes.

FILE_ACTION_RENAMED_OLD_NAME
0x00000004

The file was renamed and this is the old name.

FILE_ACTION_RENAMED_NEW_NAME
0x00000005

The file was renamed and this is the new name.

效果如下:

不足的地方:

只能檢測到指定目錄和下一級目錄,超過目錄級數,該函式檢測不到。