如何用c++用程序运行另一个c++程序或可执行文件,即是用c++运行另一个程序(的可执行文件)?
比如你可以使用popen()调用其他可执行文件或者脚本。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
FILE *fp = NULL;
char cmd[1024];
char buf[1024];
char result[4096];
sprintf(cmd, "./test");
if( (fp = popen(cmd, "r")) != NULL)
{
while(fgets(buf, 1024, fp) != NULL)
{
strcat(result, buf);
}
pclose(fp);
fp = NULL;
}
cout<<"result:"<<result<<endl;
return 0;
}
百度 c++调用外部exe程序
程序中调用cmd
或者调用winApi创建进程
#include <stdio.h>
#include <Windows.h>
int main(int argc, char * argv[])
{
//TCHAR commandLine[] = TEXT("C:\\Users\\Administrator\\source\\repos\\c++practice\\c\\test.exe");
TCHAR commandLine[] = TEXT("notepad");
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
bool bRet = CreateProcess(
NULL,
commandLine,
NULL,
NULL,
FALSE,
CREATE_NO_WINDOW,
NULL,
NULL,
&si,
&pi);
int error = GetLastError();
if (bRet)
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
printf("进程ID:%d\n", pi.dwProcessId);
printf("线程ID:%d\n", pi.dwThreadId);
}
system("pause");
return 0;
}