前言
在開發項目的時候,有的時候需要調用外部exe文件。那麼在C/C++裏面直接調用exe文件的方法有哪些呢?現在可考慮的方法主要有:
- 使用system函數
- 使用execl或者execv函數
- 使用WinExec函數
- 使用CreateProcess函數
- 使用ShellExcecuteEx函數
這裏,我們用作測試的exe文件爲:sleepXs.exe,此exe會將輸入參數(int形)加起來並返回,程序在執行時會休眠X秒,X由用戶從外部動態定義。程序源碼如下:
#include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
int c=0;
if(argc>1){
for(int i=1;i<argc;i++){
c+=atoi(argv[i]);
}
}
int time;
cout<<"- - 請輸入延時時間(s):"<<endl<<"- - ";
cin>>time;
cout<<"- - sleep "<<time<<"s start"<<endl;
Sleep(time*1000);
cout<<"- - sleep "<<time<<"s end"<<endl;
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放一起),否則需要加入路徑。