发布日期:2018-03-26
如何使用POSIX在C++中执行命令并获取命令的输出(就是用C++执行系统命令)?+ 查看更多
如何使用POSIX在C++中执行命令并获取命令的输出(就是用C++执行系统命令)?
+ 查看更多
发布日期:2018-02-26 15:56
分类:CPlusPlus
浏览次数:176
我正在找一种方法当它在C++程序中运行时来获取命令的输出(就是用C++执行系统命令)。 我已经尝试过使用system()函数,但它只是执行一个命令。 这里是我找的例子:
std :: string result = system(“./some_command”);
我需要运行一个任意命令,并得到它的输出。 我看过Boost.org,但我没有找到我想要的东西。
回答:
#include在Windows平台下用_popen和_pclose替换popen和pclose。#include #include #include #include #include std::string exec(const char* cmd) { std::array buffer; std::string result; std::shared_ptr pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != NULL) result += buffer.data(); } return result; } Pre-C++11 version: #include #include #include #include std::string exec(const char* cmd) { char buffer[128]; std::string result = ""; FILE* pipe = popen(cmd, "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != NULL) result += buffer; } } catch (...) { pclose(pipe); throw; } pclose(pipe); return result; }