[英]making a simple history function in C shell program
該命令將列出最近使用過的命令(最多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");
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]);
}
// 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.