리셋 되지 말자

[g++] popen 결과값 사용하기 본문

gcc

[g++] popen 결과값 사용하기

kyeongjun-dev 2020. 1. 23. 17:21

https://www.tutorialspoint.com/How-to-execute-a-command-and-get-the-output-of-command-within-Cplusplus-using-POSIX

 

How to execute a command and get the output of command within C++ using POSIX?

How to execute a command and get the output of command within C++ using POSIX? You can use the popen and pclose functions to pipe to and from processes. The popen() function opens a process by creating a pipe, forking, and invoking the shell. We can use a

www.tutorialspoint.com

그리고 아래는 수정한 코드

 

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

using namespace std;

void exec(string command) {
        char buffer[128];

        FILE* pipe = popen(command.c_str(), "r");

        if (!pipe) {
                cout << "popen failed!";
        }

        while (!feof(pipe)) {
                if (fgets(buffer, 128, pipe) != NULL)
                        cout<<buffer;
        }
        pclose(pipe);
        return;
}

int main() {
        exec("ls");
}

system도 사용이 가능하지만, system은 외부 실행 결과를 정수값으로 뿐이 출력을 못해줘서,

popen을 사용해야 한다.

Comments