I am currently tasked with a homework assignment to write a primitive shell in C, and am having difficulty implementing the shell feature which constructs a path to a given requested program. e.g. Transforming user input of wc
to /usr/bin/wc
.
Getenv() is working fine to get the value of $PATH. Using code supplied by my instructors, I've also parsed this value into individual 'tokens,' where a token is defined: typedef char *tok_t
My question is how can I fix this implementation of the following function, which seeks to return the absolute path to a given filename if found, and NULL
otherwise.
The main issue here is concatenating a tok_t
and a char*
to produce the full pathname.
char *resolve_path(char *filename) {
printf("trying to resolve path...\n");
char *path_var = getenv("PATH");
tok_t *path_list = get_toks(path_var);
//fprint_tok(stdout, path_list);
char *path;
for (int i = 0; path_list[i]; i++) {
path = (char*) malloc(PATH_MAX);
strcat(path, *path_list[i]);
strcat(path, filename);
printf("Trying... %s\n", path);
if (file_exists(path)) {
return path;
}
free(path);
}
return NULL;
}
Should I bother with malloc() and strcat(), or is there some better way of implementing this? Currently getting segfaults and warnings about the type compatibility in use of strcat().