1

我正在使用以下代码提取系统命令的输出。我没有在 PATH 变量中为“pic”设置路径。我想存储命令的输出"which pic"并且不想在控制台上显示它。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main ()
{
    FILE *fp;
  int status;
  char path[1035];
char *command = "which pic";


  /* Open the command for reading. */
  fp = popen(command, "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(0);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path)-1, fp) != NULL) {
   cout<<"<<<<<<<<<<,"<<endl;
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

但它在控制台中显示以下输出:

which: no pic in(/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin)
4

1 回答 1

1

"which pic 2>&1"按照您的命令运行。您想从 捕获所有输出which,包括其错误(发送到 stderr)。

于 2013-01-03T10:30:51.543 回答