-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
87 lines (78 loc) · 1.48 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
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "monty.h"
/**
* main - monty interperter
* @ac: the number of arguments
* @av: the arguments
* Return: void
*/
int main(int ac, char *av[])
{
stack_t *stack = NULL;
static char *string[1000] = {NULL};
int n = 0;
FILE *fd;
size_t bufsize = 1000;
if (ac != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fd = fopen(av[1], "r");
if (fd == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", av[1]);
exit(EXIT_FAILURE);
}
for (n = 0; getline(&(string[n]), &bufsize, fd) > 0; n++)
;
execute(string, stack);
free_list(string);
fclose(fd);
return (0);
}
/**
* execute - executes opcodes
* @string: contents of file
* @stack: the list
* Return: void
*/
void execute(char *string[], stack_t *stack)
{
int ln, n, i;
instruction_t st[] = {
{"pall", pall},
{"pint", pint},
{"add", add},
{"swap", swap},
{"pop", pop},
{"null", NULL}
};
for (ln = 1, n = 0; string[n + 1]; n++, ln++)
{
if (_strcmp("push", string[n]))
push(&stack, ln, pushint(string[n], ln));
else if (_strcmp("nop", string[n]))
;
else
{
i = 0;
while (!_strcmp(st[i].opcode, "null"))
{
if (_strcmp(st[i].opcode, string[n]))
{
st[i].f(&stack, ln);
break;
}
i++;
}
if (_strcmp(st[i].opcode, "null") && !_strcmp(string[n], "\n"))
{
fprintf(stderr, "L%u: unknown instruction %s", ln, string[n]);
if (!nlfind(string[n]))
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
}
}
free_stack(stack);
}