advent-of-c-ode/libs/buffered_reader.c

106 lines
2.1 KiB
C
Raw Permalink Normal View History

2023-12-02 21:32:40 -05:00
#include "buffered_reader.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
filelines* flines(const char* filename) {
// Define input file
FILE *file;
file = fopen(filename, "r");
//Define loop things
bool loop = true;
char *buffer;
2023-12-05 00:07:15 -05:00
size_t bufsize = 8;
2023-12-02 21:32:40 -05:00
size_t characters;
filelines *lines;
initFileLines(&lines);
2023-12-04 22:46:02 -05:00
int c;
2023-12-02 21:32:40 -05:00
//loop over file
if (file) {
while (loop) {
2023-12-05 00:07:15 -05:00
int size = bufsize;
buffer = (char *)malloc(size * sizeof(char));
2023-12-02 21:32:40 -05:00
2023-12-04 22:46:02 -05:00
int i = 0;
while((c = getc(file)) != EOF) {
2023-12-05 00:07:15 -05:00
if (c == '\n') {
2023-12-04 22:46:02 -05:00
break;
}
2023-12-05 00:07:15 -05:00
if (i == size) {
size <<= 1;
buffer = (char*)realloc(buffer, size * sizeof(char));
}
2023-12-04 22:46:02 -05:00
//TODO: resize string if input is too big
buffer[i] = c;
i += 1;
}
if (i > 0){
2023-12-05 00:07:15 -05:00
if (i == size) {
buffer = (char*)realloc(buffer, size * sizeof(char) + 1);
}
buffer[i] = '\0';
2023-12-04 22:46:02 -05:00
insert(lines, buffer);
}
if (c == EOF) {
break;
}
2023-12-02 21:32:40 -05:00
}
}
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) {
2023-12-04 22:46:02 -05:00
printf("Failed to allocate memory for lines in filelines\n");
2023-12-02 21:32:40 -05:00
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;
2023-12-04 22:46:02 -05:00
flines_ptr->size += 1;
2023-12-02 21:32:40 -05:00
}
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);
}