liaogang
liaogang

Reputation: 518

How to get sub directory while using WinAPI `ReadDirectoryChangesW`?

How to get sub directory while using WinAPI ReadDirectoryChangesW , with param BOOL bWatchSubtree = TRUE ?

MSDN says , if this parameter is TRUE, the function monitors the directory tree rooted at the specified directory.
This api only return a list of PFILE_NOTIFY_INFORMATION , witch only contains a filename info .
While how do i know witch sub directory is the file located?

typedef struct _FILE_NOTIFY_INFORMATION {
  DWORD NextEntryOffset;
  DWORD Action;
  DWORD FileNameLength;
  WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;





  void Watch()
{
    while(bShouldWatch)
    {
        if(::ReadDirectoryChangesW(hDir,
                                   myOverLapped.notify,sizeof(myOverLapped.notify),
                                   TRUE,
                                   FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME,
                                   0,&(myOverLapped.overlapped),0))
        {
            DWORD w=::WaitForSingleObject(myOverLapped.overlapped.hEvent,INFINITE);
            if (w==WAIT_OBJECT_0){
                FILE_NOTIFY_INFORMATION *pNotify=(FILE_NOTIFY_INFORMATION*)myOverLapped.notify;
                HandleNotify(pNotify);
                NotifyMsg(WM_PL_TRACKNUM_CHANGED,(WPARAM)pPL,NULL);
            }
        }
    }
    
    
}


void HandleNotify(FILE_NOTIFY_INFORMATION *pNotify)
{
    
    TCHAR szPath[MAX_PATH];
    TCHAR pathFrom[MAX_PATH];
    TCHAR pathTo[MAX_PATH];
    memset(pathTo,0,sizeof(pathTo));
    
    INT len=0;
    
    while(1)
    {
        wcsncpy(pathTo+len,pNotify->FileName,pNotify->FileNameLength/sizeof(TCHAR));
        
        switch(pNotify->Action)
        {
            case FILE_ACTION_ADDED:
                break;
            case FILE_ACTION_REMOVED:
                break;
            case FILE_ACTION_RENAMED_OLD_NAME:
                break;
            case FILE_ACTION_RENAMED_NEW_NAME:
                break;
        }
        
        if(pNotify->NextEntryOffset!=0)
            pNotify=(FILE_NOTIFY_INFORMATION*)((BYTE*)pNotify+pNotify->NextEntryOffset);
        else break;
    }

Upvotes: 0

Views: 428

Answers (1)

Harry Johnston
Harry Johnston

Reputation: 36308

From the documentation [emphasis mine]:

FileName

A variable-length field that contains the file name relative to the directory handle.

In other words, if the notification is for a file in a subdirectory, FileName includes the relative path, e.g., it will be subdir\file.txt rather than just file.txt.

Upvotes: 3

Related Questions