Created
June 9, 2016 11:44
-
-
Save blippy/ab735f9a2715db741503a29bccf1ddcb to your computer and use it in GitHub Desktop.
Execute a shell command, reading its output
This file contains hidden or 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 <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