-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.c
121 lines (88 loc) · 2.22 KB
/
parser.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//
// Created by Oliver M Batista on 2019-04-12.
//
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "parser.h"
int invalidValue(int *value) {
if (errno == EINVAL) {
printf("Error: Invalid value for number of rows/columns\n");
return 1;
}
if (errno == ERANGE) {
printf("Error: Row/Column value out of range\n");
return 1;
}
if (*value < MIN_ROWCOL_VALUE) {
printf("Error: Minimum value for rows/columns is 3\n");
return 1;
}
return 0;
}
int extractNumberOfRowsCollumns(char *line, int *row, int *col) {
char *end;
*row = strtoul(line, &end, 10);
if (invalidValue(row)) { return 1; }
*col = strtoul(end, &end, 10);
if (invalidValue(col)) { return 1; }
return 0;
}
int parseFile(int argc, char *argv[], Map **map) {
FILE* mapFile;
char buf[BUFFER_SIZE];
int row = 0;
int col = 0;
if (argc != 2) {
printf("Usage: %s <input_01.map>\n", argv[0]);
return 1;
}
if ((mapFile = fopen(argv[1], "r")) == NULL) {
perror("Error");
return 1;
}
// Read first line to determine allocation size
if (fgets(buf, sizeof(buf), mapFile) != NULL) {
if (extractNumberOfRowsCollumns(buf, &row, &col)) {
fclose(mapFile);
return 1;
}
}
(*map)->row = row;
(*map)->col = col;
// Read map from file, allocating char matrix and save starting point
char ch;
int r = 0;
int c = 0;
int teleportersFound = 0;
(*map)->firstTile = (char *)malloc(row * col * sizeof(char));
while ((ch = fgetc(mapFile)) != EOF) {
if (ch == '\n') {
c = 0;
r++;
} else {
if (ch == '@') {
(*map)->startPoint = (*map)->firstTile + r * col + c;
}
if (ch == 'T') {
switch (teleportersFound) {
case 0:
teleportersFound++;
(*map)->teleporterOne = (*map)->firstTile + r * col + c;
break;
case 1:
teleportersFound++;
(*map)->teleporterTwo = (*map)->firstTile + r * col + c;
break;
default:
printf("ERROR: The maximum number of teleporters allowed is 2");
return 1;
}
}
*(((*map)->firstTile) + r*col + c) = ch;
c++;
}
}
fclose(mapFile);
return 0;
}