#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
/* 执行系统命令,返回命令执行结果字符串*/
string get_output_of_cmd(const string &cmd)
{
int32_t count(2048);
char s[2048];
string ret;
FILE* stream = popen(cmd.c_str(), "r");
if (stream != NULL)
{
// 每次从stream中读取指定大小的内容
while (fgets(s, count, stream))
ret += s;
pclose(stream);
}
return ret;
}
/* 执行系统命令,根据命令退出代码返回布尔值*/
bool get_exit_status_of_cmd(const string &cmd)
{
return (system(cmd.c_str()) == 0);
}
int main (int argc, char** argv)
{
//get_output_of_cmd("ls -al /home/caolei");
//get_exit_status_of_cmd("ls -al /home/caolei");
//get_exit_status_of_cmd("/data/test.sh");
int a = system("ls");
cout << a << endl;
string b = get_output_of_cmd("ls");
cout << b << endl;
printf("hello world.\n");
return 0;
}
使用g++编译,不要使用gcc:
g++ cpp_to_shell.cpp -o cpp_to_shell.out
注意:popen函数是重点。