Last active
March 15, 2018 01:43
-
-
Save IvanaGyro/d2e2a7ea015a5a41a9b5668c0a762095 to your computer and use it in GitHub Desktop.
Pipe Linux command results
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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