Created
January 27, 2024 16:42
-
-
Save marler8997/5ce035b6fb8ec217c2caee5b95c4c622 to your computer and use it in GitHub Desktop.
Win32 Watch directory for changes recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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