Created
December 16, 2021 10:45
-
-
Save kuba--/6c7ba66389f3e4bea2f2b22e6a8ca51f to your computer and use it in GitHub Desktop.
c++ exec system command
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
#include <cstdio> | |
#include <iostream> | |
#include <memory> | |
#include <stdexcept> | |
#include <string> | |
#include <array> | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment