Skip to content

Instantly share code, notes, and snippets.

@marler8997
Created January 27, 2024 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marler8997/5ce035b6fb8ec217c2caee5b95c4c622 to your computer and use it in GitHub Desktop.
Save marler8997/5ce035b6fb8ec217c2caee5b95c4c622 to your computer and use it in GitHub Desktop.
Win32 Watch directory for changes recursively
#include <windows.h>
#include <stdio.h>
#define logf(fmt,...) do { fprintf(stderr, fmt "\n", ##__VA_ARGS__); fflush(stderr); } while (0)
void MonitorDirectoryRecursively(const char* directoryPath) {
HANDLE hChange = FindFirstChangeNotification(
directoryPath,
TRUE, // Watch the subtree
FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME
);
if (hChange == INVALID_HANDLE_VALUE) {
logf("Error: FindFirstChangeNotification failed (%d)", GetLastError());
return;
}
logf("Monitoring directory: %s", directoryPath);
while (TRUE) {
logf("waiting for change...");
DWORD waitResult = WaitForSingleObject(hChange, INFINITE);
if (waitResult == WAIT_OBJECT_0) {
logf("Change detected in directory: %s", directoryPath);
// Process changes here
// Continue monitoring
if (FindNextChangeNotification(hChange) == FALSE) {
logf("Error: FindNextChangeNotification failed (%d)", GetLastError());
break;
}
} else {
logf("Error: WaitForSingleObject failed (%d)", GetLastError());
break;
}
}
FindCloseChangeNotification(hChange);
}
int main(int argc, char* argv[]) {
logf("here!");
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
MonitorDirectoryRecursively(argv[1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment