Created
March 21, 2014 19:16
-
-
Save fpersson/9693879 to your computer and use it in GitHub Desktop.
How to use popen for system calls with return value.
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 <string> | |
#include <iostream> | |
#include <stdio.h> | |
/** | |
* This is not tested in windows. | |
* Windows users should use _popen and _pclose. | |
* http://msdn.microsoft.com/en-us/library/aa298534(v=vs.60).aspx | |
*/ | |
std::string exec(char* cmd) { | |
FILE* pipe = popen(cmd, "r"); | |
if (!pipe){ | |
return "ERROR"; | |
} | |
char buffer[128]; | |
std::string result = ""; | |
while(!feof(pipe)) { | |
if(fgets(buffer, 128, pipe) != NULL) | |
result += buffer; | |
} | |
pclose(pipe); | |
return result; | |
} | |
int main () | |
{ | |
std::string retval = exec("ls -l"); | |
std::cout << "Return: " << retval << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment