]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fileio: add new safe_fgetc() helper call
authorLennart Poettering <lennart@poettering.net>
Mon, 17 Dec 2018 10:21:12 +0000 (11:21 +0100)
committerLennart Poettering <lennart@poettering.net>
Tue, 18 Dec 2018 13:55:34 +0000 (14:55 +0100)
We have very similar code whenever we call fgetc() in place, let's
replae it by a common implementation.

src/basic/fileio.c
src/basic/fileio.h

index b22fcd0302708704e0b9589b37d041e15918e816..b07f4f92a9f531a76fd6a32826ed0bbe2eeb753e 100644 (file)
@@ -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;
+}
index 8480246072222491faed37ea2fe9bd91d191b4e2..300d060cea48032298a3a84445ff66f08cfaa748 100644 (file)
@@ -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);