2019年12月17日 星期二

C: Run a System Command and Get Output?

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

Use the "popen" function.
Here's an example of running the command "ls /etc" and outputing to the console.
#include 
#include 


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;
}

沒有留言: