]> git.lizzy.rs Git - linenoise.git/commitdiff
Support API to save/load history on file
authorantirez <antirez@gmail.com>
Wed, 7 Jul 2010 16:26:23 +0000 (18:26 +0200)
committerantirez <antirez@gmail.com>
Wed, 7 Jul 2010 16:26:23 +0000 (18:26 +0200)
Makefile
example.c
linenoise.c
linenoise.h

index 5d1705764ef6a02b28ecf9bf4c499fe49b6cd198..a285410678fb0ee8773cab2eff4fa97531de9714 100644 (file)
--- 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
 
index 22e5188c0d9ffa748e81ec6907c5411de96a55b6..b3f9e9e3517fce46a3a3719b7b3be85e69e4034a 100644 (file)
--- 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);
     }
index 6a1aa6010c723972d4497c429961a588fb43d61c..b7c6b73226098e58758548d37f06058c53800e01 100644 (file)
@@ -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;
+}
index 57bf9d18c1fbc2dc5919a93491603724ae4c6fb3..0d76aea9cb0e89133a4b0a766a4b71e6b7cc9bbb 100644 (file)
@@ -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 */