I am trying to find whether a file is modified or not using FirstChangeNotification
in Windows using C++. Can I use FileSystemWatcher
class to do the same? Can anyone provide me with a solution for both ways if possible? I have searched and found snippets that I'm not able to understand since i am a beginner on these topics.
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
int main(int argc, char argv[])
{
DWORD dwWaitStatus;
HANDLE dwChangeHandles[2];
LPCWSTR DirName = L"F:\\myproject";
LPCWSTR DirName1 = L"F:\\";
dwChangeHandles[0] = FindFirstChangeNotification(
DirName,FALSE,FILE_NOTIFY_CHANGE_FILE_NAME);
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
ExitProcess(GetLastError());
else
printf("FindFirstChangeNotification() for file change is
OK.\n");
dwChangeHandles[1] = FindFirstChangeNotification(
DirName1,TRUE,FILE_NOTIFY_CHANGE_DIR_NAME);
if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
{
printf("Something wrong!\n");
ExitProcess(GetLastError());
}
else
printf("FindFirstChangeNotification() for directory change is
OK.\n");
if (dwChangeHandles[0] != INVALID_HANDLE_VALUE &&
dwChangeHandles[1] != INVALID_HANDLE_VALUE)
{
printf("\nI'm monitoring any file deletion/creation in %S
and\n", DirName);
printf("I'm monitoring any directory deletion/creation in
%S.\n", DirName1);
}
while (TRUE)
{
dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE,
INFINITE);
switch (dwWaitStatus)
{
case 0:
if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
{
printf("FindNextChangeNotification() not OK\n");
ExitProcess(GetLastError());
}
else
printf("File created/deleted in %S.\n", DirName);
break;
case 1:
if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)
ExitProcess(GetLastError());
else
printf("Directory was deleted/created in %S.\n",
DirName1);
break;
default:
printf("FindNextChangeNotification(): Invalid return
value.\n");
ExitProcess(GetLastError());
}
}
if(FindCloseChangeNotification(dwChangeHandles[0]) != 0)
printf("FindCloseChangeNotification() is OK\n");
if(FindCloseChangeNotification(dwChangeHandles[1]) != 0)
printf("FindCloseChangeNotification() is OK\n");
return 0;
}
The above code is in C and i have changed it to C++ and executed it.. It works well for file creation and deletion.. but when i use FILE_NOTIFY_CHANGE_LAST_WRITE
instead of FILE_NOTIFY_FILE_NAME
it prints
the statement twice.