Mercurial > hg > index.cgi
comparison lwbasic/input.c @ 23:25a4aef9c5ed
lwbasic: Added basic character input framework
author | lost@l-w.ca |
---|---|
date | Sat, 22 Jan 2011 21:13:09 -0700 |
parents | |
children | 87590f43e76d |
comparison
equal
deleted
inserted
replaced
22:7c35fa8dbc91 | 23:25a4aef9c5ed |
---|---|
1 /* | |
2 input.c | |
3 | |
4 Copyright © 2011 William Astle | |
5 | |
6 This file is part of LWTOOLS. | |
7 | |
8 LWTOOLS is free software: you can redistribute it and/or modify it under the | |
9 terms of the GNU General Public License as published by the Free Software | |
10 Foundation, either version 3 of the License, or (at your option) any later | |
11 version. | |
12 | |
13 This program is distributed in the hope that it will be useful, but WITHOUT | |
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | |
16 more details. | |
17 | |
18 You should have received a copy of the GNU General Public License along with | |
19 this program. If not, see <http://www.gnu.org/licenses/>. | |
20 */ | |
21 | |
22 /* | |
23 handle reading input for the rest of the system | |
24 */ | |
25 | |
26 #include <stdlib.h> | |
27 #include <stdio.h> | |
28 #include <string.h> | |
29 | |
30 #include <lw_alloc.h> | |
31 | |
32 #define __input_c_seen__ | |
33 #include "lwbasic.h" | |
34 | |
35 struct input_state | |
36 { | |
37 FILE *fp; | |
38 int error; | |
39 }; | |
40 | |
41 static void input_init(cstate *state) | |
42 { | |
43 struct input_state *sp; | |
44 | |
45 sp = lw_alloc(sizeof(struct input_state)); | |
46 sp -> error = 0; | |
47 | |
48 if (!(state -> input_file) || strcmp(state -> input_file, "-")) | |
49 { | |
50 sp -> fp = stdin; | |
51 } | |
52 else | |
53 { | |
54 sp -> fp = fopen(state -> input_file, "rb"); | |
55 if (!(sp -> fp)) | |
56 { | |
57 fprintf(stderr, "Cannot open input file\n"); | |
58 exit(1); | |
59 } | |
60 } | |
61 | |
62 state -> input_state = sp; | |
63 } | |
64 | |
65 int input_getchar(cstate *state) | |
66 { | |
67 int r; | |
68 struct input_state *sp; | |
69 | |
70 if (!(state -> input_state)) | |
71 input_init(state); | |
72 sp = state -> input_state; | |
73 | |
74 | |
75 if (sp -> error) | |
76 return -2; | |
77 | |
78 if (feof(sp -> fp)) | |
79 return -1; | |
80 | |
81 r = fgetc(sp -> fp); | |
82 if (r == EOF) | |
83 return -1; | |
84 return r; | |
85 } |