在C shell程序中创建一个简单的历史函数

时间:2014-03-09 23:04:11

标签: c

此命令将列出最近使用过的命令(最多100个)。最近的将是最底层的。需要一些建议从哪里开始。我知道我确实需要一个for循环来打印历史记录。一个提示是2D阵列,但我不熟悉那些。

  MAX_HIS_SIZE 100
  char history[MAX_HIS_SIZE]; 
  int size = 0; 

   //history function
   for(int p =1; p < size; p++)
   printf(" %s ",history[p]);
   printf("\n");

2 个答案:

答案 0 :(得分:1)

char history[MAX_HIS_SIZE]保留字符。如果您的命令不仅仅是一个字符,请使用char* history[MAX_HIS_SIZE]来访问命令。

如果您想随时访问历史记录,请保留一个指向最后输入命令的索引。每当您想要列出历史记录时,只需从该点开始倒数,直到达到表示列表末尾的NULL。并通过模运算访问索引,这样您就可以倒回并访问最旧的命令,将其替换为最新的命令。

const int MAX_HIS_SIZE = 100;
int last = 0;
char * history[MAX_HIS_SIZE];

 void newCmd(char* cmd) {
     history[last%MAX_HIS_SIZE]=cmd;
     last++;
 }

void listHistory(){
    for(int i = last,  limit = 0; history[i] != NULL && limit != MAX_HIS_SIZE ; i = (i -1)%MAX_HIS_SIZE, limit++)
        printf(" %s ",history[i]);

}

答案 1 :(得分:1)

// you want an array of strings.  since each string is a different
// length, allocate them with malloc (and free them later)
// You also want to use a circular buffer:

struct History {
  char** lines;
  int max_size;
  int begin;
}

void initialize_history(struct History* history, int size) {
  history->max_size = size;
  history->lines = malloc(size * sizeof(char*));
  int i;
  for (i = 0; i < size; ++i) {
    history->lines[i] = NULL;
  }
}

void add_to_history(struct History* history, char* commandline) {
  if (history->lines[history->begin] != NULL) {
    free(history->lines[history->begin]);
  }
  history->lines[history->begin] = commandline;
  history->begin = (history->begin + 1) % history->max_size;
}

void print_history(struct History* history) {
  int i;
  int begin = history->begin;
  for (i = 0; i < size; ++i) {
    if (history->lines[begin] != NULL) {
      printf("%s\n", history->lines[begin]);
    }
    ++begin;
    if (begin >= history->max_size) {
      begin = 0;
    }
  }
}
void free_history(struct History* history) {
  int i;
  for (i = 0; i < size; ++i) {
    if (history->lines[i] != NULL) {
      free(history->lines[i]);
    }
  }
  free(history->lines);
}