본문 바로가기
프로그래밍

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

by Ohdumak 2013. 5. 8.

C Implementation

01#include <stdio.h>
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 <iostream>
02#include <stdio.h>
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}

728x90

댓글