#include "buffered_reader.h" #include #include #include #include filelines* flines(const char* filename) { // Define input file FILE *file; file = fopen(filename, "r"); //Define loop things bool loop = true; char *buffer; size_t bufsize = 8; size_t characters; filelines *lines; initFileLines(&lines); int c; //loop over file if (file) { while (loop) { int size = bufsize; buffer = (char *)malloc(size * sizeof(char)); int i = 0; while((c = getc(file)) != EOF) { if (c == '\n') { break; } if (i == size) { size <<= 1; buffer = (char*)realloc(buffer, size * sizeof(char)); } //TODO: resize string if input is too big buffer[i] = c; i += 1; } if (i > 0){ if (i == size) { buffer = (char*)realloc(buffer, size * sizeof(char) + 1); } buffer[i] = '\0'; insert(lines, buffer); } if (c == EOF) { break; } } } return lines; } void initFileLines(filelines **flines_ptr) { filelines *flines; flines = (filelines*)malloc(sizeof(filelines)); if (!flines) { printf("Failed to allocate memory for filelines\n"); exit(1); } flines->size = 0; flines->capacity = STARTING_SIZE; flines->lines = (char**)malloc(STARTING_SIZE * sizeof(char*)); if (!flines->lines) { printf("Failed to allocate memory for lines in filelines\n"); exit(1); } *flines_ptr = flines; } //inserts copy of string into array void insert(filelines *flines_ptr, char *str){ if (flines_ptr->size == flines_ptr->capacity) { char **temp = flines_ptr->lines; flines_ptr->capacity <<= 1; flines_ptr->lines = realloc(flines_ptr->lines, flines_ptr->capacity * sizeof(char*)); if (!flines_ptr->lines) { printf("Out of mem\n"); return; } } flines_ptr->lines[flines_ptr->size] = str; flines_ptr->size += 1; } char* get(filelines *flines_ptr, int index) { if(index >=flines_ptr->size) { printf("index out of bounds"); return NULL; } return flines_ptr->lines[index]; } void freeLines(filelines* flines_ptr){ free(flines_ptr->lines); free(flines_ptr); }