Linux C:运行系统命令并获取输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/646241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:06:09  来源:igfitidea点击:

C: Run a System Command and Get Output?

clinuxsystem

提问by jimi hendrix

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 notwant this text printed to screen. Is there a more elegant way than making a temporary file?

我想在 linux 中运行一个命令并返回它输出的文本,但我希望将此文本打印到屏幕上。有没有比制作临时文件更优雅的方法?

回答by dirkgently

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

您需要某种进程间通信。使用管道或共享缓冲区。

回答by dirkgently

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), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

回答by Tommy Hui

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 文件。