Created
December 4, 2019 12:21
-
-
Save fkaa/5b75cbd63bf38fb2a3a795174f7dfd6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
enum Result | |
{ | |
CantReadFile, | |
BadInput, | |
Success | |
}; | |
enum Result calculate_fuel_requirements(int *req) | |
{ | |
int read_ret = 0, mass = 0, total_fuel = 0; | |
FILE *f = NULL; | |
errno_t ferr; | |
ferr = fopen_s(&f, "input", "r"); | |
if (ferr != 0 || !f) | |
{ | |
return CantReadFile; | |
} | |
while (read_ret != EOF) | |
{ | |
mass = 0; | |
read_ret = fscanf_s(f, "%d\n", &mass, sizeof(mass)); | |
if (read_ret == EOF) | |
{ | |
break; | |
} | |
else if (read_ret == 0) | |
{ | |
goto parse_error; | |
} | |
total_fuel += mass / 3 - 2; | |
} | |
*req = total_fuel; | |
fclose(f); | |
return Success; | |
parse_error: | |
fclose(f); | |
return BadInput; | |
} | |
int main(int argc, char **argv) | |
{ | |
int req = 0; | |
switch (calculate_fuel_requirements(&req)) | |
{ | |
case Success: | |
printf("Requires %d fuel\n", req); | |
return EXIT_SUCCESS; | |
case CantReadFile: | |
printf("Can't read input file\n"); | |
return EXIT_FAILURE; | |
case BadInput: | |
printf("Bad input\n"); | |
default: | |
return EXIT_FAILURE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment