问题描述
有很多程序,例如 Visual Studio,可以检测外部程序何时修改文件,然后如果用户愿意选择重新加载文件.在 C++ 中是否有一种相对简单的方法来做这种事情(不一定是平台无关的)?
There are a lot of programs, Visual Studio for instance, that can detect when an outside program modifies a file and then reload the file if the user wants chooses. Is there a relatively easy way to do this sort of thing in C++ (doesn't necessarily have to be platform independent)?
推荐答案
根据平台,有几种方法可以做到这一点.我会从以下选项中进行选择:
There are several ways to do this depending on the platform. I would choose from the following choices:
奇趣科技的 Qt 有一个名为 QFileSystemWatcher 的对象,它允许您监视文件和目录.我敢肯定还有其他跨平台框架也可以为您提供这种功能,但根据我的经验,这个框架效果很好.
Trolltech's Qt has an object called QFileSystemWatcher which allows you to monitor files and directories. I'm sure there are other cross platform frameworks that give you this sort of capability too, but this one works fairly well in my experience.
有一个名为 FindFirstChangeNotification 可以胜任.有一篇很好的文章,其中有一个名为 How to get an notification if change if change发生在指定的目录中,这将使您开始.
There is a Win32 api called FindFirstChangeNotification which does the job. There is a nice article which a small wrapper class for the api called How to get a notification if change occurs in a specified directory which will get you started.
如果您可以在 .NET Framework 中使用 C++/CLI,那么System.IO.FileSystemWatcher 是您选择的类别.微软有一篇很好的文章如何使用此类监控文件系统更改.
If you are ok using C++/CLI with the .NET Framework then System.IO.FileSystemWatcher is your class of choice. Microsoft has a nice article on how to monitor file system changes using this class.
FSEvents API 是 OS X 10.5 的新 API,功能非常齐全.
The FSEvents API is new for OS X 10.5 and very full-featured.
使用 inotify,正如亚历克斯在回答中提到的那样.
Use inotify as Alex mentioned in his answer.
这篇关于如何让我的程序监视 C++ 中的文件修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!