From: Baptiste Daroussin Date: Fri, 10 Feb 2023 10:23:33 +0000 (+0100) Subject: init_file_lines: rework using getline(3) X-Git-Tag: RELEASE_1_4_0b1~188 X-Git-Url: http://git.ipfire.org/gitweb/index.cgi?a=commitdiff_plain;h=ebdb074ee9171afa0a6ffe57732051fc2f8dcc04;p=thirdparty%2Fmlmmj.git init_file_lines: rework using getline(3) --- diff --git a/src/prepstdreply.c b/src/prepstdreply.c index 2dc08332..d72ad8a4 100644 --- a/src/prepstdreply.c +++ b/src/prepstdreply.c @@ -134,9 +134,10 @@ struct memory_lines_state { struct file_lines_state { char *filename; - int fd; + FILE *fp; char truncate; char *line; + size_t linecap; }; @@ -193,7 +194,6 @@ file_lines_state *init_file_lines(const char *filename, char truncate) { file_lines_state *s = xcalloc(1, sizeof(file_lines_state)); s->filename = xstrdup(filename); - s->fd = -1; s->truncate = truncate; return s; } @@ -204,49 +204,37 @@ void rewind_file_lines(void *state) file_lines_state *s = (file_lines_state *)state; if (s == NULL) return; if (s->filename != NULL) { - s->fd = open(s->filename, O_RDONLY); + s->fp = fopen(s->filename, "r"); free(s->filename); s->filename = NULL; } - if (s->fd >= 0) { - if(lseek(s->fd, 0, SEEK_SET) < 0) { - log_error(LOG_ARGS, "Could not seek to start of file"); - close(s->fd); - s->fd = -1; - } - } + if (s->fp != NULL) + rewind(s->fp); } const char *get_file_line(void *state) { file_lines_state *s = (file_lines_state *)state; char *end; - if (s == NULL) return NULL; - if (s->line != NULL) { - free(s->line); - s->line = NULL; - } - if (s->fd >= 0) { - s->line = mygetline(s->fd); - if (s->line == NULL) return NULL; - if (s->truncate != '\0') { - end = strchr(s->line, s->truncate); - if (end == NULL) return NULL; - *end = '\0'; - } else { - chomp(s->line); - } - return s->line; + if (s == NULL) return (NULL); + if (s->fp == NULL) return (NULL); + if (getline(&s->line, &s->linecap, s->fp) <= 0) + return (NULL); + if (s->truncate != '\0') { + end = strchr(s->line, s->truncate); + if (end == NULL) return NULL; + *end = '\0'; + } else { + chomp(s->line); } - return NULL; + return s->line; } - void finish_file_lines(file_lines_state *s) { if (s == NULL) return; if (s->line != NULL) free(s->line); - if (s->fd >= 0) close(s->fd); + if (s->fp != NULL) fclose(s->fp); if (s->filename != NULL) free(s->filename); free(s); } diff --git a/tests/mlmmj.c b/tests/mlmmj.c index 576f3cbd..229d820c 100644 --- a/tests/mlmmj.c +++ b/tests/mlmmj.c @@ -2328,6 +2328,9 @@ ATF_TC_BODY(file_lines, tc) ATF_REQUIRE(get_file_line(s) == NULL); finish_file_lines(s); + s = init_file_lines("file", '\0'); + finish_file_lines(s); + s = init_file_lines("file", '\0'); ATF_REQUIRE(s != NULL); ATF_REQUIRE(get_file_line(s) == NULL); @@ -2336,6 +2339,7 @@ ATF_TC_BODY(file_lines, tc) ATF_REQUIRE_STREQ(get_file_line(s), "line2"); ATF_REQUIRE_STREQ(get_file_line(s), "line3: meh"); ATF_REQUIRE(get_file_line(s) == NULL); + rewind_file_lines(s); finish_file_lines(s); rewind_file_lines(NULL);