我有一个算法,它查看一个包含多个路径的数组,并检查数组中列出的任何目录中是否存在命令(例如 ls、wc、cat ... 等)。如果在其中一个目录中找到该文件,则返回完整的目录路径。
char *LookupPath(char **argv, char **dir)
{
/* String Name To Be Returned */
char *result;
char path_name[MAX_PATH_LEN] = {0};
int i;
/* Check To See If File Name Is Already An Absolute Path Name */
if(*argv[0] == '/') {
}
/* Look In Path Directories */
for(i = 0; dir[i] != NULL; i++) {
strncat(path_name, dir[i], sizeof(path_name));
strncat(path_name, "/", sizeof(path_name));
strncat(path_name, argv[0], sizeof(path_name));
printf("pathname: %s\n", path_name);
result = path_name;
if(access(result, F_OK) == 0) {
printf("SUCCESS!\n");
printf("result: %s\n", result);
return result;
}
path_name[0] = '\0';
}
/* File Name Not Found In Any Path Variable */
return NULL;
}
新问题:当使用诸如 ls -l 或其他任何命令时,结果效果很好,如下面的结果代码所示。
pathname: /usr/lib/lightdm/lightdm/ls
pathname: /usr/local/sbin/ls
pathname: /usr/local/bin/ls
pathname: /usr/sbin/ls
pathname: /usr/bin/ls
pathname: /sbin/ls
pathname: /bin/ls
SUCCESS!
result: /bin/ls
但是,现在当我只使用一个简单的命令(例如'ls')时...结果是错误的...因为某种原因,一个换行符被添加到ls...?它出现:
pathname: /usr/lib/lightdm/lightdm/ls
pathname: /usr/local/sbin/ls
pathname: /usr/local/bin/ls
pathname: /usr/sbin/ls
pathname: /usr/bin/ls
pathname: /sbin/ls
pathname: /bin/ls
pathname: /usr/games/ls
pathname: /usr/local/games/ls
ls
: Command Not Found!
我不知道为什么。有什么办法可以把它缩减为'ls'。当它只是一个简单的 ls 命令时,我不知道为什么要向 argv[0] 添加一个换行符。:S