Support API to save/load history on file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
diff --git a/Makefile b/Makefile
index 5d17057..a285410 100644
--- a/Makefile
+++ b/Makefile
@@ -1,3 +1,5 @@
+linenoise_example: linenoise.h linenoise.c
+
linenoise_example: linenoise.c example.c
$(CC) -Wall -W -Os -g -o linenoise_example linenoise.c example.c
diff --git a/example.c b/example.c
index 22e5188..b3f9e9e 100644
--- a/example.c
+++ b/example.c
@@ -5,10 +5,12 @@
int main(void) {
char *line;
+ linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
while((line = linenoise("hello> ")) != NULL) {
if (line[0] != '\0') {
printf("echo: '%s'\n", line);
linenoiseHistoryAdd(line);
+ linenoiseHistorySave("history.txt"); /* Save every new entry */
}
free(line);
}
diff --git a/linenoise.c b/linenoise.c
index 6a1aa60..b7c6b73 100644
--- a/linenoise.c
+++ b/linenoise.c
@@ -431,3 +431,39 @@ int linenoiseHistorySetMaxLen(int len) {
history_len = history_max_len;
return 1;
}
+
+/* Save the history in the specified file. On success 0 is returned
+ * otherwise -1 is returned. */
+int linenoiseHistorySave(char *filename) {
+ FILE *fp = fopen(filename,"w");
+ int j;
+
+ if (fp == NULL) return -1;
+ for (j = 0; j < history_len; j++)
+ fprintf(fp,"%s\n",history[j]);
+ fclose(fp);
+ return 0;
+}
+
+/* Load the history from the specified file. If the file does not exist
+ * zero is returned and no operation is performed.
+ *
+ * If the file exists and the operation succeeded 0 is returned, otherwise
+ * on error -1 is returned. */
+int linenoiseHistoryLoad(char *filename) {
+ FILE *fp = fopen(filename,"r");
+ char buf[LINENOISE_MAX_LINE];
+
+ if (fp == NULL) return -1;
+
+ while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
+ char *p;
+
+ p = strchr(buf,'\r');
+ if (!p) p = strchr(buf,'\n');
+ if (p) *p = '\0';
+ linenoiseHistoryAdd(buf);
+ }
+ fclose(fp);
+ return 0;
+}
diff --git a/linenoise.h b/linenoise.h
index 57bf9d1..0d76aea 100644
--- a/linenoise.h
+++ b/linenoise.h
@@ -37,5 +37,7 @@
char *linenoise(const char *prompt);
int linenoiseHistoryAdd(const char *line);
int linenoiseHistorySetMaxLen(int len);
+int linenoiseHistorySave(char *filename);
+int linenoiseHistoryLoad(char *filename);
#endif /* __LINENOISE_H */