gpt4 book ai didi

c - 在我的 shell 中存储命令历史的链表实现

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:33 24 4
gpt4 key购买 nike

我正在开发一个基本的 unix shell,我想添加的功能之一是“历史”命令,它会显示用户在该 session 期间尝试过的所有命令。我的研究表明,实现这一点的最佳方法是使用链表。

这是我的实现,无论我输入什么命令,它只存储“历史”命令。我只在主 shell 程序中包含了我认为必要的内容。

这里是输出

//output
mish> echo Hello World
Hello World
mish> date
Sat Dec 14 16:35:31 EST 2013
mish> history
============ Command History ============
[1] history
[2] history
[3] history
=========================================
mish>

这是主 shell

//main.c
List *historyList = malloc (sizeof(List));
//get command
addHistory(historyList, command);

//do other shell stuff (parsing, etc.)
if (userInput is "history)
printHistory;

这里是history.c

//history.c
typedef struct History{
char *command;
struct History *next;
}History;

typedef struct List{
unsigned int count;
History *top;
}List;

void addHistory(List *list, char *cmd){
History *h = (History*) malloc(sizeof(History));
h->command = cmd;

if (isHistoryEmpty(list)){
h->next = NULL;
list->top = h;
}
else{
h->next = list->top;
list->top = h;
}
list->count++;
}

bool isHistoryEmpty(List *list){
if (list->count == 0){
return true;
}
return false;
}

void clearHistory(List *list){
while (!isHistoryEmpty(list)){
History *temp = list->top;
list->count--;
list->top = list->top->next;
free(temp);
}
free(list);
}

void printHistory(List *list){
int i = 1;
printf("Command History\n");
while (!list->top == NULL){ //this line causes a warning on compilation (comparison between pointer and integer)
History *temp = list->top;
printf("[%d] %s \n", i, temp->command);
list->top = list->top->next;
i++;
}
} 19,2-5 Top

最佳答案

您没有复制command,因此您所有的历史记录项都共享command 缓冲区。当用户键入命令时,它会被读入唯一缓冲区,所有历史记录项都会“更改”为最新命令。

History *h = (History*) malloc(sizeof(History));
h->command = (char*) malloc(sizeof(char) * (strlen(cmd) + 1));
strcpy(h->command, cmd);

清除列表后必须释放副本。

一些错误:

  • ! 的优先级高于 ==,所以要么使用 != 要么使用方括号:!(list ->top == NULL)

  • 当遍历列表时,您不得修改 list->top。相反,将 temp 的声明和初始化移到循环外部,然后使用 temp 而不是 list->top

关于c - 在我的 shell 中存储命令历史的链表实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20588556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com