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

#include "cmd_out.hh"

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;
}