使用系统调用在C中执行“which”命令

时间:2016-11-08 17:09:02

标签: c unix

我正在尝试获取特定用户输入的路径名。例如,如果用户输入ls | wc我想创建两个字符串,第一个是a(ls),第二个是a(wc)所以我有路径名。我在C程序中执行此操作,我的代码如下所示。

/*This is a basic example of what i'm trying to do*/

char* temp;
printf("Enter a command\n");
/* assume user enters ls */
scanf("%s", temp);        
char* path = system(which temp);
printf("Testing proper output: %s\n", path);

/*I should be seeing "/bin/ls" but the system call doesn't work properly*/

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:3)

您正在使用未初始化的指针。但即使你已经正确地初始化它,它仍然无法工作,因为system()没有返回它执行的命令的输出。 您想使用popen()来执行此操作。

这是一个例子(未经测试):

if (fgets(cmd, sizeof cmd, stdin)) {
   char cmd[512];
   cmd[strcspn(cmd, "\n")] = 0; // in case there's a trailing newline
   char which_cmd[1024];
   snprintf(which_cmd, sizeof which_cmd, "which %s", cmd);
   char out[1024];
   FILE *fp = popen(which_cmd);
   if (fp && fgets(out, sizeof out, fp)) {
      printf("output: %s\n", out);
   }
}