shell中的历史记录功能

时间:2013-11-09 16:37:51

标签: c linux shell unix history

我必须实现hist命令,包括!k和!!

2个功能:

void addInHistory(char **history,char *command,int *list_size,int history_capacity)
{
int index=*(list_size);
  if(command[0]!='\n') 
  {
     if(index==history_capacity-1)
     {
        printf("History is full.Deleting commands.");
     }
     else 
     {
         char current_command[COMMAND_SIZE];
         strcpy(current_command,command);
         history[index++]=current_command;       
     }
  }
}
 void printHistory(char **history,int size) 
{
int i;
  for(int i=0;i<=size;i++)
  {
    printf("%d. %s\n",i+1,history[i]);
  }
}

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

以下是指向链接列表http://www.thegeekstuff.com/2012/08/c-linked-list-example/

的良好示例的链接

你只需用你的char *替换int val。 但是如果你修改了一行代码,你的方法就可以了。

你的错误就在这里

     char current_command[COMMAND_SIZE];
在else语句结束后,

current_command超出范围,因此被删除。而是这样做

     char * current_command = new char[COMMAND_SIZE];

然后你的代码应该工作

答案 1 :(得分:0)

对于C解决方案

 char current_command[COMMAND_SIZE];
 strcpy(current_command,command);
 history[index++]=current_command;       

应该是

history[index++]= strdup(command);       

完成后请务必释放它。

答案 2 :(得分:0)

您可能希望使用(bash} GNU readline库。然后,您将使用readline函数以交互方式从终端读取一行,并add_history将一行添加到历史记录列表中(您还可以customize the autocompletion

相关问题