(read_utmp): Take new params: count and buffer.
[gnulib.git] / lib / readutmp.c
1 /* GNU's read utmp module.
2    Copyright (C) 92, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by jla; revised by djm */
19
20 #include <config.h>
21
22 #include <sys/stat.h>
23 #if defined(STDC_HEADERS) || defined(HAVE_STRING_H)
24 # include <string.h>
25 #else
26 # include <strings.h>
27 #endif /* STDC_HEADERS || HAVE_STRING_H */
28
29 #include "readutmp.h"
30 #include "error.h"
31
32 char *xmalloc ();
33
34 /* Copy UT->ut_name into storage obtained from malloc.  Then remove any
35    trailing spaces from the copy, NUL terminate it, and return the copy.  */
36
37 char *
38 extract_trimmed_name (ut)
39   const STRUCT_UTMP *ut;
40 {
41   char *p, *trimmed_name;
42
43   trimmed_name = xmalloc (sizeof (ut->ut_name) + 1);
44   strncpy (trimmed_name, ut->ut_name, sizeof (ut->ut_name));
45   /* Append a trailing space character.  Some systems pad names shorter than
46      the maximum with spaces, others pad with NULs.  Remove any spaces.  */
47   trimmed_name[sizeof (ut->ut_name)] = ' ';
48   p = strchr (trimmed_name, ' ');
49   if (p != NULL)
50     *p = '\0';
51   return trimmed_name;
52 }
53
54 /* Read the utmp file FILENAME into *UTMP_BUF, set *N_ENTRIES to the
55    number of entries read, and return zero.  If there is any error,
56    return non-zero and don't modify the parameters.  */
57
58 int
59 read_utmp (filename, n_entries, utmp_buf)
60   const char *filename;
61   int *n_entries;
62   STRUCT_UTMP **utmp_buf;
63 {
64   FILE *utmp;
65   struct stat file_stats;
66   size_t n_read;
67   size_t size;
68   STRUCT_UTMP *buf;
69
70   utmp = fopen (filename, "r");
71   if (utmp == NULL)
72     return 1;
73
74   fstat (fileno (utmp), &file_stats);
75   size = file_stats.st_size;
76   if (size > 0)
77     buf = (STRUCT_UTMP *) xmalloc (size);
78   else
79     {
80       fclose (utmp);
81       return 1;
82     }
83
84   /* Use < instead of != in case the utmp just grew.  */
85   n_read = fread (buf, 1, size, utmp);
86   if (ferror (utmp) || fclose (utmp) == EOF
87       || n_read < size)
88     return 1;
89
90   *n_entries = size / sizeof (STRUCT_UTMP);
91   *utmp_buf = buf;
92
93   return 0;
94 }