c++winapireaddirectorychangesw

Need an efficient way to handle ReadDirectoryChangesW in C++


I want to get notified about a change in directory (new file addition/deletion/updation). I used an API - "ReadDirectoryChangesW" which correctly notifies about any change in directory. But, the API accepts a buffer in which it returns the details of file(s) added/deleted/modified in the directory. This pose a limitation as the change in directory is not certain and can be huge sometimes. For ex: 1000 files get added in the directory. In this case I alwasys need to be ready with a large enough buffer to hold notification about all 1000 files.

I dont want to always create this large buffer. Is there any other alternate way which is more efficient?


Solution

  • One approach that you could use is to use the ReadDirectoryChangesW() as a way to be notified that there has been some change in the directory and to then use this notification as an event to review the directory for changes.

    The idea is to discover what has changed yourself rather than depending on ReadDirectoryChangesW() to tell you what has changed.

    The documentation for the function indicates that a system buffer is allocated to track changes and it is possible, with a large number of changes that the buffer allocated will overflow. This results in an error returned and requires you to discover what has changed for yourself anyway.

    This article on using ReadDirectoryChangesW() may help you.

    In my case, I am using the function to monitor a print spooler folder into which a number of text files might be dropped. The number of files is small so I have just allocated a large buffer. What I then do is to use a queue to provide to the actual print functionality, which runs on another thread, the list of files to print.