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.
This commit is contained in:
Lennart Poettering
2018-12-18 14:55:34 +01:00
parent 0e89eb474d
commit 285a9b2749
2 changed files with 29 additions and 0 deletions
+27
View 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;
}
+2
View 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);