您的位置:首页 > 运维架构

如何获取system函数执行的结果------用popen搞起(很有用)

2017-11-04 11:26 393 查看
        如何获取system函数执行的结果? 搞了一下, 没搞定, 那就用别的方法搞起, 看代码:

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

string getCmdResult(const string &strCmd)
{
char buf[10240] = {0};
FILE *pf = NULL;

if( (pf = popen(strCmd.c_str(), "r")) == NULL )
{
return "";
}

string strResult;
while(fgets(buf, sizeof buf, pf))
{
strResult += buf;
}

pclose(pf);

unsigned int iSize =  strResult.size();
if(iSize > 0 && strResult[iSize - 1] == '\n')  // linux
{
strResult = strResult.substr(0, iSize - 1);
}

return strResult;
}

int main()
{
cout << getCmdResult("date") << endl;
cout << getCmdResult("echo -n abc | md5sum | awk '{print $1}'") << endl;
return 0;
}
      结果:

Sat Nov  4 11:23:56 CST 2017

900150983cd24fb0d6963f7d28e17f72

     不多说。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: