codecrafters-shell-c

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit 2c285c8d56d5123400372bbfa919a17ea35351f9
parent 3ddd50661aa344b3b62212aedc7954ce0b98795f
Author: 5hif7y <[email protected]>
Date:   Tue, 31 Dec 2024 13:09:01 -0300

8 type executable files

Diffstat:
Mapp/main.c | 39+++++++++++++++++++++++++++++++++++++--
1 file changed, 37 insertions(+), 2 deletions(-)

diff --git a/app/main.c b/app/main.c @@ -2,9 +2,10 @@ #include <string.h> #include <stdbool.h> #include <stdlib.h> +#include <unistd.h> void parse_input(const char *input, char *cmd, char **args, int *argc); - +bool find_executable(const char *cmd, char *result_path); int main() { @@ -45,11 +46,14 @@ int main() { printf("\n"); } else if(!strcmp(cmd, "type")){ if(argc > 0){ + char path[512]; if(!strcmp(args[0], "echo") || !strcmp(args[0], "exit") || !strcmp(args[0], "type")){ printf("%s is a shell builtin\n", args[0]); + } else if (find_executable(args[0], path)) { + printf("%s is %s\n", args[0], path); } else { - printf("%s not found\n", args[0]); + printf("%s not found\n", args[0]); } } else { printf("Usage: type [command]\n"); @@ -82,4 +86,35 @@ void parse_input(const char *input, char *cmd, char **args, int *argc){ args[*argc] = NULL; } +bool find_executable(const char *cmd, char *result_path){ + char *path_env = getenv("PATH"); + if(!path_env){ + return false; + } + + char path_copy[1024]; + strncpy(path_copy, path_env, sizeof(path_copy) - 1); + path_copy[sizeof(path_copy) - 1] = '\0'; + + char separator = ':'; +#ifdef _WIN32 + separator = ';'; +#endif + + char *dir = strtok(path_copy, &separator); + while (dir != NULL){ + snprintf(result_path, 512, "%s/%s", dir, cmd); + + if(access(result_path, X_OK) == 0){ + return true; + } + + dir = strtok(NULL, &separator); + } + + return false; +} + + +