C: Run a System Command and Get Output? [duplicate

2019-01-01 05:11发布

Possible Duplicate:
How can I run an external program from C and parse its output?

I want to run a command in linux and get the text returned of what it outputs, but I do not want this text printed to screen. Is there a more elegant way than making a temporary file?

标签: c linux system
3条回答
墨雨无痕
2楼-- · 2019-01-01 05:27

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

查看更多
无色无味的生活
3楼-- · 2019-01-01 05:30

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

#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;
}
查看更多
人间绝色
4楼-- · 2019-01-01 05:30

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

查看更多
登录 后发表回答