首页 > 解决方案 > 使用 QProcess 执行 CMD 命令并将其保存在 QString 中

问题描述

我想执行 cmd 命令"wmic share get name"QProcess然后将命令的结果保存在QString变量中。此外,我想展示它QMessageBox或......我该怎么做?

标签: c++qt

解决方案


你可以用QProcess这个。假设我要执行g++. 例子:

    QProcess p;
    p.setProgram("g++");
    p.setArguments({"-O3", "filename.cpp"});
    p.start();

    // wait for the process to finish executing
    // returns true on success
    if (!p.waitForFinished()) {
       qDebug() << "Failed to execute!!";
       const QString error = p.readAllStandardError();
       if (!error.isEmpty()) {
        qDebug () << "Exit status: " << p.exitStatus() << ", Error: " << error;   
       }
        return;
    }

    // read output
    const QString output = p.readAllStandardOutput();
    qDebug () << output;

    // read error
    const QString error = p.readAllStandardError();
    if (!error.isEmpty()) {
        qDebug () << error;   
    }

    //do whatever you want with output

推荐阅读