codecrafters-shell-c

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

commit f6803f48c44896696c7de3f300ef7631df2aa4b8
parent f9028fa2f85773cbf4dba9b08aab38f9d84f5b6c
Author: 5hif7y <[email protected]>
Date:   Mon, 30 Dec 2024 21:02:56 -0300

7 type and parsing implementation

Diffstat:
Mapp/main.c | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
1 file changed, 55 insertions(+), 7 deletions(-)

diff --git a/app/main.c b/app/main.c @@ -1,12 +1,19 @@ #include <stdio.h> #include <string.h> #include <stdbool.h> +#include <stdlib.h> + +void parse_input(const char *input, char *cmd, char **args, int *argc); + int main() { // Process user input bool running = true; char input[100]; + char cmd[100]; + char *args[10]; + int argc; while(running){ // Flush after every printf @@ -23,18 +30,59 @@ int main() { if(n > 0 && input[n - 1] == '\n'){ input[n - 1] = '\0'; } + + // Parse input + parse_input(input, cmd, args, &argc); + // Evaluate commands: - if(!strcmp(input, "exit")){ + if(!strcmp(cmd, "exit")){ printf("Exiting...\n"); running = false; - } else if(!strcmp(input, "exit 0")){ + } else if(!strcmp(cmd, "exit 0")){ //printf("Exiting...\n"); running = false; - } else if(!strncmp(input, "echo", strlen("echo"))){ - printf("%s\n", input + 5); - } else { - printf("%s: command not found\n", input); - } + } else if(!strcmp(cmd, "echo")){ + for (int i = 0; i < argc; i++){ + printf("%s ", args[i]); + } + printf("\n"); + } else if(!strcmp(cmd, "type")){ + if(argc > 0){ + if(!strcmp(args[0], "echo") || !strcmp(args[0], "exit") + || !strcmp(args[0], "type")){ + printf("%s is a shell builtin\n", args[0]); + } else { + printf("%s not found\n", args[0]); + } + } else { + printf("Usage: type [command]\n"); + } + } else { + printf("%s: command not found\n", input); + } } return 0; } + + +void parse_input(const char *input, char *cmd, char **args, int *argc){ + + char input_cpy[100]; + strncpy(input_cpy, input, sizeof(input_cpy) - 1); + input_cpy[sizeof(input_cpy) - 1] = '\0'; + + char *token = strtok(input_cpy, " "); + if(token != NULL){ + strcpy(cmd, token); + } + + *argc = 0; + while((token = strtok(NULL, " ")) != NULL){ + args[*argc] = token; + (*argc)++; + } + + args[*argc] = NULL; +} + +