popen 외부 프로그램 실행 결과 받아오기
윈도우나 유닉스계열에서 프로그램내에서 시스템 명령이나 특정프로그램을 실행하고 그 결과값을 확인하고자 할때 popen함수를 이용하여 결과를 확인
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> /* errno */
#include <string.h> /* strerror */
#ifdef WIN32
#define popen _popen
#define pclose _pclose
#endif
int main(int argc, char* argv[])
{
const char *pszCommand = "dir";
FILE *fp = NULL;
size_t readSize = 0;
char pszBuff[1024];
// 명령어 실행
fp = popen(pszCommand, "r");
if( !fp)
{
printf("오류 [%d:%s]\n", errno, strerror(errno));
return -1;
}
// 결과값 읽기
readSize = fread( (void*)pszBuff, sizeof(char), 1024-1, fp );
if( readSize == 0 )
{
pclose(fp);
printf("오류 [%d:%s]\n", errno, strerror(errno));
return -1;
}
pclose(fp);
pszBuff[readSize]=0;
// 결과 출력
printf("결과 : %s\n", pszBuff);
return 0;
}