#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;
}