Don't trash errno when a read fails.
authorPaul Eggert <eggert@cs.ucla.edu>
Mon, 15 Sep 2003 22:34:18 +0000 (22:34 +0000)
committerPaul Eggert <eggert@cs.ucla.edu>
Mon, 15 Sep 2003 22:34:18 +0000 (22:34 +0000)
lib/ChangeLog
lib/getndelim2.c
lib/readutmp.c

index 904cc9c..9b8480d 100644 (file)
@@ -1,3 +1,12 @@
+2003-09-15  Paul Eggert  <eggert@twinsun.com>
+
+       * 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  <bruno@clisp.org>
 
        * fwriteerror.h: New file.
index db81e1b..6f08689 100644 (file)
@@ -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)
index 1a6af08..71a913d 100644 (file)
@@ -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;