which: multiple arguments, support -a

This commit is contained in:
K. Lange 2018-10-10 07:15:12 +09:00
parent 9dee25e64a
commit 940a15eccb

View File

@ -18,20 +18,30 @@
int main(int argc, char * argv[]) {
if (argc < 2) {
int ret_val = 0;
int i = 1;
int print_all = 0;
if (i < argc && !strcmp(argv[i],"-a")) {
print_all = 1;
i++;
}
if (i == argc) {
return 1;
}
if (strstr(argv[1], "/")) {
for (; i < argc; ++i) {
if (strstr(argv[i], "/")) {
struct stat t;
if (!stat(argv[1], &t)) {
if (!stat(argv[i], &t)) {
if ((t.st_mode & 0111)) {
printf("%s\n", argv[1]);
return 0;
}
}
} else {
char * file = argv[1];
char * file = argv[i];
char * path = getenv("PATH");
if (!path) {
path = DEFAULT_PATH;
@ -39,6 +49,7 @@ int main(int argc, char * argv[]) {
char * xpath = strdup(path);
char * p, * last;
int found = 0;
for ((p = strtok_r(xpath, ":", &last)); p; p = strtok_r(NULL, ":", &last)) {
int r;
struct stat stat_buf;
@ -54,11 +65,14 @@ int main(int argc, char * argv[]) {
if (!(stat_buf.st_mode & 0111)) {
continue; /* XXX not technically correct; need to test perms */
}
found = 1;
printf("%s\n", exe);
return 0;
if (print_all) continue;
break;
}
free(xpath);
return 1;
if (!found) ret_val = 1;
}
return 1;
}
return ret_val;
}