Question

I have to implement the hist command includng !k and !!

The 2 functions:

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

Any help would be appreciated.

Was it helpful?

Solution

For a C solution

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

should be

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

Be sure to free it when you are done with it.

OTHER TIPS

Here is a link to a good example of linked lists http://www.thegeekstuff.com/2012/08/c-linked-list-example/

you would just replace int val with your char*. but your method will work if you fix one line of code

your bug is right here

     char current_command[COMMAND_SIZE];

current_command goes out of scope after the else statement is over and thus gets deleted. instead do this

     char * current_command = new char[COMMAND_SIZE];

then your code should work

You might want to use (like bash does) the GNU readline library. You'll then use the readline function to read interactively a line from the terminal and add_history to add a line to the history list (and you could also customize the autocompletion)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top