在Qt中可以使用QFileSystemWatcher类监视文件和目录的改变。在使用addPath()函数监视指定的文件和目录时,如果需要监视多个目录,则可以使用addPaths()函数加入监视。若要移除不需要监视的目录,则可以使用removePath()和removePaths()函数。
当监视的文件被修改或删除时,产生一个fileChanged()信号。如果所监视的目录被改变或删除,则产生directoryChanged()信号。
头文件
#ifndef WATCHER_H#define WATCHER_H#include <QFileSystemWatcher>#include <QLabel>#include <QWidget>class Watcher : public QWidget {Q_OBJECTpublic:Watcher(QWidget* parent = 0);~Watcher();private:QLabel* pathLabel;QFileSystemWatcher fsWatcher;};#endif // WATCHER_H
实现
#include "watcher.h"#include <QApplication>#include <QDir>#include <QMessageBox>#include <QVBoxLayout>Watcher::Watcher(QWidget* parent): QWidget(parent){QStringList args = qApp->arguments();QString path;// 读取命令行指定的目录作为监视目录。如果没有指定,则监视当前目录。if (args.count() > 1) {path = args[1];} else {path = QDir::currentPath();}pathLabel = new QLabel;pathLabel->setText(tr("监视的目录:") + path);QVBoxLayout* mainLayout = new QVBoxLayout(this);mainLayout->addWidget(pathLabel);fsWatcher.addPath(path);// 响应函数directoryChanged()使用消息对话框提示用户目录发生了改变connect(&fsWatcher, &QFileSystemWatcher::directoryChanged, this, [](QString path) {QMessageBox::information(NULL, tr("目录发生变化"), path);});}Watcher::~Watcher(){}
文件比较,基本上就看文件属性有没有改变:
class FileInfo {uint ownerId;uint groupId;QFile::Permissions permissions;QDateTime lastModified;QStringList entries;public:FileInfo(const QFileInfo& fileInfo): ownerId(fileInfo.ownerId()), groupId(fileInfo.groupId()), permissions(fileInfo.permissions()), lastModified(fileInfo.lastModified()){if (fileInfo.isDir()) {entries = fileInfo.absoluteDir().entryList(QDir::AllEntries);}}FileInfo& operator=(const QFileInfo& fileInfo){*this = FileInfo(fileInfo);return *this;}bool operator!=(const QFileInfo& fileInfo) const{if (fileInfo.isDir() && entries != fileInfo.absoluteDir().entryList(QDir::AllEntries))return true;return (ownerId != fileInfo.ownerId()|| groupId != fileInfo.groupId()|| permissions != fileInfo.permissions()|| lastModified != fileInfo.lastModified());}};
