Skip to content

Instantly share code, notes, and snippets.

@benjaminalt
Created September 24, 2016 17:01
Show Gist options
  • Select an option

  • Save benjaminalt/162000faec220784aa68fa01adf09db3 to your computer and use it in GitHub Desktop.

Select an option

Save benjaminalt/162000faec220784aa68fa01adf09db3 to your computer and use it in GitHub Desktop.
Execute command and capture stdout in C++
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL)
result += buffer;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment