I am trying to monitor different directories for changes using ReadDirectoryChangesW
and I succeed in monitoring a single directory with it. But when it comes to monitoring multiple directories, I am having problems that the first directory is assigned to the handle and it looks for changes only in that directory and then only goes to watch the next directory if the first directory condition is satisfied. But I want to watch multiple directories simultaneously. Can I help me with this problem?
I am attaching the code below for the reference.
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <mutex>
#include "sys/stat.h"
#include <dirent.h>
using namespace std;
mutex m1;
int main()
{
HANDLE hDir[20];
vector <string> directory_list;
string f_path;
string temp1;
ifstream pfile;
pfile.open("C:\\Users\\sathish-pt1608\\Desktop\\path_file.txt");
if (!pfile.is_open())
cout << "Unable to open the Requested File...";
while(pfile.good())
{
getline(pfile,f_path);
struct stat path_stat;
stat(f_path.c_str(),&path_stat);
if (S_ISREG(path_stat.st_mode))
{
int a = f_path.find_last_of('\\');
directory_list.push_back(f_path.substr(0, a - 1));
}
else if(S_ISDIR(path_stat.st_mode))
{
DIR *dir;
struct dirent *ent;
dir = opendir(f_path.c_str());
if (dir != NULL)
{
directory_list.push_back(f_path);
while ( (ent = readdir(dir)) != NULL)
{
temp1 = ent->d_name;
}
closedir(dir);
}
else
{
perror("Please Check the Directory Path...");
EXIT_FAILURE;
}
}
}
for (int i = 0; i < directory_list.size();)
{
LPCTSTR DirName = directory_list[i].c_str();
hDir[i] = CreateFile(DirName, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
FILE_NOTIFY_INFORMATION Buffer[1024];
DWORD BytesReturned;
if (!ReadDirectoryChangesW(hDir[i], &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE, &BytesReturned, NULL, NULL))
{
cout << DirName << endl;
}
else
cout << "THE DIRECTORY HAS BEEN MODIFIED..." << endl;
if (i == directory_list.size() - 1)
i = 0;
else
i++;
}
}