Skip to content

Instantly share code, notes, and snippets.

@IvanaGyro
Last active March 15, 2018 01:43
Show Gist options
  • Save IvanaGyro/d2e2a7ea015a5a41a9b5668c0a762095 to your computer and use it in GitHub Desktop.
Save IvanaGyro/d2e2a7ea015a5a41a9b5668c0a762095 to your computer and use it in GitHub Desktop.
Pipe Linux command results
#include <stdexcept>
#include <string>
#include <cstdio>
std::string exec(const char *cmd)
{
int bufferSz = 512;
char buffer[bufferSz];
std::string result = "";
FILE *pipe = popen(cmd, "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try
{
while (!feof(pipe))
{
if (fgets(buffer, bufferSz, pipe) != NULL)
result += buffer;
}
}
catch (...)
{
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment