history: History Programming Example

1 
1 2.5 History Programming Example
1 ===============================
1 
1 The following program demonstrates simple use of the GNU History
1 Library.
1 
1      #include <stdio.h>
1      #include <readline/history.h>
1 
1      main (argc, argv)
1           int argc;
1           char **argv;
1      {
1        char line[1024], *t;
1        int len, done = 0;
1 
1        line[0] = 0;
1 
1        using_history ();
1        while (!done)
1          {
1            printf ("history$ ");
1            fflush (stdout);
1            t = fgets (line, sizeof (line) - 1, stdin);
1            if (t && *t)
1              {
1                len = strlen (t);
1                if (t[len - 1] == '\n')
1                  t[len - 1] = '\0';
1              }
1 
1            if (!t)
1              strcpy (line, "quit");
1 
1            if (line[0])
1              {
1                char *expansion;
1                int result;
1 
1                result = history_expand (line, &expansion);
1                if (result)
1                  fprintf (stderr, "%s\n", expansion);
1 
1                if (result < 0 || result == 2)
1                  {
1                    free (expansion);
1                    continue;
1                  }
1 
1                add_history (expansion);
1                strncpy (line, expansion, sizeof (line) - 1);
1                free (expansion);
1              }
1 
1            if (strcmp (line, "quit") == 0)
1              done = 1;
1            else if (strcmp (line, "save") == 0)
1              write_history ("history_file");
1            else if (strcmp (line, "read") == 0)
1              read_history ("history_file");
1            else if (strcmp (line, "list") == 0)
1              {
1                register HIST_ENTRY **the_list;
1                register int i;
1 
1                the_list = history_list ();
1                if (the_list)
1                  for (i = 0; the_list[i]; i++)
1                    printf ("%d: %s\n", i + history_base, the_list[i]->line);
1              }
1            else if (strncmp (line, "delete", 6) == 0)
1              {
1                int which;
1                if ((sscanf (line + 6, "%d", &which)) == 1)
1                  {
1                    HIST_ENTRY *entry = remove_history (which);
1                    if (!entry)
1                      fprintf (stderr, "No such entry %d\n", which);
1                    else
1                      {
1                        free (entry->line);
1                        free (entry);
1                      }
1                  }
1                else
1                  {
1                    fprintf (stderr, "non-numeric arg given to `delete'\n");
1                  }
1              }
1          }
1      }
1