create buffered reader
This commit is contained in:
parent
3af6121255
commit
4217ded01b
26
day1/day1.c
26
day1/day1.c
|
@ -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;
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
line1
|
||||
line2
|
||||
line3
|
|
@ -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) {
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue