[英]How to read updating text file with Qt?
我有一個應用程序(我沒有源代碼),它將其輸出打印到控制台中。 我正在將其輸出寫入文件;
./otherApp > out.txt
並用C ++ Qt編程,我寫一個應用程序,它也應該同時讀取它的輸出。 但是我的代碼僅讀取已創建的out.txt文件。 我的意思是,當otherApp繼續寫入輸出時,如果我的項目完成讀取,則它不會讀取其余的輸出文件。
這是QTextStream關於讀取輸出的常用方法。
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();
}
我的問題是,在關閉otherApp之前或在其中未寫入任何內容之前,如何讀出文本文件?
編輯:
感謝@Bowdzone,我更改了代碼,它可以正常工作。 這是我的代碼。
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();
但是,一旦有應用程序登錄,qDebug()不會立即顯示otherApp的輸出。 看起來不應放置myProcess->waitForFinished()
因為一旦應用程序啟動,它就會創建另一個進程,而我在Qt Project中看不到日志。 您能幫我如何同時查看日志嗎?
這樣做的另一種方法不是使用注釋中提到的從QProcess
讀取標准輸出,而是使用QFileSystemWatcher並在發出QFileSystemWatcher::fileChanged
信號時讀取文件。 但是,您可能需要記住停止讀取的位置,或者丟棄已經讀取的內容,因此,如果有可能,切換到標准輸出將更加方便。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.