使用背景:想要在Qt中使用rpc,客户端会有新的不定时文件添加,设备需要随时的接收新文件中的数据,进行实时处理。
最初根据这个需求想到的方案是,通过使用QDir的方法,结合QTimer定时器,不停轮询目标文件,实现对改变文件的监控。
感觉实现起来也比较简单,但是做好比较难且花费时间。需要关注的是QDir类和相关方法,以下是嵌入main中的测试代码:
QDir myDir("/cctest");
qDebug()<<myDir.exists();
myDir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
myDir.setSorting(QDir::Size | QDir::Reversed );
const QFileInfoList myList = myDir.entryInfoList();
QFileInfoList::const_iterator myIterator = myList.begin();
qDebug()<<"目录和文件的数量:"<<myDir.count();
while(myIterator != myList.end()){
qDebug()<<(*myIterator).fileName()<<endl;
qDebug()<<(*myIterator).size()<<endl;
myIterator++;
}
后接触到QFileSystemWatcher的类,这个类里Qt官方实际上已经做好了封装,并且能够发出信号,而自己需要做的只是捕获这个信号后去做什么处理,相对便捷了许多,附上测试代码:
filecontentwatcher.h
#ifndef FILECONTENTWATCHER_H
#define FILECONTENTWATCHER_H
#include<QObject>
#include<QMap>
#include<QFileSystemWatcher>
class fileContentMoniter : public QObject
{
Q_OBJECT
public:
fileContentMoniter(QObject *parent = nullptr);
~fileContentMoniter();
void loadFile(const QString &path);
public slots:
void onFileChanged(const QString &path);
private:
QFileSystemWatcher *m_fileWatcher;
};
#endif // FILECONTENTWATCHER_H
filecontentwatcher.cpp
#include"filecontentwatcher.h"
#include<QFileSystemWatcher>
#include<QFile>
#include<QDebug>
fileContentMoniter::fileContentMoniter(QObject *parent):QObject (parent)
{
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &fileContentMoniter::onFileChanged);
loadFile("/cctest/2.txt");
}
fileContentMoniter::~fileContentMoniter()
{
}
void fileContentMoniter::loadFile(const QString &path)
{
if(path.isEmpty() || !QFile::exists(path)){
qDebug("Error!");
}
m_fileWatcher->addPath(path);
}
void fileContentMoniter::onFileChanged(const QString &path)
{
QFile file(path);
if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << file.readAll();
}
}
main.cpp
#include <QCoreApplication>
#include<QDebug>
#include<QDir>
#include"filesystemwatcher.h"
#include"filecontentwatcher.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
fileContentMoniter test;
return a.exec();
}
这个方法只是测试,实际使用时应该向外提供文件路径的接口,并且对文件和文件内容实行全监控。写的比较好的是Qt大神一去丶二三里,那份代码写的比较全面,并且直接可用。链接:https://blog.csdn.net/liang19890820/article/details/51849252