From 491aef5c49d85c1ecd1c1c44f68ff8772e4dec17 Mon Sep 17 00:00:00 2001 From: Chris Cromer Date: Tue, 6 Jul 2021 15:11:59 -0400 Subject: [PATCH] add cd builtin --- src/builtins.c | 29 +++++++++++++++++++++++++++++ src/include/builtins.h | 2 ++ 2 files changed, 31 insertions(+) diff --git a/src/builtins.c b/src/builtins.c index b483e51..1f33298 100644 --- a/src/builtins.c +++ b/src/builtins.c @@ -16,8 +16,10 @@ #include #include #include +#include #include "array.h" #include "builtins.h" +#include "console_line.h" /** * Check if the command is a builtin or not. @@ -44,6 +46,9 @@ void run_builtin(StringArray *args) { if (strcmp(args->array[0], "exit") == 0) { exit_shell(args); } + else if (strcmp(args->array[0], "cd") == 0) { + change_directory(args); + } else { fprintf(stderr, "Builtin %s does not exist!\n", args->array[0]); } @@ -57,3 +62,27 @@ void exit_shell(StringArray *args) { free_string_array(args); exit(EXIT_SUCCESS); } + +/** + * Change the directory to what the user inputs. + * @param args The arguments the user input. + */ +void change_directory(StringArray *args) { + if (args->size > 2) { + fprintf(stderr, "Too many arguments!\n"); + return; + } + else if (args->size == 1) { + char *cwd = get_working_directory(); + fprintf(stdout, "%s\n", cwd); + if (cwd != NULL) { + free(cwd); + cwd = NULL; + } + } + else { + if (chdir(args->array[1]) != 0) { + perror("cd"); + } + } +} diff --git a/src/include/builtins.h b/src/include/builtins.h index 918d168..ed76345 100644 --- a/src/include/builtins.h +++ b/src/include/builtins.h @@ -23,4 +23,6 @@ bool is_builtin(char *command); void run_builtin(StringArray *args); void exit_shell(StringArray *args); + +void change_directory(StringArray *args); #endif