Ubuntu使用C调用Shell

#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函数是重点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值