简体   繁体   中英

Qt QFile/QTextStream, unable to parse /proc/stat

I'm having a problem parsing /proc/stat with Qt.

The problem I'm having is QFile states /proc/stat is both open and readable.

When attempting to read the lines individually, QTextStream apparently dictates the stream has completed, but I know this isn't the case by running a cat /proc/stat .

None of the code in the while loop is executed. Any advice or suggestions?

  int UsageStatistics::handle_timeout(const ACE_Time_Value& currentTime, const void* param) {

        INFO("Handling timeout\n");

        QFile file(QString("/proc/stat"));
        if (!file.open(QIODevice::ReadOnly)) {
            ERROR("Unable to open file %s, aborting\n", file.fileName().toStdString().c_str());
            return false;
        }                 

        if (!file.isReadable()) {
            ERROR("Unable to read file %s, aborting\n", file.fileName().toStdString().c_str());
            return false;
        }



        QTextStream in(&file);            
        while (!in.atEnd()) {
            QString line = in.readLine();        

            INFO("%s\n", line.toStdString().c_str());

             /// processing
        }

        file.close();

        return true;          
    }

/proc/stat is a tiny file with no risk of ever being huge. Just do a readAll() into a QByteArray (no atEnd() check, you've already done isReadable()), then point a QTextStream at the byte array if you want to parse it the same way.

QFile file(QString("/proc/stat"));
if (!file.open(QIODevice::ReadOnly)) {
    qDebug("Unable to open file %s, aborting\n", 
        qPrintable(file.fileName()));
    ui->plainTextEdit->appendPlainText("Error can't open");
    return;
}

if (!file.isReadable()) {
    qDebug("Unable to read file %s, aborting\n", 
        qPrintable(file.fileName()));
    ui->plainTextEdit->appendPlainText("Error can't read");
    return;
}

QByteArray contents = file.readAll();

QTextStream in(&contents);
while (!in.atEnd()) {
    QString line = in.readLine();

    qDebug("Read: %s\n", qPrintable(line));

    ui->plainTextEdit->appendPlainText(line);
}

ui->plainTextEdit->appendPlainText("Done reading.");

file.close();

I just validated my system did the same as yours, then tried this readAll()-based method and it worked.

You're using cpuRegex.exactMatch , which is looking to match the entire line exactly. And the line you're looking for has other info on it as well. Try using cpuRegex.indexIn(line) == 0 instead.

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