Last active
January 14, 2022 06:22
-
-
Save l2m2/402f42521aee5a7f91760adafb5dfaea to your computer and use it in GitHub Desktop.
执行命令,获取输出
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-the-output-of-the-command-within-c-using-po | |
std::string exec(const char* cmd) | |
{ | |
std::array<char, 128> buffer; | |
std::string result; | |
std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cmd, "r"), _pclose); | |
if (!pipe) { | |
throw std::runtime_error("popen() failed!"); | |
} | |
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { | |
result += buffer.data(); | |
} | |
return result; | |
} | |
// https://stackoverflow.com/questions/52164723/how-to-execute-a-command-and-get-return-code-stdout-and-stderr-of-command-in-c | |
int execute(std::string cmd, std::string& output) { | |
const int bufsize=128; | |
std::array<char, bufsize> buffer; | |
auto pipe = popen(cmd.c_str(), "r"); | |
if (!pipe) throw std::runtime_error("popen() failed!"); | |
size_t count; | |
do { | |
if ((count = fread(buffer.data(), 1, bufsize, pipe)) > 0) { | |
output.insert(output.end(), std::begin(buffer), std::next(std::begin(buffer), count)); | |
} | |
} while(count > 0); | |
return pclose(pipe); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment