-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
101 lines (88 loc) · 2.14 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
#include "monty.h"
File_content *file_ptr = NULL;
/**
* count_arguments - counts the number of CLI arguments passed
* @argc: check if the arguments is == 2
*/
void count_arguments(int argc)
{
if (argc != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
}
/**
* handle_file_opening - checks if the file can open and reads it
* @name_of_file: name of file to be opened
* @file: a FILE pointer
*/
void handle_file_opening(const char *name_of_file, FILE **file)
{
*file = fopen(name_of_file, "r");
if (*file == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", name_of_file);
exit(EXIT_FAILURE);
}
}
/**
* allocated_file_content - it allocates memory to the file_contect struct
* Return: a pointer to the address of the memory created
*/
File_content *allocated_file_content(void)
{
file_ptr = (File_content *)malloc(sizeof(File_content));
if (file_ptr == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
file_ptr->file = NULL;
file_ptr->line = NULL;
file_ptr->line_number = 0;
file_ptr->num_tokens = 0;
file_ptr->tokens = NULL;
file_ptr->head = NULL;
file_ptr->opcode_instruction = (instruction_t *)
malloc(sizeof(instruction_t));
if (file_ptr->opcode_instruction == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
file_ptr->opcode_instruction->opcode = NULL;
file_ptr->opcode_instruction->f = NULL;
/* Initalize other properties of the struct here*/
return (file_ptr);
}
/**
* main - entry point of the monty interpreter
* @argc: the argument count
* @argv: argument vector
* Return: 0 on sucess
*/
int main(int argc, char **argv)
{
size_t line_size = 0;
count_arguments(argc);
file_ptr = allocated_file_content();
handle_file_opening(argv[1], &(file_ptr->file));
if (file_ptr->file == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", argv[1]);
free_file_ptr();
exit(EXIT_FAILURE);
}
while (getline(&file_ptr->line, &line_size, file_ptr->file) != -1)
{
file_ptr->line_number = file_ptr->line_number + 1;
parse_line();
get_opcode_func();
execute_opcode();
free_tokens();
}
fclose_file();
free_file_ptr();
return (0);
}