#include <Windows.h>
#include <tchar.h>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char str2[1024];
//监控主文件夹变化
string dir = "f:\\test\\";
char notify[1024];
memset(notify, 0, 1024);
DWORD cbBytes;
FILE_NOTIFY_INFORMATION *pNotify=(FILE_NOTIFY_INFORMATION *)notify;
char strNameOld[MAX_PATH],strNameNew[MAX_PATH];
BOOL bReName = FALSE;
HANDLE dwRootDirChangeHandle = CreateFileA(
dir.c_str(), /* pointer to the file name */
FILE_LIST_DIRECTORY, /* (this is important to be FILE_LIST_DIRECTORY!) access (read-write) mode */
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* (file share write is needed, or else user is not able to rename file while you hold it) share mode */
NULL, /* security descriptor */
OPEN_EXISTING, /* how to create */
FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
NULL /* file with attributes to copy */
);
if (dwRootDirChangeHandle == INVALID_HANDLE_VALUE)
{
printf("error: %d", GetLastError());
return 0;
}
while ( 1 )
{
if(ReadDirectoryChangesW(dwRootDirChangeHandle, ¬ify, 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))
{
if(!bReName)
{
memset(strNameOld, 0, MAX_PATH);
}
memset(strNameNew, 0, MAX_PATH);
WideCharToMultiByte( CP_ACP,0,pNotify->FileName, pNotify->FileNameLength/2, strNameNew,MAX_PATH / 2,NULL,NULL );
switch(pNotify->Action)
{
case FILE_ACTION_ADDED:
printf("New Folder: %s\n", strNameNew);
break;
case FILE_ACTION_MODIFIED:
if(bReName){
printf("old name %s, new name %s.\n",strNameOld, strNameNew);
bReName = FALSE;
}
else{
printf("modified name %s\n", strNameNew);
}
break;
case FILE_ACTION_REMOVED:
printf("The file was removed from the directory. %s \n",strNameNew);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
printf("The file was renamed and this is the new name. %s \n",strNameNew);
break;
case FILE_ACTION_RENAMED_OLD_NAME:
printf("The file was renamed and this is the old name %s.\n", strNameNew);
bReName = TRUE;
break;
default:
printf("Unknown command.\n");
}
if( 0 != pNotify->NextEntryOffset && (pNotify->FileNameLength > 0 && pNotify->FileNameLength < MAX_PATH))
{
PFILE_NOTIFY_INFORMATION p = (PFILE_NOTIFY_INFORMATION)((char*)pNotify+pNotify->NextEntryOffset);
memset( str2, 0, sizeof(str2) );
WideCharToMultiByte( CP_ACP,0,p->FileName,p->FileNameLength/2,str2,99,NULL,NULL );
cout << str2 << endl;
}
if(bReName)
{
memcpy(strNameOld, strNameNew, MAX_PATH);
}
}
}
::CloseHandle(dwRootDirChangeHandle);
return 0;
}
文件监视
最新推荐文章于 2023-06-08 21:35:49 发布