如何获取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
不多说。