[英]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.