diff options
Diffstat (limited to 'src/filehandler.c')
| -rw-r--r-- | src/filehandler.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/filehandler.c b/src/filehandler.c new file mode 100644 index 0000000..f42a22b --- /dev/null +++ b/src/filehandler.c @@ -0,0 +1,62 @@ +#include <filehandler.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static size_t +size(filehandler_t *fh) +{ + unsigned int current = ftell(fh->f); + + fseek(fh->f, 0, SEEK_END); + unsigned int s = ftell(fh->f); + + fseek(fh->f, current, SEEK_SET); + return s; +} + +void +filehandler_init(filehandler_t *fh, char *path) +{ + fh->f = NULL; + fh->buffer = NULL; + + fh->path = (char *) calloc(strlen(path) + 1, sizeof(char)); + strcpy(fh->path, path); +} + +bool +filehandler_open(filehandler_t *fh) +{ + fh->f = fopen(fh->path, "r"); + if (fh->f == NULL) { + printf("Unable to open %s\n", fh->path); + return false; + } + + return true; +} + +char * +filehandler_read(filehandler_t *fh) +{ + fseek(fh->f, 0, SEEK_SET); + + size_t buf_size = size(fh); + + fh->buffer = (char *) calloc(buf_size, sizeof(char)); + int bytesread = fread(fh->buffer, sizeof(char), buf_size, fh->f); + + if (bytesread < 0) { + return NULL; + } + return fh->buffer; +} + +void +filehandler_close(filehandler_t *fh) +{ + fclose(fh->f); + free(fh->buffer); +} |
