C: システムコマンドを実行して出力を取得しますか? [重複] 質問する

C: システムコマンドを実行して出力を取得しますか? [重複] 質問する

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

ベストアンサー1

開く「 」機能。以下は「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;
}

おすすめ記事