How to use QProcess to show tail command output of a log file on QTextEdit Window?
-
You can mimic part of tail -f by holding a QTimer that for example fires every second. In a slot connected to the timout signal of that timer, you just check the still open file for new data and read that.
@
class logFile: QObject (or QWidget) {
public:
logFile(QObject *parent);protected slots:
readData();private:
QTimer timer;
QFile logFile;
QTextStream logStream;
};logFile::logFile(QObject *parent)
{
logFile.setFileName("/var/log/system.log");
logFile.open(QIODevice::ReadOnly|QIODevice::Text);
logStream.setDevice(logFile);
// read the current file contents here if neededconnect(&timer, SIGNAL(timeout()), this, SLOT(readData())); timer.start(1000);}
void logFile::readData()
{
while(!logStream.atEnd()) {
QString line = logStream.readLine();
// supposing logTextEdit is a QPlainTextEdit
ui->logTextEdit->appendPlainText(line);
ui->logTextEdit->appendPlainText("\n");
}
}
@[Brain to terminal, not tested.]
-
as suggested i have changed the code and am using QFileSystemWatcher.But i am still not getting the result,i think there is some mistake somewhere in my code,i can't figure out.
Ui form appears for a fraction of second and then the application terminates unexpectedly.
here's the code:-
LOGFILE.h
@
public slots:
void readContents(QString);
@LOGFILE.cpp
@
logFile::logFile(QWidget *parent):QMainWindow(parent),ui(new Ui::logFile)
{
QFile *logFile = new QFile("/path/to/log/file");
new QTextStream(logFile);
QFileSystemWatcher fileWatcher = new QFileSystemWatcher(this) ;
fileWatcher->addPath("/path/to/log/file");
QObject::connect(fileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(readContents(QString))) ;
}void logFile::readContents(QString path)
{
QFile *logFile;
QString textAppended ;
int newSize = logFile->size();
int oldSize;
if(newSize > oldSize)
{
if(!logFile->open(QIODevice::ReadOnly))
{
textAppended = "Error in opening the File";
//showOutput();
ui->logTextEdit->setPlainText(textAppended);
return;
}
else
{
logFile->seek((logFile->size() - 1) - (newSize - oldSize));
QTextStream txtStream(logFile);
while(!txtStream.atEnd())
{
textAppended = txtStream.readLine();
}
// showOutput();
ui->logTextEdit->setPlainText(textAppended);
}
oldSize = newSize;
logFile->close();
}
}
@ -
In readContents(), logFile is not initialized. Your program crashes.
In the constructor, you create a QTextStream, but don't keep it anywhere.
May I ask if you have any experience with C++ at all? It dosen't look so, and I would suggest to take the time for some online tutorial on C++ before you continue with Qt.