1.system
#include <cstdlib>
int main()
{
system("ls");
return 0;
}
运行结果:
lpr@lpr-OptiPlex-7050:/media/lpr/76c21ebf-ed88-4c59-bc41-de64659cd16d/shiyan$ a.out
a.out SAFE test2.cpp test.cpp test.o
2.popen
system()函数只能运行命令,不能获取输出
#include <stdio.h>
#include <string.h>
#include <iostream>
int main(){
char outBuffer[1024]; // 保存运行后输出的结果
char *cmdStr = "ls"; // 准备运行的命令
FILE * pipeLine = popen(cmdStr,"r"); // 建立流管道
if(!pipeLine){
// 检测流管道
perror("Fail to popen\n");
return 1;
}
while(fgets(outBuffer, 1024, pipeLine) != NULL){
// 获取输出
printf("输出: %s",outBuffer); // 打印输出
}
pclose(pipeLine);
return 0;
}
运行结果:
lpr@lpr-OptiPlex-7050:/media/lpr/76c21ebf-ed88-4c59-bc41-de64659cd16d/shiyan$ test3.out
result:a.out
SAFE
test2.cpp
test3.cpp
test3.out
test.cpp
test.o
3.写为函数形式
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
void getRes(char* cmd, char* result)
{
FILE *fp = NULL;
char buf[1024];
fp = popen(cmd, "r");
if( fp != NULL)
{
while(fgets(buf, 1024, fp) != NULL)
{
strcat(result, buf);
}
pclose(fp);
fp = NULL;
}
}
int main(){
char cmd[1024];
char result[4096];
sprintf(cmd, "echo hello world");
getRes(cmd, result);
cout<<"result:"<<result<<endl;
return 0;
}