#include #include #include int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: ./depth \n"); exit(EXIT_FAILURE); } FILE *fp; char *buffer; ssize_t read; size_t len = 0; fp = fopen(argv[1], "r"); if (fp == NULL) { perror("fopen"); exit(EXIT_FAILURE); } int scalar; char *way; int h_pos = 0, depth = 0, aim = 0; while ((read = getline(&buffer, &len, fp)) != -1) { sscanf(buffer, "%s %d", way, &scalar); // printf("READ: <%s>, <%d>\n", way, scalar); if (strncmp(way, "forward", strlen("forward")) == 0) { // printf("GOING FORWARD\n"); h_pos += scalar; depth += aim * scalar; } else if (strncmp(way, "down", strlen("forward")) == 0) { aim += scalar; } else { /* up */ aim -= scalar; } } printf("%d\n", depth * h_pos); return 0; }