[英]Using a system call to execute “which” command in C
我正在尝试获取特定用户输入的路径名。 例如,如果用户输入ls | 我想创建两个字符串,第一个字符串是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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.