转自:http://www.cnblogs.com/mumuli/p/4364386.html
#include <windows.h>
#include <tchar.h>
#include <stdio.h>#include <assert.h>char* WideCharToMultiByte(LPCTSTR widestr)
{int num = WideCharToMultiByte(CP_OEMCP,NULL,widestr,-1,NULL,0,NULL,FALSE);char *pchar = new char[num];WideCharToMultiByte (CP_OEMCP,NULL,widestr,-1,pchar,num,NULL,FALSE);return pchar;
}bool IsDirectory(const LPTSTR & strPath)
{DWORD dwAttrib = GetFileAttributes( strPath );return static_cast<bool>( ( dwAttrib != 0xffffffff && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) );
}int main()
{HANDLE hDir;BYTE* pBuffer = (LPBYTE)new CHAR[4096];DWORD dwBufferSize;LPTSTR lpPath = _T("D:\\同步目录\\");WCHAR szFileName[MAX_PATH];char* szFilePath;PFILE_NOTIFY_INFORMATION pNotify = (PFILE_NOTIFY_INFORMATION)pBuffer;hDir = CreateFile( lpPath, FILE_LIST_DIRECTORY,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);if (hDir == INVALID_HANDLE_VALUE){printf("INVALID_HANDLE_VALUE");return 0;}while (TRUE){if(ReadDirectoryChangesW(hDir, pBuffer, 4096, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &dwBufferSize, NULL, NULL)){memset(szFileName, 0, MAX_PATH);memcpy(szFileName, lpPath, _tcslen(lpPath) * sizeof(WCHAR));memcpy(szFileName + _tcslen(lpPath), pNotify->FileName, pNotify->FileNameLength);szFilePath = WideCharToMultiByte(szFileName);switch(pNotify->Action){case FILE_ACTION_ADDED:if (IsDirectory(szFileName)){printf("Directory %s added.\n", szFilePath);}else{printf("File %s added.\n", szFilePath);}break;case FILE_ACTION_REMOVED:if (IsDirectory(szFileName)){printf("Directory %s removed.\n", szFilePath);}else{printf("File %s removed.\n", szFilePath);}break;case FILE_ACTION_MODIFIED:if (!IsDirectory(szFileName)){printf("File %s modified.\n", szFilePath);}break;case FILE_ACTION_RENAMED_OLD_NAME:if (pNotify && pNotify->NextEntryOffset != 0UL){PFILE_NOTIFY_INFORMATION pNext = (PFILE_NOTIFY_INFORMATION) ((LPBYTE)pNotify + pNotify->NextEntryOffset);assert((DWORD)((BYTE*)pNext - pBuffer) < dwBufferSize);{WCHAR szFileName2[MAX_PATH];char* szFilePath2;memset(szFileName2, 0, MAX_PATH);memcpy(szFileName2, lpPath, _tcslen(lpPath) * sizeof(WCHAR));memcpy(szFileName2 + _tcslen(lpPath), pNext->FileName, pNext->FileNameLength);szFilePath2 = WideCharToMultiByte(szFileName2);if (IsDirectory(szFileName2)){printf("Directory name changed from %s to %s.\n", szFilePath, szFilePath2);}else{printf("File name changed from %s to %s.\n", szFilePath, szFilePath2);}}}break;case FILE_ACTION_RENAMED_NEW_NAME:printf("FILE_ACTION_RENAMED_NEW_NAME.\n");break;default:break;}}}
}
关于ReadDirectoryChangesW的详细介绍可以查看
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465(v=vs.85).aspx