#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
UINT MonitorFileThreadProc(LPVOID lpVoid)
{
char *pszDirectory = (char *)lpVoid;
// 打开目录, 获取文件句柄
HANDLE hDirectory = CreateFile(pszDirectory, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == hDirectory)
return 1;
char szFileName[MAX_PATH] = { 0 };
BOOL bRet = FALSE;
DWORD dwRet = 0;
DWORD dwBufferSize = 2048;
// 申请一个足够大的缓冲区
BYTE *pBuf = new BYTE[dwBufferSize];
if (NULL == pBuf)
return 2;
FILE_NOTIFY_INFORMATION *pFileNotifyInfo = (FILE_NOTIFY_INFORMATION *)pBuf;
// 开始循环设置监控
do
{
RtlZeroMemory(pFileNotifyInfo, dwBufferSize);
// 设置监控目录
bRet = ReadDirectoryChangesW(hDirectory, pFileNotifyInfo, dwBufferSize, TRUE,
FILE_NOTIFY_CHANGE_FILE_NAME |// 修改文件名
FILE_NOTIFY_CHANGE_ATTRIBUTES |// 修改文件属性
FILE_NOTIFY_CHANGE_LAST_WRITE,// 最后一次写入
&dwRet, NULL, NULL);
if (FALSE == bRet)
break;
// 将宽字符转换成窄字符,宽字节字符串转多字节字符串
WideCharToMultiByte(CP_ACP, 0, (wchar_t *)(&pFileNotifyInfo->FileName),
(pFileNotifyInfo->FileNameLength / 2),szFileName,MAX_PATH,NULL,NULL);
// 将路径与文件连接成完整文件路径
char FullFilePath[1024] = { 0 };
strncpy(FullFilePath, pszDirectory, strlen(pszDirectory));
strcat(FullFilePath, szFileName);
// 判断操作类型并显示
switch (pFileNotifyInfo->Action)
{
case FILE_ACTION_ADDED:
printf("文件被 [创建]: %s \n", FullFilePath); break;
case FILE_ACTION_REMOVED:
printf("文件被 [删除]: %s \n", FullFilePath); break;
case FILE_ACTION_MODIFIED:
printf("文件被 [修改]: %s \n", FullFilePath); break;
case FILE_ACTION_RENAMED_OLD_NAME:
printf("文件被 [重命名]: %s \n", FullFilePath); break;
}
} while (bRet);
CloseHandle(hDirectory);
delete[] pBuf;
pBuf = NULL;
return 0;
}
int main(int argc, char * argv[])
{
char *pszDirectory = "C:\\";
// 创建线程开始监控
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MonitorFileThreadProc, pszDirectory, 0, NULL);
while (1)
{
Sleep(10000);
}
system("pause");
return 0;
}
|