From 285a9b274978349cfd762a6cd6e6aa666909ec5e Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Mon, 17 Dec 2018 11:21:12 +0100 Subject: fileio: add new safe_fgetc() helper call We have very similar code whenever we call fgetc() in place, let's replae it by a common implementation. --- src/basic/fileio.c | 27 +++++++++++++++++++++++++++ src/basic/fileio.h | 2 ++ 2 files changed, 29 insertions(+) (limited to 'src') diff --git a/src/basic/fileio.c b/src/basic/fileio.c index b22fcd0302..b07f4f92a9 100644 --- a/src/basic/fileio.c +++ b/src/basic/fileio.c @@ -828,3 +828,30 @@ int read_line(FILE *f, size_t limit, char **ret) { return (int) count; } + +int safe_fgetc(FILE *f, char *ret) { + int k; + + assert(f); + + /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and + * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc() + * has. */ + + errno = 0; + k = fgetc(f); + if (k == EOF) { + if (ferror(f)) + return errno > 0 ? -errno : -EIO; + + if (ret) + *ret = 0; + + return 0; + } + + if (ret) + *ret = k; + + return 1; +} diff --git a/src/basic/fileio.h b/src/basic/fileio.h index 8480246072..300d060cea 100644 --- a/src/basic/fileio.h +++ b/src/basic/fileio.h @@ -64,3 +64,5 @@ int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) int read_nul_string(FILE *f, char **ret); int read_line(FILE *f, size_t limit, char **ret); + +int safe_fgetc(FILE *f, char *ret); -- cgit v1.2.3