-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
103 lines (91 loc) · 1.69 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"
global_t vglo;
/**
* free_vglo - frees the global variables
*
* Return: no return
*/
void free_vglo(void)
{
free_dlistint(vglo.head);
free(vglo.buffer);
fclose(vglo.fd);
}
/**
* start_vglo - initializes the global variables
*
* @fd: file descriptor
* Return: no return
*/
void start_vglo(FILE *fd)
{
vglo.lifo = 1;
vglo.cont = 1;
vglo.arg = NULL;
vglo.head = NULL;
vglo.fd = fd;
vglo.buffer = NULL;
}
/**
* check_input - checks if the file exists and if the file can
* be opened
*
* @argc: argument count
* @argv: argument vector
* Return: file struct
*/
FILE *check_input(int argc, char *argv[])
{
FILE *fd;
if (argc == 1 || argc > 2)
{
dprintf(2, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fd = fopen(argv[1], "r");
if (fd == NULL)
{
dprintf(2, "Error: Can't open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
return (fd);
}
/**
* main - Entry point
*
* @argc: argument count
* @argv: argument vector
* Return: 0 on success
*/
int main(int argc, char *argv[])
{
void (*f)(stack_t **stack, unsigned int line_number);
FILE *fd;
size_t size = 256;
ssize_t nlines = 0;
char *lines[2] = {NULL, NULL};
fd = check_input(argc, argv);
start_vglo(fd);
nlines = getline(&vglo.buffer, &size, fd);
while (nlines != -1)
{
lines[0] = _strtoky(vglo.buffer, " \t\n");
if (lines[0] && lines[0][0] != '#')
{
f = get_opcodes(lines[0]);
if (!f)
{
dprintf(2, "L%u: ", vglo.cont);
dprintf(2, "unknown instruction %s\n", lines[0]);
free_vglo();
exit(EXIT_FAILURE);
}
vglo.arg = _strtoky(NULL, " \t\n");
f(&vglo.head, vglo.cont);
}
nlines = getline(&vglo.buffer, &size, fd);
vglo.cont++;
}
free_vglo();
return (0);
}