views:

132

answers:

3

I need a .Net's FileSystemWatcher analog in raw C++/WinAPI. I almost started to code one myself using FindFirstChangeNotification/FindNextChangeNotification, but then it occurred to me that I am probably not the first one who needs this and maybe someone will be willing to share.

Ideally what I need is a class which can be used as follows:

FileWatcher fw;
fw.startWatching("C:\MYDIR", "filename.dat", 
     FileWatcher::SIZE | FileWatcher::LAST_WRITE,
     &myChangeHandler);
...
fw.stopWatching();

Or if it would use somehting like boost::signal it would be even better. But please, no dependencies other than the Standard Library, boost and raw WinAPI. Thanks!

+1  A: 

Does this link help?

Abhay
Very good! But doesn't support watching for a specific file, and requires a window to receive notifications. But still can be used as a blueprint for own implementation.
Alex Jenter
+1  A: 

There is some public-domain code here. My current project uses this (inherited from previous developers). It works pretty well but we do miss notifications for reasons that are unclear (and possibly not caused by this code).

Note that the Win32 API here has some limitations which make it difficult/impossible to avoid missing notifications. Background and alleged work-round for the API are here

Steve Townsend
Thanks, seems to be a very nice piece of code! Very, very close indeed. Unfortunately depends on MFC (CString, CSingleLock, CCriticalSection) thus can't be used as is and needs rewriting.
Alex Jenter
Yes, and in fact our own usage of this code is not MFC-dependent. However, the hard part here is the signal management from the Win32 API and this seems to work well.
Steve Townsend
Still needs too much rewriting to get rid of MFC. I may be wrong, but I feel that carefully wrapping ReadDirectoryChangesW myself would be both faster and easier.
Alex Jenter
+1  A: 

What about the ReadDirectoryChangesW function?

http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx

It stores notifications in a buffer so you don't miss any changes (unless the buffer overflows)

Dynite
It seems to impose periodical polling strategy, but I'd like to get notified of the changes (I need to reload a file when it is changed).
Alex Jenter
Sorry, I was wrong. It allows to wait on an event. Seems to be a viable option.
Alex Jenter