C/C++项目调用外部exe程序方法

前言

在开发项目的时候,有的时候需要调用外部exe文件。那么在C/C++里面直接调用exe文件的方法有哪些呢?现在可考虑的方法主要有:

  • 使用system函数
  • 使用execl或者execv函数
  • 使用WinExec函数
  • 使用CreateProcess函数
  • 使用ShellExcecuteEx函数

这里,我们用作测试的exe文件为:sleepXs.exe,此exe会将输入参数(int形)加起来并返回,程序在执行时会休眠X秒,X由用户从外部动态定义。程序源码如下:

#include 
#include 

using namespace std;

int main(int argc, char* argv[]){
    int c=0;
    if(argc>1){
        for(int i=1;iint time;
    cout<<"- - 请输入延时时间(s):"<"- - ";
    cin>>time;

    cout<<"- - sleep "<"s start"<1000);
    cout<<"- - sleep "<"s end"<return c;
}

方法一、使用system函数

system()函数的功能是发出一个DOS命令:int system(char *command),调用方式如下:

//1+2+3
int res = system("sleepXs.exe 1 2 3");

休眠时间需要从键盘输入,如果需要避免交互,可以换成如下:

int res = system("sleepXs.exe 1 2 3 < sleepXs_input.txt");

sleepXs_input.txt是我们提前创建好的一个txt文件,里面写好参数(那些需要从键盘输入的),如果有多个参数用空格或换行区分,将它和sleepXs.exe放在同一目录即可。sleepXs.exe和系统源文件放在一起(部署时和callExe.exe放一起),否则需要加入路径。

持续更新中。。。

你可能感兴趣的:(C++学习整理)