commit f18ac71ad41773ae5feee74a9c2e2c25855a97b6
parent 53faf8ede208ca33cafabf4346559b2eac484744
Author: bsandro <brian.drosan@gmail.com>
Date: Wed, 1 Dec 2021 23:16:47 +0200
Compatibility fix (fgetln -> fgets)
Diffstat:
2 files changed, 12 insertions(+), 16 deletions(-)
diff --git a/day01/puzzle1.c b/day01/puzzle1.c
@@ -3,6 +3,8 @@
#include <errno.h>
#include <string.h>
+#define MAX_LEN 8
+
int puzzle1(const char *filename) {
FILE *infile = fopen(filename, "r");
if (infile == NULL) {
@@ -10,24 +12,21 @@ int puzzle1(const char *filename) {
return -1;
}
- char *buf = NULL;
- size_t len = 0;
+ char buf[MAX_LEN] = {0};
int prev_depth = -1;
int counter = 0;
- while ((buf = fgetln(infile, &len)) != NULL) {
- if (len == 0) {
- fprintf(stderr, "Error: invalid input line\n");
- counter = -1;
- break;
- }
+ while (fgets(buf, MAX_LEN, infile) != NULL) {
int depth = atoi(buf);
if (prev_depth > -1 && depth > prev_depth) {
++counter;
}
prev_depth = depth;
+ bzero(buf, MAX_LEN);
}
+ // mutiny! ignoring feof/ferror.
+
fclose(infile);
return counter;
}
diff --git a/day01/puzzle2.c b/day01/puzzle2.c
@@ -4,6 +4,8 @@
#include <string.h>
#include <stdbool.h>
+#define MAX_LEN 8
+
void rotate_window(int window[3]) {
int tmp = window[0];
window[0] = window[1];
@@ -30,17 +32,11 @@ int puzzle2(const char *filename) {
return -1;
}
- char *buf = NULL;
- size_t len = 0;
+ char buf[MAX_LEN] = {0};
int window[3] = {0, 0, 0};
int counter = 0;
- while ((buf = fgetln(infile, &len)) != NULL) {
- if (len == 0) {
- fprintf(stderr, "Error: invalid input line\n");
- counter = -1;
- break;
- }
+ while (fgets(buf, MAX_LEN, infile) != NULL) {
int depth = atoi(buf);
int sum_win = sum_window(window);
int sum_new = sum_new_window(window, depth);
@@ -49,6 +45,7 @@ int puzzle2(const char *filename) {
}
rotate_window(window);
window[2] = depth;
+ bzero(buf, MAX_LEN);
}
fclose(infile);