监控目录下文件变化

有关目录监视可能讨论过很多了,但大多使用FindFirstChangeNotification,FindCloseChangeNotification,FindNextChangeNotification这三个函数来做的,他们的问题是不能直接指出发生改变的文件名,而用ReadDirectoryChangesW就可以知道发生改变的文件名。

    这个程序可以监视一个目录中的任何变化,并指出发生改变的文件。但是还有一个小问题,就是处于监视下的目录中的任何文件都不能改名了,不知道为什么。

    程序贴过来的时候缩进没了,看起来费劲些,抱歉。

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>

typedef struct parm
{
char dir[128];
HANDLE hDir;
} THREAD_PARAM;

DWORD WINAPI thread(LPVOID lParam)
{
THREAD_PARAM *Par=(THREAD_PARAM *)lParam;
char notify[1024];
FILE_NOTIFY_INFORMATION *pnotify=(FILE_NOTIFY_INFORMATION *)notify;
char AnsiChar[3];
wchar_t UnicodeChar[2];
DWORD cbBytes;
printf("Watch [%s] start./n",Par->dir);
while(true)
{
if(ReadDirectoryChangesW(Par->hDir,
&notify,
sizeof(notify),
true,
FILE_NOTIFY_CHANGE_FILE_NAME|
FILE_NOTIFY_CHANGE_DIR_NAME|
FILE_NOTIFY_CHANGE_ATTRIBUTES|
FILE_NOTIFY_CHANGE_SIZE|
FILE_NOTIFY_CHANGE_LAST_WRITE|
FILE_NOTIFY_CHANGE_LAST_ACCESS|
FILE_NOTIFY_CHANGE_CREATION|
FILE_NOTIFY_CHANGE_SECURITY,
&cbBytes,
NULL,
NULL))
{
switch(pnotify->Action)
{
case FILE_ACTION_ADDED:
printf("Directory/File added - ");
break;
case FILE_ACTION_REMOVED:
printf("Directory/File removed - ");
break;
case FILE_ACTION_MODIFIED:
printf("Directory/File modified - ");
break;
case FILE_ACTION_RENAMED_OLD_NAME:
printf("Directory/File old name - ");
break;
case FILE_ACTION_RENAMED_NEW_NAME:
printf("Directory/File new name - ");
break;
}
printf("%s",Par->dir);
for(DWORD i=0;i<pnotify->FileNameLength/2;i++)
{
UnicodeChar[0]=pnotify->FileName[i];
UnicodeChar[1]=0;
ZeroMemory(AnsiChar,3);
WideCharToMultiByte(CP_ACP,0,UnicodeChar,-1,AnsiChar,3,NULL,NULL);
printf("%s",AnsiChar);
}
printf("/n");
}
}


}

int main(int argc,char **argv)
{
DWORD ThreadId;
THREAD_PARAM Par;
HANDLE hThread;
if(argc!=2)
{
printf("DirWatch <Directory>/n");
return 0;
}
lstrcpyn(Par.dir,argv[1],127);
Par.hDir = CreateFile(
Par.dir, // pointer to the file name
FILE_LIST_DIRECTORY, // access (read/write) mode
FILE_SHARE_READ|FILE_SHARE_DELETE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
FILE_FLAG_BACKUP_SEMANTICS, // file attributes
NULL // file with attributes to copy
);
if(Par.hDir)
{
printf("Open Directory [%s] successfully./n",Par.dir);

}
else
{
printf("Open Directory [%s] failed./n",Par.dir);
return 0;
}
hThread=CreateThread(NULL,0,thread,(LPVOID *)&Par,0,&ThreadId);
if(hThread)
{
printf("CreateThread OK./n");
printf("Press <q> to quit./n");
while(getch()!='q');
TerminateThread(hThread,0);
WaitForSingleObject(hThread,1000);
CloseHandle(Par.hDir);
}
else
{
printf("CreateThread failed, the program exit./n");
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值