Win32 C++ ReadDirectoryChangesW“创建”和“修改”文件差异检测?

发布于 2024-09-28 05:08:26 字数 632 浏览 1 评论 0原文

问题如下:我使用 Win32 API 监视目录ReadDirectoryChangesW 函数。我需要区分新创建的文件和修改的文件。但还是有问题......一如既往:(

案例:

  1. 我监视目录的新建/修改(FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE)。问题:文件创建后,新文件事件+修改文件事件被触发。但我只需要一个,如何避免这种情况?当文件被修改时,我得到了我想要的:)。
  2. 我仅监视目录中的新文件 (FILE_NOTIFY_CHANGE_FILE_NAME) - 没有问题。
  3. 我仅监视目录的修改文件(FILE_NOTIFY_CHANGE_SIZE)。 问题:当创建新文件时,修改操作会与文件创建事件一起触发。我怎样才能避免这种情况?

当然,我实施了一些解决方法。但是,我想知道是否有任何优雅的方法来处理我所描述的问题。

Here is the problem: I monitor a directory using Win32 API ReadDirectoryChangesW function. And I need to distinguish between newly created files and modified files. But there are problems... as always :(

Cases:

  1. I monitor directory for new/modify (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE). Problem: After file creation, new file event + modify file event is triggered. But i need only one. How can I avoid that? When file is modified I get what I want :).
  2. I monitor directory only for new file (FILE_NOTIFY_CHANGE_FILE_NAME) - NO PROBLEM.
  3. I monitor directory only for modify file (FILE_NOTIFY_CHANGE_SIZE). Problem: When a new file is, modify action is fired along with file creation event. How can I avoid that?

Of course, I implemented some workarounds. But, I want to know if there any elegant way of handling the problems I described.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

路还长,别太狂 2024-10-05 05:08:26

对于已修改的文件,您应该捕获 FILE_NOTIFY_CHANGE_LAST_WRITE,而不是 FILE_NOTIFY_CHANGE_SIZE。可以修改文件而不改变大小。

您还应该保留更改的队列及其发生的时间,并且仅在过去 1-2 秒内没有更改后才处理队列。某些应用程序在创建或修改文件时可能会执行非常奇怪的操作,如果您打算在野外使用此代码,您很可能需要针对流行应用程序进行特殊处理。

ReadDirectoryChanges 不是最友好的 winapi 函数之一。您可能无法避免接收有关文件创建的两个事件;我不完全确定您是否会在创建时对 FILE_NOTIFY_CHANGE_LAST_WRITE 进行额外修改,但我认为您可能会的。如果额外的事件与创建事件具有相同的时间戳,那么使用队列方法将允许您轻松地丢弃额外的事件。

You should be catching FILE_NOTIFY_CHANGE_LAST_WRITE, not FILE_NOTIFY_CHANGE_SIZE, for a modified file. Files may be modified without the size changing.

You should also keep a queue of changes and the time they happened and only process the queue after there have been no changes in the past 1-2 seconds. Some applications can do very strange things when creating or modifying files, and you'll most likely want to special case for popular applications if you plan on using this code in the wild.

ReadDirectoryChanges isn't one of the friendliest winapi functions. You probably can't get around receiving two events on file creation; I'm not completely sure whether you'll get an extra modify for FILE_NOTIFY_CHANGE_LAST_WRITE on creation, but I think you probably will. Using the queue approach will allow you to easily throw out the extra event if it has the same time stamp as the creation event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文