diff --git a/file.c b/file.c index cabab79..dd34e45 100644 --- a/file.c +++ b/file.c @@ -83,3 +83,59 @@ cstuff_file_move(const char *src, const char *dest) return rc; } + + +CStuffRetcode +cstuff_file_get_lines(const char *src, CStuffFileGetLine get_line) +{ + FILE *f = NULL; + size_t sz = 256; + char *line; + ssize_t rs; + CStuffRetcode result = CSTUFF_SUCCESS; + + if (!(line = malloc(sz))) + goto e_malloc; + + if (!(f = fopen(src, "r"))) + goto e_syscall; + + while ((rs = getdelim(&line, &sz, '\n', f)) != -1) { + if (!get_line(line, rc)) { + continue; + } else { + goto e_input; + } + } + + switch(errno) { + case 0: + break; + + case ENOMEM: + goto e_malloc; + + default: + goto e_syscall; + } + goto finally; + +e_input: + result = CSTUFF_INPUT_ERROR; + goto finally; + +e_malloc: + result = CSTUFF_MALLOC_ERROR; + goto finally; + +e_syscall: + result = CSTUFF_SYSCALL_ERROR; + goto finally; + +finally: + if (line) + free(line); + if (f) + fclose(f); + return result; +} diff --git a/file.h b/file.h index 28d39fb..4d473e1 100644 --- a/file.h +++ b/file.h @@ -20,6 +20,9 @@ #include "retcode.h" +typedef int +(*CStuffFileGetLine)(char *line, ssize_t length, void *ctx); + bool cstuff_file_exists(const char *file); @@ -32,4 +35,7 @@ CStuffRetcode cstuff_file_move(const char *src, const char *dest); +CStuffRetcode +cstuff_file_get_lines(const char *src, CStuffFileGetLine get_line, void *ctx); + #endif /* !FILE_H */