Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Reading file as written by external process



  • I have a log file that is being written asynchronously from a docker command using a tee. I want to either copy and/or parse the file up to the current point it is written. Is this possible with QFile or at all? Any advice is appreciated.


  • Lifetime Qt Champion

    What wrong with simply open the file and read it?


  • Lifetime Qt Champion

    Hi and welcome to the forums

    Yes it will work.

    You have to use a timer or similar to read it from time to time
    Disclaimer. fast code. needs more love to be solid.

    class Reader : QObject
    {
        QFile file;
        QTextStream in;
        QTimer timer;
    public:
       explicit Reader(QObject *parent) : QObject(parent)
        {
            connect(&timer, &QTimer::timeout, this, [this]() {
                while (!in.atEnd()) {
                    QString line = in.readLine();
                    qDebug() << line;
                }
            });
        }
        void Process(QString filename)
        {
            file.setFileName( filename);
            in.setDevice(&file);
            if ( ! file.open(QFile::ReadOnly)) {
                qDebug() << "open error" << file.errorString();
                return;
            }
            timer.start(1000);
            qDebug() << "started";
        }
    };
    
    

    using

     Reader *LogReader = new Reader(this);
    LogReader->Process("e:/test.txt");
    

    Note file must exist when you try.

    alt text

    alt text



  • Got it working, thank you. Errors were unrelated to the program writing the file.


Log in to reply