aboutsummaryrefslogtreecommitdiff
path: root/src/cmd_out.cc
blob: a855add13a3ca738121ad0fd4c3dc0fe4dd260da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

std::string cmd_out(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(), static_cast<int>(buffer.size()), pipe.get()) != nullptr) {
    result += buffer.data();
  }
  return result;
}