Question: #include #include #include #include #define BUF_SIZE 1024 #define HIST_SIZE 15 int main(int argc, char **argv) { char *buffer = malloc(sizeof(char) * BUF_SIZE); char **token =

#include  #include  #include  #include  #define BUF_SIZE 1024 #define HIST_SIZE 15 int main(int argc, char **argv) { char *buffer = malloc(sizeof(char) * BUF_SIZE); char **token = malloc(sizeof(char*) * BUF_SIZE); int c, flag, position; char* hist[HIST_SIZE] = { NULL }; // History array int hist_count = 0; // Number of commands in history flag = 0; // signal(SIGINT, SIG_IGN); // Ignoring SIGINT, commented out for simplicity do { position = 0; char pathname[512]; memset(pathname, '\0', 512); getcwd(pathname, 512); printf(" PSUsh %s ", pathname); while (true) { c = getchar(); if (c == EOF) exit(EXIT_SUCCESS); if (c == ' ') { buffer[position] = '\0'; break; } else { buffer[position] = c; } position++; } token[0] = strtok(buffer, " "); for (position = 1; position < BUF_SIZE; position++) { token[position] = strtok(NULL, " "); if (token[position] == NULL) { break; } } token = realloc(token, sizeof(char*) * position); // Build-in commands if (!strcmp(token[0], "bye")) flag = 1; else if (!strcmp(token[0], "cwd")) printf(" cwd: %s ", pathname); else if (!strcmp(token[0], "cd") && token[2] == NULL) { if (token[1] == NULL) chdir(getenv("HOME")); else chdir(token[1]); } else if (!strcmp(token[0], "history")) { for (int i = 0; i < hist_count; i++) { printf("%d: %s ", i + 1, hist[i]); } } else if (token[0] != NULL) { // Free the oldest command if history is full if (hist_count == HIST_SIZE) { free(hist[HIST_SIZE - 1]); } // Shift the history array to make space for the new command for (int i = hist_count - 1; i > 0; i--) { hist[i] = hist[i - 1]; } // Store the new command in history hist[0] = strdup(token[0]); // Update the history count if (hist_count < HIST_SIZE) { hist_count++; } } else { printf(" "); } } while (flag == 0); free(buffer); free(token); }

I'm making my shell

I want to make history command, which store 15 command. if new command is entered, first one remove. its queue. Please help me. my code doesn't display history if user enter history

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!