在C shell程序中制作一个简单的历史函数

在C shell程序中制作一个简单的历史函数,c,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]); print

此命令将列出最近使用的命令(最多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");
最大尺寸为100码
字符历史[最大大小];
int size=0;
//历史函数
对于(int p=1;p
字符历史记录[最大大小]
保留字符。如果您的命令不止一个字符,请使用
char*history[MAX\u HIS\u 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]);

}
//您需要一个字符串数组。因为每个字符串都是不同的
//长度,使用malloc分配它们(稍后释放它们)
//您还需要使用循环缓冲区:
结构历史{
字符**行;
int max_大小;
int开始;
}
无效初始化_历史(结构历史*历史,整数大小){
历史->最大尺寸=尺寸;
历史->行=malloc(大小*sizeof(字符*);
int i;
对于(i=0;i行[i]=NULL;
}
}
void add_to_history(结构历史*历史,字符*命令行){
if(历史记录->行[历史记录->开始]!=NULL){
自由(历史->行[历史->开始]);
}
历史->行[历史->开始]=命令行;
历史->开始=(历史->开始+1)%history->max\u size;
}
作废打印历史记录(结构历史记录*历史记录){
int i;
int begin=历史->开始;
对于(i=0;i行[开始]!=NULL){
printf(“%s\n”,历史->行[开始];
}
++开始;
如果(开始>=历史->最大大小){
开始=0;
}
}
}
无效自由_历史(结构历史*历史){
int i;
对于(i=0;i行[i]!=NULL){
自由(历史->行[i]);
}
}
自由(历史->行);
}

为数组指定一些值!应该在解析我的代码之前调用newCmd吗?这取决于您的代码。如果要保持输入的状态,可以在输入之前执行。但是,如果要首先验证命令或仅保留命令的一部分,则在解析命令后,可以调用
newCmd(char*validatedCmd)
函数。
// 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);
}