Question

ReadDirectoryChangesW / FWATCH MSDN sample not working!

Asked by: mrwad99

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 );

}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-04-12 at 07:53:24ID22507220
Tags

fwatch

,

readdirectorychangesw

,

msdn

Topics

C++ Programming Language

,

Windows Programming

,

Windows MFC Programming

Participating Experts
1
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. void pointers
    Hi, Im having difficulties working with void pointer arguments and doubly linked lists containing data fiels of type void *. The below code works well with structures and strings, however, floats and ints escape me. the functions are to be generic, in that they are to be abl...
  2. typedef struct
    Hi, I've written a program that receives some data over a socket connection. I receive the data as a character array.... char *pData=(char*)calloc(1,USSP_RESSIZE); while(nError == WSAEWOULDBLOCK) { nBytes = socket.Receive(pData, USSP_RESSIZE, MSG_PEEK); switch(nB...
  3. global typedef
    I try to make a linked list class for my school project and got some problem with typedef thing. MY HEADER FILE LOOKS LIKE (list.h): struct node; struct dataTypeList; typedef dataTypeList itemListType; class list { public: list(); ~list(); void getItem(item...
  4. Dependent typedef problem (not yet declared struct in a st…
    Hi, I have a problem typedefing a struct that uses another struct that uses the first struct! still there? Is there a way to do that (I'd like to avoid void pointers if possible) Thanks typedef struct _one { char* s1; char* s2; Second* data; } First; typedef s...
  5. struct and functions
    What rules are there if you are accessing a structure in a function outside the function that it was declared ? Actually I have the delcaration of the struct outside the main function (done globally) I have the typedef done globally And I initialise the structure inside the...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

20120131-EE-VQP-001

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...