diff --git a/examples/cli.c b/examples/cli.c index c1aa002..3b4673d 100644 --- a/examples/cli.c +++ b/examples/cli.c @@ -22,6 +22,8 @@ #include "editline.h" #include +#define HISTORY "/tmp/.cli-history" + static char *list[] = { "foo ", "bar ", "bsd ", "cli ", "ls ", "cd ", "malloc ", "tee ", NULL }; @@ -86,11 +88,14 @@ int main(int ac __attribute__ ((unused)), char *av[] __attribute__ ((unused))) /* Setup callbacks */ rl_set_complete_func(&my_rl_complete); rl_set_list_possib_func(&my_rl_list_possib); + read_history(HISTORY); while ((line = readline(prompt)) != NULL) { printf("\t\t\t|%s|\n", line); free(line); } + write_history(HISTORY); + return 0; } diff --git a/include/editline.h b/include/editline.h index a27d7b5..f85bd99 100644 --- a/include/editline.h +++ b/include/editline.h @@ -56,4 +56,7 @@ extern void rl_reset_terminal(char *p); extern char *readline(const char *prompt); extern void add_history(const char *line); +extern int read_history(const char *filename); +extern int write_history(const char *filename); + #endif /* __EDITLINE_H__ */ diff --git a/src/editline.c b/src/editline.c index 266b267..f95a2b6 100644 --- a/src/editline.c +++ b/src/editline.c @@ -1155,6 +1155,50 @@ void add_history(const char *p) hist_add(p); } + + +int read_history(const char *filename) +{ + FILE *fp; + char buf[SCREEN_INC]; + + hist_alloc(); + fp = fopen(filename, "r"); + if (fp) { + H.Size = 0; + while (H.Size < el_hist_size) { + if (!fgets(buf, SCREEN_INC, fp)) + break; + buf[strlen(buf) - 1] = 0; /* Remove '\n' */ + add_history(buf); + } + fclose(fp); + + return 0; + } + + return errno; +} + +int write_history(const char *filename) +{ + FILE *fp; + + hist_alloc(); + fp = fopen(filename, "w"); + if (fp) { + int i = 0; + + while (i < H.Size) { + fprintf(fp, "%s\n", H.Lines[i++]); + } + fclose(fp); + + return 0; + } + + return errno; +} /*