简体   繁体   English

如何监视文件的更改?

[英]how to monitor a file for changes?

How do I monitor rtf file to check if it is updated for a while (lets say 15 min). 我如何监视rtf文件以检查它是否被更新了一段时间(比如说15分钟)。 If not updating then let the main thread know that file is not updated. 如果不更新,则让主线程知道该文件未更新。 I am thinking of using WaitforSingleObject function to wait for any changes in last 15 minute. 我正在考虑使用WaitforSingleObject函数来等待最近15分钟内的任何更改。 how can I implement this funcationality? 如何实现这种功能?

我相信正在寻找的是文件更改通知,例如FindFirstChangeNotificationFindNextChangeNotificationReadDirectoryChangesW您可以监视文件或目录的更改,重命名,写入等。

Presumably your platform is Windows since you mention WaitForSingleObject. 由于您提到WaitForSingleObject,因此您的平台大概是Windows。 In which case the function you are looking for is ReadDirectoryChangesW . 在这种情况下,您要查找的功能是ReadDirectoryChangesW This will allow you to be notified as soon as changes are made, without you performing any polling. 这将使您在进行更改后立即得到通知,而无需执行任何轮询。

Jim Beveridge has an excellent pair of articles that go into some depth: 吉姆·贝弗里奇(Jim Beveridge)撰写了一篇很棒的文章,其中涉及到一些深层次的内容:

You can stat() the file, check its modification date and act appropriately. 您可以stat()文件,检查其修改日期并采取适当措施。

You can also periodically compute a checksum of the file and compare it to the previous one. 您还可以定期计算文件的校验和,并将其与前一个校验和进行比较。

For RTF files you can also take the size of the file and compare it to the previous size; 对于RTF文件,您还可以获取文件的大小并将其与以前的大小进行比较; if it's been modified it's very likely the size will be different. 如果对其进行了修改,则大小很可能会有所不同。

All those methods will probably introduce more overhead than the system calls mentioned by others. 所有这些方法可能会比其他人提到的系统调用引入更多的开销。

In my opinion, you can achieve this in two ways. 我认为,您可以通过两种方式实现这一目标。 You can write a file filter driver that can monitor write operation on the file. 您可以编写文件过滤器驱动程序,以监视文件的写操作。 However this is little bit stretching. 但是,这有点牵强。

Another way is simple one. 另一种方法很简单。 In your main thread, create a hash of your RTF file and cache it. 在主线程中,创建RTF文件的哈希并对其进行缓存。 Create an event in non-signaled state, create a callback function, create a worker thread. 在非信号状态下创建事件,创建回调函数,创建工作线程。 Wait in the worker thread on event for 15 min. 等待事件中的工作线程15分钟。 After timout, again generate hash of your file and compare it with cached hash. timout之后,再次生成文件的哈希并将其与缓存的哈希进行比较。 If mismatch, notify your main thread through callback function. 如果不匹配,请通过回调函数通知您的主线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM