Thứ Tư, 15 tháng 4, 2015


popen() – execute shell command from C/C++

Copied from http://www.sw-at.com/blog/2011/03/23/popen-execute-shell-command-from-cc/

March 23rd, 2011 by Atul Sharma
The popen() function executes a command and pipes the executes command to the calling program, returning a pointer to the stream which can be used by calling program to read/write to the pipe.
Below are the C/C++ snippets to run a simple command, read the stream from pipe and then write to console.
C Implementation
01#include
02
03int main(void) {
04    FILE *in;
05    extern FILE *popen();
06    char buff[512];
07
08    if(!(in = popen("ls -sail""r"))){
09        exit(1);
10    }
11
12    while(fgets(buff, sizeof(buff), in)!=NULL){
13        printf("%s", buff);
14    }
15    pclose(in);
16
17}
C++ Implementation
01#include
02#include
03
04using namespace std;
05
06int main() {
07    FILE *in;
08    char buff[512];
09
10    if(!(in = popen("ls -sail""r"))){
11        return 1;
12    }
13
14    while(fgets(buff, sizeof(buff), in)!=NULL){
15        cout << buff;
16    }
17    pclose(in);
18
19    return 0;
20}