-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_functions.c
88 lines (76 loc) · 1.66 KB
/
file_functions.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
#include "monty.h"
/**
* openfile - test existance of the file and open it for read.
*
* @filename: filename to open it.
*
* Return: nothing.
*/
int openfile(char *filename)
{
FILE *fd = fopen(filename, "r");
int mode = 0;
if (filename == NULL || fd == NULL)
{
error(2, filename);
exit(EXIT_FAILURE);
}
mode = readfile(fd);
fclose(fd);
return (mode);
}
/**
* readfile - read a file.
*
* @fd: pointer to file descriptor.
*
* Return: (1) success read, (0) unsuccess read.
*/
int readfile(FILE *fd)
{
int line_number, mode = 0;
char *buffer = NULL;
size_t len = 0;
for (line_number = 1; (int) getline(&buffer, &len, fd) != -1; line_number++)
{
mode = parse_line(buffer, line_number, mode);
if (mode == 3)
break;
}
free(buffer);
free_nodes();
return (mode);
}
/**
* parse_line - extract op_code and value from the line.
*
* @buffer: the line i will parse.
* @line_number: if errors occured i'll return line number with the error.
* @mode: (0) for stack, (1) for queue.
*
* Return: (0) for stack, (1) for queue.
*/
int parse_line(char *buffer, int line_number, int mode)
{
char *operation_code, *value, *token;
const char *delimiter = "\n ";
operation_func func;
operation_code = strtok(buffer, delimiter);
if (operation_code == NULL)
return (mode);
value = strtok(NULL, delimiter);
while ((token = strtok(NULL, delimiter)))
{
if (strcmp(token, "stack") == 0)
mode = 0;
if (strcmp(token, "queue") == 0)
mode = 1;
token = strtok(NULL, delimiter);
}
func = select_operation_func(operation_code, line_number);
if (func != NULL)
call_func(func, operation_code, value, line_number, &mode);
else
mode = 3;
return (mode);
}