【问题标题】:History feature in a shellshell 中的历史功能
【发布时间】:2013-11-21 14:28:20
【问题描述】:

我必须执行 hist 命令,包括 !k 和 !!

两个功能:

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]);
  }
}

任何帮助将不胜感激。

【问题讨论】:

  • 为什么这被标记为 C++?

标签: c linux shell unix history


【解决方案1】:

这里是链接列表的一个很好的例子http://www.thegeekstuff.com/2012/08/c-linked-list-example/

您只需将 int val 替换为您的 char*。 但是,如果您修复一行代码,您的方法将起作用

你的错误就在这里

     char current_command[COMMAND_SIZE];

current_command 在 else 语句结束后超出范围,因此被删除。而是这样做

     char * current_command = new char[COMMAND_SIZE];

那么你的代码应该可以工作

【讨论】:

  • 糟糕,我刚刚看到您发布(C 代码)的方式是 C++ 方式。如果您严格使用 c,则必须使用 maloc 而不是 new,但我不知道它的确切语法,抱歉
  • 链表的优点是不会耗尽空间(不会耗尽计算机上的内存),但让它工作起来要简单得多我添加了一个指向链表的链接很好的例子
  • @CharlieBurns 方法比调用maloc好
【解决方案2】:

对于 C 解决方案

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

应该是

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

完成后一定要释放它。

【讨论】:

  • 不,以前您将字符串保存在堆栈中,一旦块完成,该字符串就会消失。 strdup() 将字符串放在它永远存在的堆上,直到你释放它。你的版本不正确,这个版本应该可以解决这个问题。
【解决方案3】:

您可能想要使用(就像bash 一样)GNU readline 库。然后,您将使用readline 函数从终端交互读取一行,并使用add_history 将一行添加到历史列表(您也可以customize the autocompletion

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2021-02-07
    • 2010-11-06
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多