目录文件监控

// 监视文件夹中文件变化.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <string>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	//监控主文件夹变化 
	string dir = "d:\\QLDownload\\"; 
	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; 
	} 

	char notify[1024]; 
	memset(notify, 0, 1024); 
	DWORD cbBytes;  
	FILE_NOTIFY_INFORMATION *pNotify=(FILE_NOTIFY_INFORMATION *)notify; 
	char str1[MAX_PATH], str2[MAX_PATH]; 

	while ( 1 ) 
	{    
		if(ReadDirectoryChangesW(dwRootDirChangeHandle, ¬ify, sizeof(notify), 
			FALSE, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_DIR_NAME/*FILE_NOTIFY_CHANGE_LAST_WRITE*/, &cbBytes, NULL, NULL)) 
		{            
			int i = 0; 
			memset(str1, 0, MAX_PATH); 
			WideCharToMultiByte( CP_ACP,0,pNotify->FileName, pNotify->FileNameLength/2, str1,99,NULL,NULL ); 

			switch(pNotify->Action) 
			{ 
			case FILE_ACTION_ADDED: 
				printf("New Folder: %s\n", str1); 
				break; 
			case FILE_ACTION_MODIFIED: 
				printf("The file was modified. This can be a change in the time stamp or attributes.\n"); 
				break; 
			case FILE_ACTION_REMOVED: 
				printf("The file was removed from the directory.\n"); 
				break; 
			case FILE_ACTION_RENAMED_NEW_NAME: 
				printf("The file was renamed and this is the new name.\n"); 
				break; 
			case FILE_ACTION_RENAMED_OLD_NAME: 
				printf("The file was renamed and this is the old name.\n"); 
				break; 
			default: 
				printf("Unknown command.\n"); 
			}        
		} 
	} 
	::CloseHandle(dwRootDirChangeHandle); 
	return 0;
}


参考自: http://blog.csdn.net/woshinia/article/details/8162983

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值