运行系统命令并得到输出?(复制)

时间:2022-02-24 20:11:41

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

可能的副本:如何从C运行一个外部程序并解析它的输出?

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?

我想在linux中运行一个命令,并得到它输出的文本,但是我不希望将这个文本打印到屏幕上。是否有比临时文件更优雅的方法?

3 个解决方案

#1


201  

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

你想要的是“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;
}

#2


4  

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

你需要某种进程间的交流。使用管道或共享缓冲区。

#3


-7  

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

所以C代码就像这样。

exec("command > file_output.txt");

Then you can use the file_output.txt file.

然后可以使用file_output。txt文件。

#1


201  

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

你想要的是“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;
}

#2


4  

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

你需要某种进程间的交流。使用管道或共享缓冲区。

#3


-7  

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

所以C代码就像这样。

exec("command > file_output.txt");

Then you can use the file_output.txt file.

然后可以使用file_output。txt文件。