使用ReadDirectoryChangesW API监视目录

时间:2011-02-14 11:32:48

标签: c winapi filenames systems-programming readdirectorychangesw

我正在尝试使用ReadDirectoryChangesW API监控目录e:\test

我的代码:

#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参数。

当我运行代码时,除了空白控制台窗口外,我没有得到任何输出。有人能指出我正确的方向吗?

感谢。

1 个答案:

答案 0 :(得分: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);
    }