Skip to content

Instantly share code, notes, and snippets.

@kuba--
Created December 16, 2021 10:45
Show Gist options
  • Save kuba--/6c7ba66389f3e4bea2f2b22e6a8ca51f to your computer and use it in GitHub Desktop.
Save kuba--/6c7ba66389f3e4bea2f2b22e6a8ca51f to your computer and use it in GitHub Desktop.
c++ exec system command
#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