programing

C: 시스템 명령어를 실행하여 출력을 얻으시겠습니까?

itsource 2022. 8. 7. 17:07
반응형

C: 시스템 명령어를 실행하여 출력을 얻으시겠습니까?

중복 가능성:
C에서 외부 프로그램을 실행하여 출력을 해석하려면 어떻게 해야 합니까?

Linux에서 명령어를 실행하여 출력한 텍스트를 반환하고 싶은데 이 텍스트를 스크린에 인쇄하고 싶지 않습니다.임시 파일을 만드는 것보다 더 우아한 방법이 있을까요?

"팝펜" 기능이 필요합니다.다음은 명령어 "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), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

일종의 프로세스 간 커뮤니케이션이 필요합니다.파이프 또는 공유 버퍼를 사용합니다.

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

반응형