Add cstuff_file_get_lines function

This commit is contained in:
Ilja Kartašov 2019-07-17 22:53:55 +02:00
parent 4ba00ca17a
commit 93234df78d
2 changed files with 62 additions and 0 deletions

56
file.c
View File

@ -83,3 +83,59 @@ cstuff_file_move(const char *src, const char *dest)
return rc; 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;
}

6
file.h
View File

@ -20,6 +20,9 @@
#include "retcode.h" #include "retcode.h"
typedef int
(*CStuffFileGetLine)(char *line, ssize_t length, void *ctx);
bool bool
cstuff_file_exists(const char *file); cstuff_file_exists(const char *file);
@ -32,4 +35,7 @@ CStuffRetcode
cstuff_file_move(const char *src, const char *dest); 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 */ #endif /* !FILE_H */