Files
advent-of-code-2023/day_1.c

54 lines
1.2 KiB
C

//
// Created by Lennart on 02/12/2023.
//
#include <stdio.h>
#define ARRAY_LIST_IMPLEMENTATION
#include "array_list.h"
int read_line(FILE *f);
int main() {
FILE *f = fopen("day_1.txt", "r");
if(f == NULL) {
printf("Error! Missing input file!");
return -1;
}
int sum = 0;
while(!feof(f)) {
sum += read_line(f);
}
fclose(f);
printf("Result: %i\n", sum);
return 0;
}
// Read all digits form the next line in a file
int read_line(FILE *f) {
int first = -1, last = 10; // Use first=-1 to detect unset value and last=10 to return 0 (-10 + 10) when no values are set
char buffer[16];
int digit;
do {
fgets(&buffer[0], 16, f);
for(int i = 0; i < 16; i++) {
if(buffer[i] == '\n') {
goto result;
} else if(buffer[i] == 0) {
break; // End of buffer
}
if(sscanf(&buffer[i], "%1d", &digit) == 1) { // NOLINT(*-err34-c)
if(first == -1) {
first = digit;
}
last = digit;
}
}
} while(!feof(f));
result:
return first * 10 + last;
}