162

重複の可能性:
Cから外部プログラムを実行してその出力を解析するにはどうすればよいですか?

Linuxでコマンドを実行し、出力されたテキストを返したいのですが、このテキストを画面に出力したくありません。一時ファイルを作成するよりもエレガントな方法はありますか?

4

2 に答える 2

294

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;
}
于 2009-03-14T17:01:06.767 に答える
5

ある種のプロセス間通信が必要です。パイプまたは共有バッファーを使用します。

于 2009-03-14T16:59:59.310 に答える