aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2018-12-17 11:21:12 +0100
committerLennart Poettering <lennart@poettering.net>2018-12-18 14:55:34 +0100
commit285a9b274978349cfd762a6cd6e6aa666909ec5e (patch)
tree7bd2c166d427ca4582b4348ff7780bc87503bd21 /src
parentMerge pull request #10221 from lucaswerkmeister/bash-completion (diff)
downloadsystemd-285a9b274978349cfd762a6cd6e6aa666909ec5e.tar.gz
systemd-285a9b274978349cfd762a6cd6e6aa666909ec5e.tar.bz2
systemd-285a9b274978349cfd762a6cd6e6aa666909ec5e.zip
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.
Diffstat (limited to 'src')
-rw-r--r--src/basic/fileio.c27
-rw-r--r--src/basic/fileio.h2
2 files changed, 29 insertions, 0 deletions
diff --git a/src/basic/fileio.c b/src/basic/fileio.c
index b22fcd030..b07f4f92a 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 848024607..300d060ce 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);