How to monitor a directory for changes with ReadDirectoryChangesW

Here's how to use ReadDirectoryChangesW without knowing all of this and without using this overkill C++ class library (remove the &o parameter in the call to make it blocking instead of async. Note: This only returns one change, you have to step trough a buffer of FILE_NOTIFY_INFORMATIONs if you need to get more):


HANDLE hDirectory;
OVERLAPPED o = {0};
union {
    FILE_NOTIFY_INFORMATION i;
    char d[sizeof(FILE_NOTIFY_INFORMATION)+MAX_PATH];
} fni;


int checkAutoCompile() {
    DWORD b;

    if (!hDirectory) {
        hDirectory = CreateFile(".", 
        FILE_LIST_DIRECTORY | GENERIC_READ, 
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        0, 
        OPEN_EXISTING, 
        FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, 
        0
        );
        o.hEvent = CreateEvent(0,0,0,0);
    }
    ReadDirectoryChangesW(hDirectory,
        &fni,
        sizeof(fni),
        TRUE,
        FILE_NOTIFY_CHANGE_LAST_WRITE,
        &b,
        &o, 
        0);
    
    GetOverlappedResult(hDirectory,&o,&b,FALSE);
    if (fni.i.Action != 0) {
        wprintf(L"action %d, b: %d, %s\n", fni.i.Action, b, fni.i.FileName);
        fni.i.Action = 0;
    }

    return 0;
}

Comments

  1. THANK YOU!!! I just spent 4 hours trying to figure out ReadDirectoryChangesW until I found this. Thanks again man. Peace & Love.

    ReplyDelete
  2. Hi there, I think |'ing the GENERIC_READ is not right, as that is not a access constant, if i or that with FILE_LIST_DIRETORY it is giving me a negative result which wont work as its suppoed to be a DWORD (which is usngiend long)

    ReplyDelete
    Replies
    1. whoops never mind my ctypes const was defined wrong

      Delete
  3. I'm having a major issue, I sometimes get true, but most times false and GetLastError of 6 for ReadDirectoryChangesW. How come you don't pass null to the &b argument, as its async it should be null no? It should not get populated.

    I posted help on stackoverflow: http://stackoverflow.com/questions/29638868/readdirectorychangesw-sometimes-returns-true-sometimes-and-most-other-times-fals?noredirect=1#comment47451723_29638868

    ReplyDelete

Post a Comment

Popular posts from this blog

Coins - Pay to Win

Fastest way to zero out memory - stream past cache with movntdq/_mm_stream_si128