C:运行系统命令,并获取输出? [英] C: Run a System Command and Get Output?

查看:150
本文介绍了C:运行系统命令,并获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output\">How我可以运行从C外部程序和解析它的输出?

我想在Linux中运行命令,并获得它所输出返回的文本...但我不希望这个文印到屏幕上。必须有比制作一个临时文件右一个更优雅的方式?

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. There has to be a more elegant way than making a temporary file right?

推荐答案

您希望的popen 功能。这就是我们运行命令ls / etc而向允许输出在控制台的一个例子。

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

这篇关于C:运行系统命令,并获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆