From 938091dc22d7ea924ee5195dd16019cdbc682b19 Mon Sep 17 00:00:00 2001 From: Skylar Date: Fri, 25 Mar 2022 20:40:17 +1300 Subject: [PATCH] Added history executing --- ash.c | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 6 deletions(-) diff --git a/ash.c b/ash.c index 8cce04d..ba398a8 100644 --- a/ash.c +++ b/ash.c @@ -6,18 +6,27 @@ char *readLine(void) { + printf("ash> "); char *fullLine = malloc(1000); int adder = 0; while (1) { + char in = fgetc(stdin); if (in == EOF || in == '\n') { // ending on null byte fullLine[adder] = '\0'; + + if (fullLine[0] == '\0') + { + printf("ash> "); + continue; + } + return fullLine; } @@ -68,17 +77,53 @@ void executeAndWait(char **userArgs) void historyCommand(char *commandType, char **historyOfUser) { + if (historyOfUser[0]==NULL) + { + printf("No history\n"); + return; + } - for (int i = 1; i <= 10; i++) + if (commandType==NULL) + { + for (int i = 1; i <= 10; i++) + { + printf("%d: %s\n", i, historyOfUser[i-1]); + + if (historyOfUser[i]==NULL) + { + break; + } + } + } + + else { - printf("%d: %s\n", i, historyOfUser[i-1]); + // Getting the history value wanted + char *extraString; + char *historyWanted = malloc(1000); + strcpy(historyWanted, commandType); + + // Converting to int to get the history string + long histNum = strtol(historyWanted, &extraString, 10); + char *fullCommandWanted = malloc(1000); - if (historyOfUser[i]==NULL) + // if doesnt exist, return + if (historyOfUser[histNum-1]==NULL) { - break; + printf("That value has no history!\n"); + return; } + + strcpy(fullCommandWanted, historyOfUser[histNum-1]); + + // Running the history command + char **historyArgs = malloc(1000); + splitToArgs(fullCommandWanted, historyArgs); + + executeAndWait(historyArgs); } + } void addToHistory(char *userString, char **historyOfUser) @@ -117,14 +162,22 @@ int main() // Taking the users full line fullCommand = readLine(); - // Adding this to command history - addToHistory(fullCommand, historyCommands); + // Taking a constant version of full line + char *constantFullCommand = malloc(1000); + strcpy(constantFullCommand, fullCommand); // Resetting an args 2d array char **userArgs = malloc(1000); // Filling the array with users args splitToArgs(fullCommand, userArgs); + + // Adding this to command history, unless it is the history check command + if (strcmp(userArgs[0], "history") != 0 && strcmp(userArgs[0], "h") != 0) + { + addToHistory(constantFullCommand, historyCommands); + } + // If command is cd if (strcmp(userArgs[0], "cd") == 0) {