C언어에서 외부 프로그램 실행 결과 가져오기
#include <Process.h> int main( int argc, char** argv ) { system( "ls" ); return 0; }
이러한 방식으로 system() 함수를 이용하여 외부 프로그램을 실행할 수 있다.
하지만, system 함수는 실행 결과의 상태를 알려주는 int 값을 리턴할 뿐
ls의 출력결과를 main 함수 내부에서 가져올 수 없다.
(solution 1)
결과값을 받아오려면, 파일로 출력하여 다시 읽어들이는 방법을 이용하면 된다.
#include <Process.h> #include <iostream> #include <fstream> using namespace std; int main( int argc, char** argv ) { system( "ls > aaa" ); char tmp[256]; ifstream fin( aaa ); while( fin >> tmp ) { cout << tmp << endl; } fin.close(); return 0; }
실행하면 aaa 라는 text file이 출력되어 있을 것이다..
출력 결과를 얻어온 후 다시 system( “rm -f aaa” ); 를 실행하여 파일을 삭제해줄 수 도 있다.
(solution 2)
popen() 함수를 이용하는 좀 더 세련된 방법
#include <sstream> #include <iostream> using namespace std; int main( int argc, char** argv ) { FILE* stream = popen( "ls", "r" ); ostringstream output; while( !feof(stream) && !ferror(stream) ) { char buf[128]; int bytesRead = fread( buf, 1, 128, stream ); output.write( buf, bytesRead ); } string result = output.str(); cout << result << endl; }
(출처) http://stackoverflow.com/questions/309491/how-do-i-read-the-results-of-a-system-call-in-c