Line data Source code
1 : #include "history_command.h" 2 : 3 : CommandHistory command_history; 4 : 5 2 : void init_command_history() 6 : { 7 2 : command_history.history_count = 0; 8 2 : command_history.current_index = -1; 9 2 : load_command_history_from_file(); 10 2 : } 11 : 12 20 : void add_to_command_history(const char *command) 13 : { 14 20 : if (command_history.history_count < MAX_HISTORY_SIZE) 15 : { 16 20 : strcpy(command_history.history[command_history.history_count], command); 17 20 : command_history.history_count++; 18 20 : command_history.current_index = command_history.history_count; 19 20 : save_command_history_to_file(); 20 : } 21 : else 22 : { 23 0 : printf("History is full. Delete your history.txt file.\n"); 24 : } 25 20 : } 26 : 27 20 : void save_command_history_to_file() 28 : { 29 20 : FILE *file = fopen(HISTORY_FILE, "a"); // Open in append mode 30 20 : if (file == NULL) 31 : { 32 0 : perror("Error opening history file for writing"); 33 0 : return; 34 : } 35 : 36 : // Save the new command if it's not already in the history 37 20 : if (command_history.history_count > 0) 38 : { 39 20 : int last_index = command_history.history_count - 1; 40 20 : if (strcmp(command_history.history[last_index], command_history.history[last_index - 1]) != 0) 41 : { 42 19 : fprintf(file, "%s\n", command_history.history[last_index]); 43 : } 44 : } 45 : else 46 : { 47 0 : fprintf(file, "%s\n", command_history.history[0]); 48 : } 49 : 50 20 : fclose(file); 51 : } 52 : 53 2 : void load_command_history_from_file() 54 : { 55 2 : FILE *file = fopen(HISTORY_FILE, "r"); 56 2 : if (file != NULL) 57 : { 58 : char line[1000]; 59 778 : while (fgets(line, sizeof(line), file) != NULL && command_history.history_count < MAX_HISTORY_SIZE) 60 : { 61 : // Remove newline character if present 62 776 : size_t length = strlen(line); 63 776 : if (line[length - 1] == '\n') 64 : { 65 776 : line[length - 1] = '\0'; 66 : } 67 : 68 776 : strcpy(command_history.history[command_history.history_count], line); 69 776 : command_history.history_count++; 70 776 : command_history.current_index = command_history.history_count; 71 : } 72 2 : fclose(file); 73 : } 74 : else 75 : { 76 : // Create the history file if it doesn't exist 77 0 : file = fopen(HISTORY_FILE, "w"); 78 0 : if (file != NULL) 79 : { 80 0 : fclose(file); 81 : } 82 : else 83 : { 84 0 : perror("Error creating history file"); 85 : } 86 : } 87 2 : }