我用BCB写了一个监视某个目录(如果要监视一个已经存在文件原理是一样的,而且
应该说更简单一些)
调用了以下API:
FindFirstChangeNotification()
FindNextChangeNotification()
WaitForSingleObject()
三个函数的具体含义和参数请参看MSDN或WIN32 HELP
然后为了保证在监视的时候避免死锁,而无法做其他的控制操作,因此我采用了线程
来设计这些功能,我将部分代码贴出来,如果需要,可以找我全部代码.
//--以下是用于监视的函数-----------START------
bool WatchResume(HANDLE hWatched,unsigned int interval)
{
DWORD rWatch;
//pathname="C://inetpub";
rWatch=FindNextChangeNotification(hWatched);
do{
rWatch = WaitForSingleObject(hWatched, interval);
}while((rWatch!=0)&&(!terminateFlag));
return rWatch;
}
HANDLE WatchCreate(LPCTSTR pathname,unsigned long flags)
{
return FindFirstChangeNotification(pathname, true,flags);
}
DWORD WatchDirectory(HANDLE hWatched,unsigned long interval)
{
DWORD rWatched;
do{
rWatched=WaitForSingleObject(hWatched,interval);
}while((rWatched!=0)&&(!terminateFlag));
return rWatched;
}
void WatchDelete(HANDLE hWatched)
{
DWORD rWatched;
terminateFlag=true;
FindCloseChangeNotification(hWatched);
}
//-----------以上是用于监视的函数-------END
//与相关线程相关的函数
__fastcall TWatchThread::TWatchThread(int theFlag):TThread(true)
{
FreeOnTerminate=true;
flag=theFlag;
logmsg="";
Resume();
}
void __fastcall TWatchThread::Execute(void)
{
DWORD watchStatus;
WIN32_FIND_DATA FileInfo;
HANDLE FileHandle;
unsigned int i;
static FILETIME WriteTime;
terminateFlag=false;
if (flag==1){ //监视文件的创建,重命名,删除,覆盖
hWatched = WatchCreate("C://InetPub",FILE_NOTIFY_CHANGE_FILE_NAME);
watchStatus = WatchDirectory(hWatched, 100);
if (watchStatus==0){
logmsg="有文件被创建,重命名,删除或者覆盖了!";
Synchronize(Writelog);
}
}else if(flag==2){ //监视文件的修改
hWatched = WatchCreate("C://InetPub",FILE_NOTIFY_CHANGE_LAST_WRITE);
watchStatus = WatchDirectory(hWatched, 100);
if (watchStatus==0){
//ShowMessage("文件变化了!");
logmsg="有文件的内容被被修改了!";
Synchronize(Writelog);
}
}
}
void __fastcall TWatchThread::Writelog(void)
{
Form1->Memo1->Lines->Add(logmsg);
}
//在头文件中的声明
class TWatchThread
ublic TThread
{
public:
__fastcall TWatchThread(int theFlag);
private:
int flag;
char *logmsg;
void __fastcall Execute(void);
void __fastcall Writelog(void);
};
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TButton *Button2;
TMemo *Memo1;
TButton *Button3;
TButton *Button4;
TLabel *Label1;
TClientSocket *ClientSocket1;
TPanel *Panel1;
TComboBox *ComboBox1;
TLabel *Label2;
TMemo *Memo2;
TTimer *Timer1;
void __fastcall Button1Click(TObject *Sender);
void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
void __fastcall FormCreate(TObject *Sender);
void __fastcall Button3Click(TObject *Sender);
void __fastcall Button4Click(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
void __fastcall Timer1Timer(TObject *Sender);
private: // User declarations
TWatchThread *WatchWrite,*WatchChange;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//启动线程
WatchWrite=new TWatchThread(1);
WatchChange=new TWatchThread(2);
目前我可以实时监视任何目录下的文件的变化,但是我现在缺乏一个方案:
即发现哪个文件变化了,只能知道我监视的目录下有文件变化了
还希望各位大虾帮忙解决