简体   繁体   中英

How to read updating text file with Qt?

I have one application(I dont have source code), which prints its output into console. I am writing its output to file like;

./otherApp > out.txt

And with c++ qt programming, I am writing an application which should also read its output simultaneously . However my code is only reading out.txt file which is created. I mean while otherApp is continue to write output, if my project finished reading, it is not reading the rest of output file.

Here is usual method with QTextStream about reading output.

QString fileName = "/.1/Work/appOutput/out1";

QFile inputFile(fileName);
if(inputFile.open(QIODevice::ReadOnly))
{
    QTextStream in(&inputFile);
    while(!in.atEnd())
    {
        QString line = in.readLine();

        qDebug() << line;
    }
    inputFile.close();
}

My question is how I can read out text file until I close otherApp or after it does not write anything inside?

EDIT:

thanks to @Bowdzone I changed my code and it is working. Here is my code.

    QString program = "/.1/Work/otherApp";
    QStringList arguments;
    arguments << "-x" <<  "1002";

    QProcess *myProcess = new QProcess();
    myProcess->start(program, arguments);

    QString strOut = myProcess->readAllStandardOutput();

    qDebug() << QTime::currentTime().toString() << strOut;

    myProcess->waitForFinished();

However qDebug() does not show output of otherApp as soon as there is log in application. Looks like myProcess->waitForFinished() should not be placed because as soon as application start it create another process and I cannot see logs in Qt Project. Could you please help me how I can see logs in same time?

Another way of doing this is instead of reading the standard output from the QProcess as mentioned in the comments would be to use QFileSystemWatcher and read the file whenever QFileSystemWatcher::fileChanged signal is emitted. However then you would need to either remember where you stopped reading or discard the contents that you have already read in so if it is possible a switch to the standard output would be much more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM