IT story

C : 시스템 명령을 실행하고 출력을 얻습니까?

hot-time 2020. 7. 5. 07:54
반응형

C : 시스템 명령을 실행하고 출력을 얻습니까? [복제]


가능한 중복 :
C에서 외부 프로그램을 실행하고 출력을 구문 분석하는 방법은 무엇입니까?

리눅스에서 명령을 실행하고 출력 된 텍스트를 반환 하려고 하지만 이 텍스트를 화면에 인쇄하고 싶지 않습니다 . 임시 파일을 만드는 것보다 더 우아한 방법이 있습니까?


" popen "기능을 원합니다 . 다음은 "ls / etc"명령을 실행하고 콘솔에 출력하는 예입니다.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

프로세스 간 통신이 필요합니다. 파이프 또는 공유 버퍼를 사용하십시오 .


일반적으로 명령이 외부 프로그램 인 경우 OS를 사용하여 여기에서 도움을 줄 수 있습니다.

command > file_output.txt

따라서 C 코드는 다음과 같은 작업을 수행합니다.

exec("command > file_output.txt");

그런 다음 file_output.txt 파일을 사용할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output

반응형