Skip to content

Instantly share code, notes, and snippets.

@blippy
Created June 9, 2016 11:44
Show Gist options
  • Select an option

  • Save blippy/ab735f9a2715db741503a29bccf1ddcb to your computer and use it in GitHub Desktop.

Select an option

Save blippy/ab735f9a2715db741503a29bccf1ddcb to your computer and use it in GitHub Desktop.
Execute a shell command, reading its output
#include <iostream>
#include <stdexcept>
#include <string>
std::string run(const char* cmd)
{
FILE *in;
char buff[512];
std::string result;
if(!(in = popen(cmd, "r")))
throw std::runtime_error("popen() failed");
while(fgets(buff, sizeof(buff), in)!=NULL) result += buff;
pclose(in);
return result;
}
int main()
{
std::cout << run("ls -sail");
run("ls -sail"); // won't print anything
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment