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/console_line.c b/src/console_line.c index 7fe7e8a..6c31c86 100644 --- a/src/console_line.c +++ b/src/console_line.c @@ -84,8 +84,14 @@ void print_input_line() { char *hostname = get_hostname(); char *cwd = get_working_directory(); printf(BRIGHT_GREEN "%s" RESET BRIGHT_MAGENTA "@" RESET BRIGHT_RED "%s" RESET BRIGHT_MAGENTA ":" RESET BRIGHT_BLUE "%s" RESET BRIGHT_MAGENTA "$ " RESET, username, hostname, cwd); - free(hostname); - free(cwd); + if (hostname != NULL) { + free(hostname); + hostname = NULL; + } + if (cwd != NULL) { + free(cwd); + cwd = NULL; + } } /** 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