altos/lisp: Add save/restore to ao_lisp_test
[fw/altos] / src / test / ao_lisp_test.c
1 /*
2  * Copyright © 2016 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  */
14
15 #include "ao_lisp.h"
16 #include <stdio.h>
17
18 static FILE *ao_lisp_file;
19 static int newline = 1;
20
21 static char save_file[] = "lisp.image";
22
23 int
24 ao_lisp_os_save(void)
25 {
26         FILE    *save = fopen(save_file, "w");
27
28         if (!save) {
29                 perror(save_file);
30                 return 0;
31         }
32         fwrite(ao_lisp_pool, 1, AO_LISP_POOL_TOTAL, save);
33         fclose(save);
34         return 1;
35 }
36
37 int
38 ao_lisp_os_restore(void)
39 {
40         FILE    *restore = fopen(save_file, "r");
41         size_t  ret;
42
43         if (!restore) {
44                 perror(save_file);
45                 return 0;
46         }
47         ret = fread(ao_lisp_pool, 1, AO_LISP_POOL_TOTAL, restore);
48         fclose(restore);
49         if (ret != AO_LISP_POOL_TOTAL)
50                 return 0;
51         return 1;
52 }
53
54 int
55 ao_lisp_getc(void)
56 {
57         int c;
58
59         if (ao_lisp_file)
60                 return getc(ao_lisp_file);
61
62         if (newline) {
63                 printf("> ");
64                 newline = 0;
65         }
66         c = getchar();
67         if (c == '\n')
68                 newline = 1;
69         return c;
70 }
71
72 int
73 main (int argc, char **argv)
74 {
75         while (*++argv) {
76                 ao_lisp_file = fopen(*argv, "r");
77                 if (!ao_lisp_file) {
78                         perror(*argv);
79                         exit(1);
80                 }
81                 ao_lisp_read_eval_print();
82                 fclose(ao_lisp_file);
83                 ao_lisp_file = NULL;
84         }
85         ao_lisp_read_eval_print();
86 }