Qt定时查看文件(内容)状态

       使用背景:想要在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

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雲烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值