qt 调用自定义控制台程序,给控制台传递参数(一个文件的绝对路径,和一个文件夹路径),控制台程序读取参数,取到文件里面的数据,进行计算,再写到txt文件中,将这个txt文件保存到参数里面的文件夹路径中。

 

一、c++控制台部分

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main( int arge,char **argv)
{
    ofstream ofs;    
    ifstream ifs;
    char ** temp = argv;  /* 保留argv */    
    vector<string> str;
    if (*temp != nullptr) {
        str.push_back(*(temp + 1)); //获取第一个参数 文件绝对路径 
        str.push_back(*(temp + 2)); //获取第二个参数 文件存放路径
    }
    else
    {
        return 0;
    }
    string txtfile = str.at(0); //文件
    string filePath = str.at(1); //路径
    
    ifs.open(txtfile, ios::in | ios::binary);
    if (ifs.is_open() == true);//判断文件是否打开成功
    else return 0;
    
    ofs.open(filePath+"write.txt", 0x02);   //将数据写入到指定文件
    char data[] = " ";
    vector<double> parameter;
     while (ifs >>data) {
        parameter.push_back(atof(data));    
     }
    for (int i = 0; i < parameter.size(); i++)
    {
        ofs << parameter.at(i) << endl;
    }
    
    //5.关闭文件
    ofs.close();
    ifs.close();
    system("pause");
    return 0;
}

 

 

二、qt程序部分

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QString>
#include <QtDebug>
#define  CALC_MODEL_1 QApplication::applicationDirPath() + "/calcApp" + "/process4.exe"
#define  CALC_MODEL_2 QApplication::applicationDirPath() + "/calcApp" + "/process4.txt"
#define  CALC_MODEL_3 QApplication::applicationDirPath() + "/calcApp/"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QProcess *myProcess = new QProcess(this);

        QString _cmd = CALC_MODEL_1;
        QString _fileName =CALC_MODEL_2;
        QString _path =CALC_MODEL_3;
        _cmd.replace('/', '\\');
        _path.replace('/','\\');
        QStringList strlt;
        //strlt<<_cmd;
        strlt<<_fileName;
        strlt<<_path;
        myProcess->start(_cmd,strlt);
        //myProcess->waitForFinished(1000 * 10);
        qDebug() <<  strlt;

}

 

posted @ 2022-05-12 18:26  雾枫  阅读(624)  评论(0)    收藏  举报