forked from fatimasgit/holbertonschool-monty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
98 lines (91 loc) · 1.76 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
#include "monty.h"
/**
* main - main function
* @argc: argument counts
* @argv: arguments passed
* Return: success
*/
int main(int argc, char **argv)
{
FILE *file;
char *buff = NULL, *string;
size_t s = 0;
unsigned int linenum = 1;
stack_t *stk = NULL;
variables.check = 0;
if (argc != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
file = fopen(argv[1], "r");
if (file == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
while (getline(&buff, &s, file) != -1)
{
if (*buff != '\n')
{
string = strtok(buff, "\n");
_tokenizer(string, &stk, linenum);
}
linenum++;
}
fclose(file);
free(buff);
if (stk != NULL)
free_stk(&stk, linenum);
return (EXIT_SUCCESS);
}
/**
* _tokenizer - function to tokenize strings and commands
* @string: string to be tokenized
* @stk: pointer to the stack
* @linenum: line numbers
* Return: void
*/
void _tokenizer(char *string, stack_t **stk, unsigned int linenum)
{
char *token;
char *tokens;
token = strtok(string, " \n");
if (token == NULL || *token == ' ' || *token == '\n' || *token == '#')
return;
if (strcmp(token, "push") == 0)
{
tokens = token;
token = strtok(NULL, " ");
if (!check_digit(token))
{
dprintf(2, "L%d: usage: push integer\n", linenum);
free_stk(stk, linenum);
exit(EXIT_FAILURE);
}
variables.holder = atoi(token);
_ops(tokens, stk, linenum);
}
else
_ops(token, stk, linenum);
}
/**
* check_digit - checks if string is a number
* @token: string to check
* Return: 1 if number, 0 if not
*/
int check_digit(char *token)
{
if (token == NULL)
return (0);
if (*token == '-')
token++;
while (*token != '\0')
{
if (!isdigit(*token))
return (0);
token++;
}
token++;
return (1);
}