VC++文件监控(一) ReadDirectoryChangesW

From: http://www.cnblogs.com/doublesnke/archive/2011/08/16/2141374.html

VC++实施文件监控:实例和详解

相关帮助: http://hi.baidu.com/jiahaosoft/blog/item/b441d1218eebece0d6cae274.html

我这里只介绍采用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.

效果如下:

VC++文件监控(一) ReadDirectoryChangesW_第1张图片

不足的地方:

只能检测到指定目录和下一级目录,超过目录级数,该函数检测不到。


你可能感兴趣的:(VC++文件监控(一) ReadDirectoryChangesW)