VC目录实时监控

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <string>
using namespace std;



class CFileWatcher 
{
public:
 bool StartWatch( string path); //开始监视
 CFileWatcher()  // 初始化
    { 
  hThread=NULL;
  hDir=INVALID_HANDLE_VALUE  ;
 }
    ~CFileWatcher() 
 {
  if(hThread !=NULL)
  {
   ::TerminateThread(hThread, 0 );
   hThread = NULL;
  }
  if(hDir !=INVALID_HANDLE_VALUE)
  {
   CloseHandle( hDir );
   hDir = INVALID_HANDLE_VALUE;
  }
 }
 
private:
    string strWatchedDir;
    HANDLE hThread;
    HANDLE hDir; 
private:
    static DWORD WINAPI ThreadProc( LPVOID lParam ) ; //线程函数,用来监视
};

 

 

 

 


bool CFileWatcher::StartWatch( string path)
{
 strWatchedDir = path;
 
 DWORD ThreadId;  //创建一个新线程用于监视
 hThread=::CreateThread(NULL,0,ThreadProc,this,0,&ThreadId );
 
 return NULL!=hThread;
}

DWORD WINAPI CFileWatcher::ThreadProc( LPVOID lParam )  //线程函数
{
 CFileWatcher* obj = (CFileWatcher*)lParam;  //参数转化
 
 obj->hDir = CreateFile(            //打开目录,得到目录的句柄
  obj->strWatchedDir.c_str(),
  GENERIC_READ|GENERIC_WRITE,
  FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
  NULL,
  OPEN_EXISTING,
  FILE_FLAG_BACKUP_SEMANTICS,
  NULL
        );
 if(obj->hDir ==INVALID_HANDLE_VALUE  )
  return false;
 
 char buf[(sizeof(FILE_NOTIFY_INFORMATION)+MAX_PATH)*2];
 FILE_NOTIFY_INFORMATION* pNotify=(FILE_NOTIFY_INFORMATION*)buf;
 DWORD dwBytesReturned;       
 while(true)
 {
  if( ::ReadDirectoryChangesW( obj->hDir,
   pNotify,
   sizeof(buf),
   true,
   FILE_NOTIFY_CHANGE_FILE_NAME|
   FILE_NOTIFY_CHANGE_DIR_NAME|
   FILE_NOTIFY_CHANGE_LAST_WRITE|
   FILE_NOTIFY_CHANGE_ATTRIBUTES|
   FILE_NOTIFY_CHANGE_CREATION|
   FILE_NOTIFY_CHANGE_SECURITY|
   FILE_NOTIFY_CHANGE_SIZE|
   FILE_NOTIFY_CHANGE_LAST_ACCESS,
      &dwBytesReturned,
   NULL,
   NULL ) )
  {
   char tmp[MAX_PATH], str1[MAX_PATH], str2[MAX_PATH];
   memset( tmp, 0, sizeof(tmp) ); //ZeroMemory()
   WideCharToMultiByte( CP_ACP,0,pNotify->FileName,pNotify->FileNameLength/2,tmp,99,NULL,NULL );
   strcpy( str1, tmp );
   
   if(pNotify->NextEntryOffset !=0 )
   {
    PFILE_NOTIFY_INFORMATION p = (PFILE_NOTIFY_INFORMATION)((char*)pNotify+pNotify->NextEntryOffset);
    memset( tmp, 0, sizeof(tmp) );
    WideCharToMultiByte( CP_ACP,0,p->FileName,p->FileNameLength/2,tmp,99,NULL,NULL );
    strcpy( str2, tmp );
   }
   switch(pNotify->Action)
   {
    case FILE_ACTION_ADDED:
     cout << "添加了新文件: " << str1 << endl; break;
    case FILE_ACTION_REMOVED:
     cout << "删除了文件: " << str1 << endl; break;
    case FILE_ACTION_MODIFIED:
     cout << "修改了文件:" << str1 << endl; break;
    case FILE_ACTION_RENAMED_NEW_NAME:
     cout << "重命名了文件" << str1 << " " << str2 << endl; break;
   }  
  }
  else          
   break;          
 }
 return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值