Skip to content

Commit

Permalink
Support API to save/load history on file
Browse files Browse the repository at this point in the history
  • Loading branch information
antirez committed Jul 7, 2010
1 parent 28884b5 commit ce84546
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 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

Expand Down
2 changes: 2 additions & 0 deletions example.c
Expand Up @@ -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);
}
Expand Down
36 changes: 36 additions & 0 deletions linenoise.c
Expand Up @@ -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;
}
2 changes: 2 additions & 0 deletions linenoise.h
Expand Up @@ -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 */

0 comments on commit ce84546

Please sign in to comment.