Qt and Linux pipes

2019-08-04 20:13发布

问题:

I have written a program which strips the tags from a HTML website which the user specifies. I am know creating a GUI program to go with this to allow the user to input the URL.

I have the following code which opens a pipe to open the executable file I made which processes the input from the QT program.

    QString stringURL = ui->lineEdit->text();
    const char* result;

    ui->labelError->clear();
    if(stringURL.isEmpty() || stringURL.isNull()) {
        ui->labelError->setText("You have not entered a URL.");
        stringURL.clear();
        return;
    }

    std::string cppString = stringURL.toStdString();
    const char* cString = cppString.c_str();

    FILE *fid;
    fid = popen("htmlstrip", "w");    //Note that this application is in the PATH
    fprintf(fid, "%s\n", cString);    //Send URL
    pclose(fid);

However the code above only allows me to write to the pipe. Could anyone tell me how I would allow the Qt program to send the input to the executable and then receive the output from the executable once it has done the processing and put this into a textbox/textarea in the Qt program?

回答1:

You could avoid c pipes by using QProcess.

#include <QDebug>
#include <QProcess>
#include <QString>

int main()
{
    QProcess echo;

    // call your program (e.g. echo) and add your input as argument
    echo.start("echo", QStringList() << "foo bar");

    // wait until your program has finished 
    if (!echo.waitForFinished())
        return 1;

    // read the output
    qDebug() << echo.readAll();

    return 0;
}


标签: qt pipe