开发者

How to monitor a directory for files in C++?

I need to monitor a directory which contains many files and a proc开发者_运维问答ess reads and deletes the .txt files from the directory; once all the .txt files are consumed, the consuming process needs to be killed. How do I check if all the .txt files are consumed using C++? I am developing my application on Visual Studio on windows platform.


To get callbacks of when the contents of the directory changed, use the ReadDirectoryChangesW and FindFirstChangeNotification Win32 API.

You can see examples from this question.


Use FindFirstChangeNotification to register a notification callback.


Since it was not required to perform action on each txt file deletion. I came up with following code:

{
  intptr_t hFile;
  struct _finddata_t c_file;
  string searchSpec;
  for (size_t i = 0; i < dataPathVec.size(); ++i)
  {
    searchSpec = dataPathVec.at(i) + DIRECTORY_SEPERATOR + "*" + TXT_FILE_EXT;
    hFile = 0;
    while((hFile != -1L) || (ret != 0))
    {
        hFile = _findfirst(searchSpec.c_str(), &c_file);
        Sleep(500);
        if (hFile != -1L)
        {
            ret = _findclose(hFile);
        }
    }
  }
}

It can monitor many folders and wait till all the txt files are deleted from all the monitored folders.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜