-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
73 lines (54 loc) · 1.41 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "interpreter.h"
int repl() {
char buffer[4096] = {0};
so_interpreter interp;
so_interpreter_init(&interp);
printf("> ");
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
if (strcmp(buffer, ".quit\n") == 0)
break;
so_interpreter_run(&interp, buffer);
memset(buffer, 0, sizeof(buffer));
printf("> ");
}
so_interpreter_deinit(&interp);
return 0;
}
int file(const char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "error: could not read file: %s\n", filename);
return -1;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
char *contents = malloc(size + 1);
int nread = fread(contents, sizeof(char), size, fp);
if (nread < size) {
fprintf(stderr, "error: read less than %ld bytes\n", size);
return -1;
}
contents[nread] = '\0';
so_interpreter interp;
so_interpreter_init(&interp);
so_interpreter_run(&interp, contents);
so_interpreter_deinit(&interp);
free(contents);
fclose(fp);
return 0;
}
int main(int argc, char **argv) {
if (argc == 1) {
return repl();
}
if (argc == 2) {
char *filename = argv[1];
return file(filename);
}
fprintf(stderr, "usage: sotest [filename]\n");
return -1;
}