그렉은 완전히 정확하지 않습니다. 당신은 시스템을 사용할 수 있지만, 정말 나쁜 생각입니다. 명령의 출력을 임시 파일에 기록한 다음 파일을 읽음으로써 시스템을 사용할 수 있지만 popen()은 훨씬 더 나은 방법입니다. 예를 들면 :
#include <stdlib.h>
#include <stdio.h>
void
die(char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int
main(void)
{
size_t len;
FILE *f;
int c;
char *buf;
char *cmd = "echo foo";
char *path = "/tmp/output"; /* Should really use mkstemp() */
len = (size_t) snprintf(buf, 0, "%s > %s", cmd, path) + 1;
buf = malloc(len);
if(buf == NULL) die("malloc");
snprintf(buf, len, "%s > %s", cmd, path);
if(system(buf)) die(buf);
f = fopen(path, "r");
if(f == NULL) die(path);
printf("output of command: %s\n", buf);
while((c = getc(f)) != EOF)
fputc(c, stdout);
return EXIT_SUCCESS;
}
파일 시스템에서 파일을 떠나 이러한 접근 방식에 문제가 많은 ... (리디렉션에 대한 구문의 휴대 성, 임시 파일을 읽는 다른 프로세스와 보안 문제가 있습니다, 등, 등)
많은 시간을 물었습니다. 한 가지 예 : http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output – dmckee
죄송합니다. 질문을 썼다, 나는 관련 질문을 보지 않았다. 감사! – make