#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函数是重点。
本文介绍了一种在C++程序中调用并获取Shell命令输出的方法,通过使用popen和pclose函数实现。文中提供了两个实用函数示例:一个用于获取命令执行结果的字符串输出,另一个用于检查命令的退出状态。
3161

被折叠的 条评论
为什么被折叠?



