We help IT Professionals succeed at work.

ReadDirectoryChangesW / FWATCH MSDN sample not working!

11,803 Views
Last Modified: 2013-12-03
Ah hello.

I have been looking into how to monitor changes to a directory; i.e. receive notification that a file has been added to a directory.  After reading many previous questions on here and looking at numerous linked articles, I found that the MSDN sample FWATCH was the best way to learn.  So, I downloaded the code and started playing.  I include the code below, with a few minor changes made by myself, for reference.

The program loads the directories/files it watches from an INI file; I modified the file that came with the code on MSDN to watch two directories; I am not interested in files.  My INI file looks like this:

[Files]
[Directories]
c:\temp1=
c:\temp2=

When you look at the code, you will see the function HandleDirectoryChange(), into which I perform a switch on the action performed that caused GetQueuedCompletionStatus() to return.  Now, my questions:

1) I copy a file and paste it into C:\temp1.  HandleDirectoryChange() shows that FILE_ACTION_MODIFIED was the reason for the call.  Why?  I added a file, I did not change one!  Surely it should be FILE_ACTION_ADDED?  In total, for this one paste operation, I get the code under the case for FILE_ACTION_MODIFIED hit *three* times!  Why is this?

2) I add a new file via a right click->New Text Document.  HandleDirectoryChange() gets called.  I then add a second file.  This time, HandleDirectoryChange() does not get called!  Huh?  I then add a third file, it still does not get called.  Only on the fourth file I add does it get called.  Why?

3) I delete a file (one of the many I have created in the above two steps).  HandleDirectoryChange() does not get called at all.  Why?

TIA

Code follows:

// FWatch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

//Main source file for sample demonstrating use of file change
//notification APIs.
//
//Functions:
//
//CheckChangedFile()      - Gets and displays change information
//HandleDirectoryChange() - Watch function
//WatchDirectories()      - Starts the watch
//main()                  - Program main
//
//
//Written by Microsoft Product Support Services, Windows Developer Support.
//Copyright 1996-1997 Microsoft Corporation. All rights reserved.


#define MAX_DIRS    10
#define MAX_FILES   255
#define MAX_BUFFER  4096

// this is the all purpose structure that contains  
// the interesting directory information and provides
// the input buffer that is filled with file change data
typedef struct _DIRECTORY_INFO {
      HANDLE      hDir;
      TCHAR       lpszDirName[MAX_PATH];
      CHAR        lpBuffer[MAX_BUFFER];
      DWORD       dwBufLength;
      OVERLAPPED  Overlapped;
}DIRECTORY_INFO, *PDIRECTORY_INFO, *LPDIRECTORY_INFO;

DIRECTORY_INFO  DirInfo[MAX_DIRS];        // Buffer for all of the directories
TCHAR           FileList[MAX_FILES*MAX_PATH];   // Buffer for all of the files
DWORD           numDirs;


/**********************************************************************
CheckChangedFile()

Purpose:
This function prints out information when one of the files we
are watching is changed.

Parameters:

LPDIRECTORY_INFO lpdi - Information about the watched directory
PFILE_NOTIFY_INFORMATION lpfni - Information about modified file


Return Value:
None

Comments:

********************************************************************/
void WINAPI CheckChangedFile( LPDIRECTORY_INFO lpdi,
                                           PFILE_NOTIFY_INFORMATION lpfni)
{
      TCHAR      szFullPathName[MAX_PATH];
      TCHAR      *p;
      HANDLE     hFile;
      FILETIME   LocalFileTime;
      SYSTEMTIME SystemTime;
      BY_HANDLE_FILE_INFORMATION FileInfo;

      p = FileList;

      while(*p && lstrcmpi(p,lpfni->FileName))
            p+=(lstrlen(p)+1);

      if(*p)
      {
            lstrcpy( szFullPathName, lpdi->lpszDirName );
            lstrcat( szFullPathName, L"\\" );
            lstrcat( szFullPathName, lpfni->FileName );

            // we assume that the file was changed, since
            // that is the only thing we look for in this sample
            wprintf( L"%s changed,", szFullPathName );

            hFile=CreateFile( szFullPathName,
                  GENERIC_READ,
                  FILE_SHARE_READ,
                  NULL,
                  OPEN_EXISTING,
                  FILE_FLAG_SEQUENTIAL_SCAN,
                  0);

            GetFileInformationByHandle( hFile, &FileInfo );

            FileTimeToLocalFileTime( &(FileInfo.ftLastWriteTime), &LocalFileTime );

            FileTimeToSystemTime( &LocalFileTime, &SystemTime );

            wprintf( L" Size = %d bytes,", FileInfo.nFileSizeLow );
            wprintf( L" Last Access = %02d/%02d/%02d %02d:%02d:%02d",
                  SystemTime.wMonth,
                  SystemTime.wDay,
                  SystemTime.wYear,
                  SystemTime.wHour,
                  SystemTime.wMinute,
                  SystemTime.wSecond );

            CloseHandle( hFile );

            wprintf( L"\n" );
      }
}


/**********************************************************************
HandleDirectoryChanges()

Purpose:
This function receives notification of directory changes and
calls CheckChangedFile() to display the actual changes. After
notification and processing, this function calls
ReadDirectoryChangesW to reestablish the watch.

Parameters:

HANDLE hCompPort - Handle for completion port


Return Value:
None

Comments:

********************************************************************/
void WINAPI HandleDirectoryChange( DWORD dwCompletionPort )
{
      DWORD numBytes;
      DWORD cbOffset;
      LPDIRECTORY_INFO di;
      LPOVERLAPPED lpOverlapped;
      PFILE_NOTIFY_INFORMATION fni;
      WCHAR FileName[1000];

      do
      {
            // Retrieve the directory info for this directory
            // through the completion key
            GetQueuedCompletionStatus( (HANDLE) dwCompletionPort,
                  &numBytes,
                  (LPDWORD) &di,      // This is the DIRECTORY_INFO structure that was passed in the call to CreateIoCompletionPort below.
                  &lpOverlapped,
                  INFINITE);

            if ( di )
            {
                  wprintf ( _T("Notify...\n") );
                  fni = (PFILE_NOTIFY_INFORMATION)di->lpBuffer;

                  do
                  {
                        cbOffset = fni->NextEntryOffset;

                        //if( fni->Action == FILE_ACTION_MODIFIED )
                        //      CheckChangedFile( di, fni );

                        //
                        switch ( fni->Action )
                        {
                        case FILE_ACTION_ADDED:
                              wprintf(L"file added: ");
                              break;
                        case FILE_ACTION_REMOVED:
                              wprintf(L"file deleted: ");
                              break;
                        case FILE_ACTION_MODIFIED:
                              wprintf(L"time stamp or attribute changed: ");
                              break;
                        case FILE_ACTION_RENAMED_OLD_NAME:
                              wprintf(L"file name changed - old name: ");
                              break;
                        case FILE_ACTION_RENAMED_NEW_NAME:
                              wprintf(L"file name changed - new name: ");
                              break;
                        default: wprintf(L"unknown event: ");
                              break;
                        }
                        //
                        lstrcpyn(FileName, fni->FileName, fni->FileNameLength / sizeof(WCHAR) + 1);
                        FileName[fni->FileNameLength / sizeof(WCHAR) + 1] = '\0';

                        wprintf(L"%s\n", FileName);

                        fni = (PFILE_NOTIFY_INFORMATION)((LPBYTE) fni + cbOffset);

                  } while( cbOffset );

                  // Reissue the watch command
                  ReadDirectoryChangesW( di->hDir,di->lpBuffer,
                        MAX_BUFFER,
                        TRUE,
                        FILE_NOTIFY_CHANGE_LAST_WRITE,
                        &di->dwBufLength,
                        &di->Overlapped,
                        NULL);
            }

      } while( di );


}


/**********************************************************************
WatchDirectories()

Purpose:
This function implements the ReadDirectoryChangesW API for
indicated directories. For each directory watched, a thread
is created which waits for changes to the directory. This
function waits for the user to input 'q', then cleans up and
quits.

Parameters:

HANDLE hCompPort - Handle for completion port


Return Value:
None

********************************************************************/
void WINAPI WatchDirectories( HANDLE hCompPort )
{
      DWORD   i;
      DWORD   tid;
      HANDLE  hThread;


      // Start watching each of the directories of interest

      for (i=0;i<numDirs;i++)
      {
            ReadDirectoryChangesW( DirInfo[i].hDir,            // HANDLE TO DIRECTORY
                  DirInfo[i].lpBuffer,                                                      // Formatted buffer into which read results are returned.  This is a
                  MAX_BUFFER,                                                            // Length of previous parameter, in bytes
                  TRUE,                                                                              // Monitor sub trees?
                  FILE_NOTIFY_CHANGE_LAST_WRITE,            // What we are watching for
                  &DirInfo[i].dwBufLength,                                    // Number of bytes returned into second parameter
                  &DirInfo[i].Overlapped,                                          // OVERLAPPED structure that supplies data to be used during an asynchronous operation.  If this is NULL, ReadDirectoryChangesW does not return immediately.
                  NULL);                                                                        // Completion routine
      }

      // Create a thread to sit on the directory changes

      hThread = CreateThread( NULL,
            0,
            (LPTHREAD_START_ROUTINE) HandleDirectoryChange,
            hCompPort,
            0,
            &tid);

      // Just loop and wait for the user to quit

      while (getch() != 'q');

      // The user has quit - clean up

      PostQueuedCompletionStatus( hCompPort, 0, 0, NULL );

      // Wait for the Directory thread to finish before exiting

      WaitForSingleObject( hThread, INFINITE );

      CloseHandle( hThread );
}


/**********************************************************************
main()

Purpose:
Main entry-point for fwatch sample. This function reads an .ini
file (fwatch.ini) to determine which directories and files to
watch. For each directory watched some information is gathered
and stored.

Return Value:  (see errors.h for description)
None

Comments:

********************************************************************/
void main(int argc, char *argv[])
{
      TCHAR   *p,*q;                          // Temporary String Pointer
      HANDLE  hCompPort=NULL;                 // Handle To a Completion Port
      DWORD   i;                              // You always need an I.
      TCHAR   DirList[MAX_DIRS*MAX_PATH];     // Buffer for all of the directories
      TCHAR   IniFile[MAX_PATH];
      TCHAR   FilePath[MAX_PATH];
      HANDLE  hFile;

      GetCurrentDirectory( MAX_PATH, IniFile );

      lstrcat( IniFile, L"\\fwatch.ini" );

      GetPrivateProfileString( L"Directories",
            NULL,
            NULL,
            DirList,
            MAX_DIRS*MAX_PATH,
            IniFile );

      GetPrivateProfileString( L"Files",
            NULL,
            NULL,
            FileList,
            MAX_FILES*MAX_PATH,
            IniFile );

      wprintf( L"Watching these directories:\n" );

      // First, walk through the raw list and count items, creating
      // an array of handles for each directory
      for (p=DirList;*p!='\0';numDirs++,p+=(lstrlen(p) + 1))      // Each string is appended with a NULL, so we skip this with the +1
      {

            if( CreateDirectory( p, NULL ) )
                  wprintf( L"Directory %s created\n", p );
            else
                  wprintf( L"Directory %s exists\n", p );

            // Get a handle to the directory
            DirInfo[numDirs].hDir = CreateFile( p,
                  FILE_LIST_DIRECTORY,
                  FILE_SHARE_READ |
                  FILE_SHARE_WRITE |
                  FILE_SHARE_DELETE,
                  NULL,
                  OPEN_EXISTING,
                  FILE_FLAG_BACKUP_SEMANTICS |
                  FILE_FLAG_OVERLAPPED,
                  NULL);

            if( DirInfo[numDirs].hDir == INVALID_HANDLE_VALUE )
            {
                  wprintf( L"Unable to open directory %s. GLE=%d. Terminating...\n",
                        p, GetLastError() );
                  exit( 0 );
            }

            for (q=FileList;*q!='\0';q+=(lstrlen(q)+1))      // Each string is appended with a NULL, so we skip this with the +1
            {
                  lstrcpy( FilePath, p );
                  lstrcat( FilePath, L"\\" );
                  lstrcat( FilePath, q );

                  if( hFile = CreateFile( FilePath,
                        GENERIC_WRITE,
                        FILE_SHARE_READ |
                        FILE_SHARE_WRITE |
                        FILE_SHARE_DELETE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL) )
                  {
                        wprintf( L"  File %s created\n", FilePath );
                        CloseHandle( hFile );
                  }
                  else
                        wprintf( L"  File %s could not be created\n", FilePath );

            }

            lstrcpy( DirInfo[numDirs].lpszDirName, p );

            // Set up a key(directory info) for each directory
            hCompPort=CreateIoCompletionPort( DirInfo[numDirs].hDir,
                  hCompPort,
                  (DWORD) &DirInfo[numDirs],
                  0);

      }

      wprintf( L"\n\nPress <q> to exit\n" );

      // Start watching
      WatchDirectories( hCompPort );

      for(i=0;i<numDirs;i++)
            CloseHandle( DirInfo[i].hDir );

      CloseHandle( hCompPort );

}
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2012
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
BTW, more than one attribute is changed during such a process, thus the multile notifys. But the main issue is to set all the necessary flags in 'dwNotifyFilter' when calling 'ReadDirectoryChangesW()'.
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
And one other point: I've seen crashes because 'GetQueuedCompletionStatus()' yielded 0 as the completion key and returning 'FALSE', better make that

            // Retrieve the directory info for this directory
            // through the completion key
            BOOL bRC = GetQueuedCompletionStatus( (HANDLE) dwCompletionPort,
                  &numBytes,
                  (LPDWORD) &di,      // This is the DIRECTORY_INFO structure that was passed in the call to CreateIoCompletionPort below.
                  &lpOverlapped,
                  INFINITE);

            if (!bRC) return;

Author

Commented:
Heh, yeah: setting those extra flags did the trick.  Thanks.

>> I've seen crashes because 'GetQueuedCompletionStatus()' yielded 0 as the completion key and returning 'FALSE'...

Not sure what you mean there.  If the completion key is 0, the code does nothing with it...

if ( di )
{
   //...
}

?
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
Sorry, that only happens with no fwatch.ini present - then 'di' is some value, the 'if' applies and some really low address is read.

Author

Commented:
Thanks :0)

Author

Commented:
I have asked a related question at http:Q_22515734.html; if you could help there it would be appreciated :o)

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.