C: Run a System Command and Get Output? 在C程序中调用工具,并且得到结果。

现在在做一个WIFI API相关的库,这样就可以让其他的人管理WIFI.

在调用API的时候要回复SHELL打印的信息,比如说搜索热点,而且不在SHELL中打印出来。然后把信息返回给调用API的程序。

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

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




posted @ 2015-10-14 16:29  johnny_shi  阅读(291)  评论(0编辑  收藏  举报