簡體   English   中英

_popen() 不返回任何內容

[英]_popen() returns nothing

這是一個Qt程序。 我正在嘗試運行gcc命令並使用_popen (在 Windows 上)獲得結果。 但是,我沒有得到 output。

調試后發現gcc命令運行正常。

void editor::on_action_Compile_triggered()
{
    QString str = "gcc \""+curFile+"\" -o \""+outputFile+"\" 2>&1"; //compile curFile 

    FILE *fp = _popen(str.toStdString().data(),"r");

    if (!fp)
    {
        ui->Log->setText("Error."); //Log is a text browser
    }
    else
    {
        QString tmpStr = "";
        char tmp[1024] = { 0 };

        while (fgets(tmp, 1024, fp) != NULL) //read fp
            tmpStr += (QString)tmp;

        ui->Log->setText(tmpStr); //print to screen
    }
    _pclose(fp);
}

在我看來,你沒有問題。 您上面的代碼對我有用(只要我聲明了正確的curfileoutputFile )。 您沒有輸出,因為 gcc 已成功編譯該文件。 您可能想驗證是否已生成名為outputFile的文件 實際上,當gcc成功時,它不會輸出任何內容。

否則,您的signal/slot連接可能有問題,它不會觸發插槽on_action_Compile_triggered (然后請閱讀下面提供的完整代碼)

要對其進行測試,請嘗試修改您的curFile以指向不存在的文件,您將收到典型的gcc的輸出錯誤。

為了檢查這一點,就我而言,我創建了一個帶有QPushButton按鈕(稱為 pushbutton)和QmainWindow (稱為Log )的QtextEdit 我在下面提供了我的完整代碼。

當我遇到錯誤時(例如找不到編譯的文件。要模擬這個,將你的curFile重命名為錯誤的文件),我會得到這個(使用上面的代碼)。

在此處輸入圖像描述

當我沒有任何錯誤時,我在QTextEdit控件中什么都沒有得到,但是outputFile可執行文件是由目錄中的 gcc 生成的:

這是我的代碼:

// QMainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void compile();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

// QMainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::compile);
}

MainWindow::~MainWindow()
{
    QObject::disconnect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::compile);

    delete ui;
}

void MainWindow::compile()
{
    QString curFile("..\\..\\T0180694\\test.c");
    QString outputFile("..\\..\\T0180694\\test.exe");
    //copied all from your code
    QString str = "gcc \""+curFile+"\" -o \""+outputFile+"\" 2>&1"; //compile curFile

    FILE *fp = _popen(str.toStdString().data(),"r");

    if (!fp)
    {
        ui->Log->setText("Error."); //Log is a text browser
    }
    else
    {
        QString tmpStr = "";
        char tmp[1024] = { 0 };

        while (fgets(tmp, 1024, fp) != NULL) //read fp
            tmpStr += (QString)tmp;

        ui->Log->setText(tmpStr); //print to screen
    }
    _pclose(fp);
    //until here
}

//main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM