Window/Linux重定向结果C++、C读取方法
#ifdef _MSC_VER
#include <winsock2.h>
#define MAX_PATH_LEN MAX_PATH
#define popen _popen
#define pclose _pclose
#else
#include <unistd.h>
#include <limits.h>
#define MAX_PATH_LEN PATH_MAX
#endif
static std::string RunCmd(const std::string& cmd)
{
std::string ret = ("");
FILE* f = popen((cmd + " 2>&1").c_str(), "r");
if (f != nullptr)
{
size_t s = 0;
char d[MAX_PATH_LEN] = { 0 };
while (!feof(f))
{
s = fread(d, sizeof(char), sizeof(d) / sizeof(char), f);
if (s > 0)
{
ret.append(d, s);
}
}
pclose(f);
}
else
{
printf("popen %s error:(%d),%s.\n", cmd.c_str(), errno, strerror(errno));
}
return ret;
}