在自己的C Shell中保存历史
我正在编写自己的C Shell,在实现一些东西来维护命令历史记录时遇到了问题。 我想将它存储在一个包含整数和字符串的结构中(这样我就可以将命令和它在内存中的位置放在一起),我只想存储20个元素 我尝试过使用其他人在这个网站上提出的问题的代码,但当我编译它时,它只返回一个分段错误,所以我猜指针有问题 以下是我找到的所有与历史相关的代码:在自己的C Shell中保存历史,c,segmentation-fault,C,Segmentation Fault,我正在编写自己的C Shell,在实现一些东西来维护命令历史记录时遇到了问题。 我想将它存储在一个包含整数和字符串的结构中(这样我就可以将命令和它在内存中的位置放在一起),我只想存储20个元素 我尝试过使用其他人在这个网站上提出的问题的代码,但当我编译它时,它只返回一个分段错误,所以我猜指针有问题 以下是我找到的所有与历史相关的代码: char** cmdHistory; /* command history - no longer than 20 elements & null ter
char** cmdHistory; /* command history - no longer than 20 elements & null terminated */
int historySize = 0;
void addToHistory(char* newEntry) {
char** h;
int historySize = 0;
while (*cmdHistory != NULL)
if (sizeof(cmdHistory) == 20) {
char** newPtr = ++cmdHistory;
free(cmdHistory[0]);
cmdHistory = newPtr;
h = (char**)realloc(cmdHistory,20*sizeof(int));
cmdHistory = h;
cmdHistory[20] = newEntry;
} else {
h = (char**)realloc(cmdHistory,sizeof(int)+sizeof(cmdHistory));
cmdHistory = h;
cmdHistory[historySize] = newEntry;
++historySize;
}
}
void printHistory() {
char** currCmd = cmdHistory;
printf("\n\n");
while (*currCmd != NULL) {
printf("%s\n", *currCmd);
currCmd++;
}
printf("\n\n");
}
int main() {
cmdHistory[20] = NULL; /* null terminate the history */
}
我对C没有什么用处,所以非常感谢您的帮助。您可以使用链接列表实现历史记录,始终在头部添加当前命令。像这样:
#include <stdio.h>
typedef struct history
{
char *ent;
struct history * next;
}hist;
hist *top = NULL;
void add(char *s)
{
hist *h = (hist *) malloc(sizeof(hist));
h->ent = s;
h->next = top;
top = h;
}
void print()
{
hist *i;
for (i = top; i != NULL; i = i->next)
printf("%s\n", i->ent);
}
int main()
{
add("command");
print();
}
#包括
typedef结构历史
{
特征;
结构历史*下一步;
}历史的;
hist*top=NULL;
无效添加(字符*s)
{
hist*h=(hist*)malloc(sizeof(hist));
h->ent=s;
h->next=顶部;
top=h;
}
作废打印()
{
历史*i;
for(i=top;i!=NULL;i=i->next)
printf(“%s\n”,i->ent);
}
int main()
{
添加(“命令”);
打印();
}
“我在写我自己的C shell”你是说你在用C编写bourne shell,还是C shell?如果是后者…为什么?使用libreadline,它会自动保存历史记录并支持自定义完成。代码很奇怪。例如,我不确定为什么要重新定位该表,因为如果该表应该具有固定的大小,则添加了一个新元素。整个事情在我看来非常可疑,无论你在哪里找到你正在使用的代码,我都会去其他地方寻找。至于为什么会出现故障,您可以将cmdHistory定义为一个char**指针,并且在不初始化它的情况下,首先设置“cmdHistory[20]=NULL”;在执行cmdHistory[20]之前,需要初始化和分配cmdHistory。空终止具有已知长度的数组也没有意义。