From 824046ca2900f2bc9524015d5cdfa1a7ec0005e5 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Mon, 15 Sep 2003 22:34:18 +0000 Subject: [PATCH] Don't trash errno when a read fails. --- lib/ChangeLog | 9 +++++++++ lib/getndelim2.c | 5 +++-- lib/readutmp.c | 32 +++++++++++++++++++++----------- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/lib/ChangeLog b/lib/ChangeLog index 904cc9c89f..9b8480dd7c 100644 --- a/lib/ChangeLog +++ b/lib/ChangeLog @@ -1,3 +1,12 @@ +2003-09-15 Paul Eggert + + * lib/getndelim2.c (getndelim2): Don't trash errno when a read + fails, so that the caller gets the proper errno. + + * readutmp.c (read_utmp): Likewise. + Check for fstat error. Close stream and free storage + when failing. + 2003-09-14 Bruno Haible * fwriteerror.h: New file. diff --git a/lib/getndelim2.c b/lib/getndelim2.c index db81e1b29d..6f08689995 100644 --- a/lib/getndelim2.c +++ b/lib/getndelim2.c @@ -70,7 +70,7 @@ getndelim2 (char **lineptr, size_t *linesize, size_t nmax, { /* Here always *lineptr + *linesize == read_pos + nbytes_avail. */ - register int c = getc (stream); + register int c; /* We always want at least one char left in the buffer, since we always (unless we get an error while reading the first char) @@ -95,7 +95,8 @@ getndelim2 (char **lineptr, size_t *linesize, size_t nmax, } } - if (c == EOF || ferror (stream)) + c = getc (stream); + if (c == EOF) { /* Return partial line, if any. */ if (read_pos == *lineptr) diff --git a/lib/readutmp.c b/lib/readutmp.c index 1a6af083c9..71a913df0b 100644 --- a/lib/readutmp.c +++ b/lib/readutmp.c @@ -104,23 +104,33 @@ read_utmp (const char *filename, int *n_entries, STRUCT_UTMP **utmp_buf) if (utmp == NULL) return 1; - fstat (fileno (utmp), &file_stats); + if (fstat (fileno (utmp), &file_stats) != 0) + { + int e = errno; + fclose (utmp); + errno = e; + return 1; + } size = file_stats.st_size; - if (size > 0) - buf = xmalloc (size); - else + buf = xmalloc (size); + n_read = fread (buf, sizeof *buf, size / sizeof *buf, utmp); + if (ferror (utmp)) { + int e = errno; + free (buf); fclose (utmp); + errno = e; + return 1; + } + if (fclose (utmp) != 0) + { + int e = errno; + free (buf); + errno = e; return 1; } - /* Use < instead of != in case the utmp just grew. */ - n_read = fread (buf, 1, size, utmp); - if (ferror (utmp) || fclose (utmp) == EOF - || n_read < size) - return 1; - - *n_entries = size / sizeof (STRUCT_UTMP); + *n_entries = n_read; *utmp_buf = buf; return 0; -- 2.30.2