diff --git a/day1/day1 b/day1/day1 new file mode 100755 index 0000000..bec4242 Binary files /dev/null and b/day1/day1 differ diff --git a/day1/day1.c b/day1/day1.c index 28d3f81..83b5f6e 100644 --- a/day1/day1.c +++ b/day1/day1.c @@ -1,25 +1,19 @@ -#include #include +#include #include +#include "../libs/buffered_reader.h" + int main(int argc, char *argv[]) { - // Define input file - FILE *file; - file = fopen(argv[1], "r"); + filelines *lines = flines(argv[1]); - //Define loop things - bool loop = true; - char *buffer; - size_t bufsize = 128; - size_t characters; + if (lines == NULL) { + printf("Failed to read file"); + exit(1); + } - //loop over file - if (file) { - while (loop) { - buffer = (char *)malloc(bufsize * sizeof(char)); - characters = getline(&buffer, &bufsize, file); - - } + for (int i = 0; i < lines->size; i++) { + printf("%s\n", get(lines, i)); } return 0; diff --git a/day1/input.txt b/day1/input.txt new file mode 100644 index 0000000..83db48f --- /dev/null +++ b/day1/input.txt @@ -0,0 +1,3 @@ +line1 +line2 +line3 diff --git a/libs/buffered_reader.c b/libs/buffered_reader.c index 6ee41ba..51698b8 100644 --- a/libs/buffered_reader.c +++ b/libs/buffered_reader.c @@ -19,12 +19,30 @@ filelines* flines(const char* filename) { filelines *lines; initFileLines(&lines); + int c; //loop over file if (file) { while (loop) { buffer = (char *)malloc(bufsize * sizeof(char)); - characters = getline(&buffer, &bufsize, file); + int i = 0; + while((c = getc(file)) != EOF) { + if (c == '\n' || i == bufsize) { + printf("breaking\n"); + break; + } + + //TODO: resize string if input is too big + printf("Adding %d\n", c); + buffer[i] = c; + i += 1; + } + if (i > 0){ + insert(lines, buffer); + } + if (c == EOF) { + break; + } } } @@ -42,9 +60,8 @@ void initFileLines(filelines **flines_ptr) { flines->size = 0; flines->capacity = STARTING_SIZE; flines->lines = (char**)malloc(STARTING_SIZE * sizeof(char*)); - flines = (filelines*)malloc(sizeof(filelines)); if (!flines->lines) { - printf("Failed to allocate memory for filelines\n"); + printf("Failed to allocate memory for lines in filelines\n"); exit(1); } @@ -62,8 +79,8 @@ void insert(filelines *flines_ptr, char *str){ return; } } - flines_ptr->size += 1; flines_ptr->lines[flines_ptr->size] = str; + flines_ptr->size += 1; } char* get(filelines *flines_ptr, int index) { diff --git a/libs/buffered_reader.h b/libs/buffered_reader.h index cacc70e..e56984f 100644 --- a/libs/buffered_reader.h +++ b/libs/buffered_reader.h @@ -16,6 +16,6 @@ filelines* flines(const char* filename); void initFileLines(filelines** flines_ptr); void insert(filelines* flines_ptr, char* str); char* get(filelines* flines_ptr, int index); -void free(filelines* flines_ptr); +void freeLines(filelines* flines_ptr); #endif