.
[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 STRUCT_UTMP *utmp_contents = 0;
35
36 /* Copy UT->ut_name into storage obtained from malloc.  Then remove any
37    trailing spaces from the copy, NUL terminate it, and return the copy.  */
38
39 char *
40 extract_trimmed_name (ut)
41   const STRUCT_UTMP *ut;
42 {
43   char *p, *trimmed_name;
44
45   trimmed_name = xmalloc (sizeof (ut->ut_name) + 1);
46   strncpy (trimmed_name, ut->ut_name, sizeof (ut->ut_name));
47   /* Append a trailing space character.  Some systems pad names shorter than
48      the maximum with spaces, others pad with NULs.  Remove any spaces.  */
49   trimmed_name[sizeof (ut->ut_name)] = ' ';
50   p = strchr (trimmed_name, ' ');
51   if (p != NULL)
52     *p = '\0';
53   return trimmed_name;
54 }
55
56 /* Read the utmp file FILENAME into UTMP_CONTENTS and return the
57    number of entries it contains. */
58
59 int
60 read_utmp (filename)
61   const char *filename;
62 {
63   FILE *utmp;
64   struct stat file_stats;
65   size_t n_read;
66   size_t size;
67
68   if (utmp_contents)
69     {
70       free (utmp_contents);
71       utmp_contents = 0;
72     }
73
74   utmp = fopen (filename, "r");
75   if (utmp == NULL)
76     error (1, errno, "%s", filename);
77
78   fstat (fileno (utmp), &file_stats);
79   size = file_stats.st_size;
80   if (size > 0)
81     utmp_contents = (STRUCT_UTMP *) xmalloc (size);
82   else
83     {
84       fclose (utmp);
85       return 0;
86     }
87
88   /* Use < instead of != in case the utmp just grew.  */
89   n_read = fread (utmp_contents, 1, size, utmp);
90   if (ferror (utmp) || fclose (utmp) == EOF
91       || n_read < size)
92     error (1, errno, "%s", filename);
93
94   return size / sizeof (STRUCT_UTMP);
95 }