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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s datafile\n", *argv);
return 1;
}
FILE *fd = fopen(argv[1], "r");
if (fd == NULL) {
perror(argv[1]);
return 1;
}
int coords[2] = {0, 0};
int aim = 0;
char *buf = NULL;
size_t buflen = 0;
while (getline(&buf, &buflen, fd) != -1) {
int param = atoi(strchr(buf, ' ') + 1);
switch (buf[0]) {
case 'f': /* forward */
coords[0] += param;
coords[1] += param * aim;
break;
case 'u': /* up */
aim -= param;
break;
case 'd': /* down */
aim += param;
break;
}
}
free(buf);
printf("final coords: %d %d\n", coords[0], coords[1]);
printf("product: %d\n", coords[0] * coords[1]);
if (fclose(fd) == EOF) {
perror("fclose");
return 1;
}
return 0;
}
|