2015-09-23 29 views
1

我寫在Qt的程序和當前使用POPEN運行Linux命令和讀取輸出到一個字符串:如何獲取使用QProcess調用的程序的返回stdout?

QString Test::popenCmd(const QString command) { 
    FILE *filePointer; 
    int status; 
    int maxLength = 1024; 
    char resultStringBuffer[maxLength]; 
    QString resultString = ""; 

    filePointer = popen(command.toStdString().c_str(), "r"); 
    if (filePointer == NULL) { 
     return 0; 
    } 

    while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) { 
     resultString += resultStringBuffer; 
    } 
    status = pclose(filePointer); 
    if (status == 0) { 
     return resultString; 
    } else { 
     return 0; 
    } 
} 

所以我想扔上面的代碼作爲離我更願意如果可能,請使用Qt提供的更高級別的設施。有沒有人有過如何用QProcess做這個事情的例子,或者至少有一個關於如何完成的粗略想法?

這是值得的,它將在Linux上運行。

謝謝

+0

[讀取QProcess輸出到字符串]的可能重複(http://stackoverflow.com/questions/17344807/read-qprocess-output-to-string) –

回答

1

這樣做:

void Process::runCommand(const QString &p_Command) { 
    QProcess *console = new QProcess(); 
    console->connect(console, SIGNAL(readyRead()), this, SLOT(out())); 
    console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int))); 
    console->start(p_Command); 
} 

void Process::out() { 
    QProcess *console = qobject_cast<QProcess*>(QObject::sender()); 
    QByteArray processOutput = console->readAll(); 
} 

void Process::processFinished(int p_Code) { 
    QProcess *console = qobject_cast<QProcess*>(QObject::sender()); 
    QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1(); 
} 

信號QProcess::finished()可以用來獲取進程的退出代碼。

相關問題