create buffered reader

This commit is contained in:
Preston Baxter 2023-12-04 21:46:02 -06:00
parent 3af6121255
commit 4217ded01b
5 changed files with 35 additions and 21 deletions

BIN
day1/day1 Executable file

Binary file not shown.

View File

@ -1,25 +1,19 @@
#include <stdio.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#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;

3
day1/input.txt Normal file
View File

@ -0,0 +1,3 @@
line1
line2
line3

View File

@ -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) {

View File

@ -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