summaryrefslogtreecommitdiff
path: root/input.c
diff options
context:
space:
mode:
authorVincent Douillet <vincent@vdouillet.fr>2022-12-01 20:35:58 +0100
committerVincent Douillet <vincent@vdouillet.fr>2022-12-01 20:35:58 +0100
commit076d2ca0e0c2f0308373628272a3972241575653 (patch)
treebf60b98fe6b5a569649f41ff93836a9623a93c18 /input.c
day 1
Diffstat (limited to 'input.c')
-rw-r--r--input.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/input.c b/input.c
new file mode 100644
index 0000000..1c72194
--- /dev/null
+++ b/input.c
@@ -0,0 +1,74 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+#include "input.h"
+
+size_t count_lines(FILE* file) {
+ size_t lineCount = 0;
+ char currentChar;
+ // on part du debut
+ // TODO verifier le code de retour
+ fseek(file, 0, SEEK_SET);
+ while((currentChar=fgetc(file)) != EOF) {
+ if(currentChar == '\n')
+ lineCount++;
+ }
+ return lineCount;
+}
+
+void input_int_read(struct input_int* result, char* filename) {
+ // open input file
+ FILE* file=fopen(filename, "r");
+ if(file == NULL)
+ err(1, "cannot open file %s\n", filename);
+ // compute line count
+ result->line_count = count_lines(file);
+ // read each line of the file
+ // TODO check return code
+ fseek(file, 0, SEEK_SET);
+ int current;
+ result->lines = malloc(result->line_count * sizeof(int));
+ for(size_t lineIndex = 0; lineIndex < result->line_count; lineIndex++) {
+ if(fscanf(file, "%d", &current) != 1)
+ err(1, "parsing error line %ld\n", lineIndex);
+
+ result->lines[lineIndex] = current;
+ }
+
+ // close file
+ fclose(file);
+}
+
+void input_str_read(struct input_str* result, char* filename) {
+ // open input file
+ FILE* file=fopen(filename, "r");
+ if(file == NULL)
+ err(1, "cannot open file %s\n", filename);
+ // compute line count
+ result->line_count = count_lines(file);
+
+ // read each line of the file
+ // TODO check return code
+ fseek(file, 0, SEEK_SET);
+ size_t lineSize = 0;
+ result->lines = malloc(result->line_count * sizeof(char*));
+ for(size_t lineIndex = 0; lineIndex < result->line_count; lineIndex++) {
+ char** dst = &(result->lines[lineIndex]);
+ if(getline(dst, &lineSize, file) < 0)
+ err(1, "read error line %ld\n", lineIndex);
+ }
+
+ fclose(file);
+}
+
+void input_int_free(struct input_int* input) {
+ free(input->lines);
+}
+
+void input_str_free(struct input_str* input) {
+ for(size_t i = 0; i < input->line_count; i++) {
+ free(input->lines[i]);
+ }
+ free(input->lines);
+}