[英]How can I read and write from files using the headers fcntl.h and unistd.h?
[英]How do I use **environ from unistd.h to search for the right path?
嗨,我正在尝试将execvp()
与**environ
变量结合使用,以找到用户所输入命令的正确路径。
问题是我不太了解如何执行此操作。 我知道我只能尝试打开命令文件以检查它们是否存在,但我不知道如何从**environ
获取需要搜索的路径。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char *start, *end;
char ch;
char* path = getenv("PATH");
if (!path) {
fprintf(stderr, "could not get $PATH, exiting\n");
exit(EXIT_FAILURE);
}
start = path;
do {
end = strchr(start, ':');
if (!end) {
printf("%s\n", start);
} else {
ch = *end;
*end = '\0';
printf("%s\n", start);
*end = ch;
}
start = end + 1;
} while (end != NULL);
return 0;
}
这个小程序演示了如何从env [PATH]获得单独的路径。
人execvp:
execvp()将在搜索可执行文件时复制外壳程序的动作
因此,您不必使用** environ变量来找到命令的正确路径 ; execvp()
为您做到了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.