2

我正在嘗試使用ReadDirectoryChangesW API監控目錄e:\test使用ReadDirectoryChangesW監控目錄API

我的代碼:

#define UNICODE 
#define WIN32_WINNT 0x0500 
#include "stdafx.h" 
#include <stdio.h> 
#include <windows.h> 


HANDLE hDir; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    FILE_NOTIFY_INFORMATION fniDir; 
    DWORD i = 0; 

    hDir = CreateFile(_T("e:\\test"), GENERIC_READ , FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 

    ReadDirectoryChangesW(hDir, &fniDir, sizeof(fniDir), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME, &i, NULL, NULL); 
    while(TRUE) 
    { 


    if(i>0) 
     wprintf(L"%s", fniDir.FileName); 
    } 

    CloseHandle(hDir); 

    return 0; 
} 

我不知道,因爲我沒有理解ReadDirectoryChangesW文檔完全,特別是LPOVERLAPPED參數有什麼錯我的代碼。

當我運行代碼時,我沒有得到任何輸出,除了一個空白的控制檯窗口。有人能指引我正確的方向嗎?

謝謝。

回答

8

如果您計劃異步捕獲更改通知,則只需要重疊結構。在你的代碼中你不需要它。

以下是您的操作方法。

HANDLE hDir = CreateFile( 
     p.string().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(hDir == INVALID_HANDLE_VALUE){ 
     throw runtime_error(string("Could not open ").append(p.string()).append(" for watching!")); 
    } 

    FILE_NOTIFY_INFORMATION buffer[1024]; 
    DWORD BytesReturned; 
    while(ReadDirectoryChangesW(
     hDir, /* handle to directory */ 
     &buffer, /* read results buffer */ 
     sizeof(buffer), /* length of buffer */ 
     TRUE, /* monitoring option */   
     FILE_NOTIFY_CHANGE_LAST_WRITE, /* filter conditions */ 
     &BytesReturned, /* bytes returned */ 
     NULL, /* overlapped buffer */ 
     NULL)){ 
      do{ 
          //CANT DO THIS! FileName is NOT \0 terminated 
       //wprintf("file: %s\n",buffer.FileName); 
          buffer += buffer.NextEntryOffset; 
      }while(buffer.NextEntryOffset); 
    } 
+0

+1感謝您的回答。我有幾個問題爲什麼我們必須創建`FILE_NOTIFY_INFORMATION`數組以及什麼是'NextEntryOffset`這是否意味着它包含要轉到數組中下一條記錄的字節數? – Searock 2011-02-14 12:25:35