c - 在C中使用系统调用执行 "which"命令

标签 c unix

我正在尝试获取特定用户输入的路径名。例如,如果用户输入 ls | wc 我想创建两个字符串,第一个是which(ls),第二个是which(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*/

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

最佳答案

您正在使用未初始化的指针。但即使您已正确初始化它,它仍然无法工作,因为 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);
   }
}

关于c - 在C中使用系统调用执行 "which"命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40492658/

相关文章:

c - 套接字无法连接到服务器

c++ - 如何在 x86-64 上优化 C 和 C++ 中的函数返回值?

c - 我如何修复由 c 中的 man 2 stat 成员造成的泄漏

c - 在ubuntu上安装glibtop

c - C++中复制字符串的函数选择,注重性能

linux - 仅当该行不存在时,如何向不同子目录下的多个文本文件添加一行?

c - 多次 pthread_create 调用后出现 `Cannot allocate memory` 错误

shell - 如何在使用 sed 时转义 & 字符

c++ - 指向指针 : managing strings for different languages 的指针数组

将日期指针与日期进行比较