-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
103 lines (93 loc) · 1.74 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "monty.h"
/**
* opcode_finder - find opcode
* @stack: stack pointer
* @opcode: user input opcode
* @line_number: line number
* Return: Always 1 (Success) or stderr
**/
int find_opcode(stack_t **stack, char *opcode, int line_number)
{
instruction_t opcodes[] = {
{"pall", pall},
{"pop", pop},
{"swap", swap},
{"pint", pint},
{NULL, NULL}
};
int i;
for (i = 0; opcodes[i].opcode; i++)
{
if (strcmp(opcode, opcodes[i].opcode) == 0)
{
(opcodes[i].f)(stack, line_number);
return (EXIT_SUCCESS);
}
}
fprintf(stderr, "L%d: unknown instruction %s\n", line_number, opcode);
exit(EXIT_FAILURE);
}
/**
* main - Process Monty byte codes from a file passed in as an argument
* @argc: size of argv
* @argv: A double pointer contain the arguments
* Return: EXIT_SUCCESS if no errors or EXIT_FAILURE
**/
int main(__attribute__((unused)) int argc, char const *argv[])
{
FILE *mf;
char *buff = NULL, *opcode, *n;
size_t lol = 0;
int line_number = 0;
stack_t *stack = NULL, *current;
if (argc != 2)
{
fprintf(stderr, "USAGE: monty file\n");
return (EXIT_FAILURE);
}
mf = fopen(argv[1], "r");
if (mf == NULL)
{
fprintf(stderr, "Error: can't open file %s\n", argv[1]);
exit(1);
}
while ((getline(&buff, &lol, mf)) != -1)
{
line_number++;
opcode = strtok(buff, DELIMATOR);
if (opcode == NULL || opcode[0] == '#')
continue;
if (!strcmp(opcode, "nop"))
continue;
else if (!strcmp(opcode, "push"))
{
n = strtok(NULL, DELIMATOR);
push(&stack, n, line_number);
}
else
find_opcode(&stack, opcode, line_number);
}
fclose(mf);
free(buff);
while (stack != NULL)
{
current = stack;
stack = stack->next;
free(current);
}
return (0);
}
/**
* free_stack - fff
* @stack: fff
**/
void free_stack(stack_t *stack)
{
stack_t *next;
while (stack != NULL)
{
next = stack->next;
free(stack);
stack = next;
}
}