add "const" attribute, where possible
[platform/upstream/coreutils.git] / src / sum.c
1 /* sum -- checksum and count the blocks in a file
2    Copyright (C) 86, 89, 91, 1995-2002, 2004, 2005, 2008
3    Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Like BSD sum or SysV sum -r, except like SysV sum if -s option is given. */
19
20 /* Written by Kayvan Aghaiepour and David MacKenzie. */
21
22 #include <config.h>
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <getopt.h>
27 #include "system.h"
28 #include "error.h"
29 #include "human.h"
30 #include "safe-read.h"
31
32 /* The official name of this program (e.g., no `g' prefix).  */
33 #define PROGRAM_NAME "sum"
34
35 #define AUTHORS \
36   proper_name ("Kayvan Aghaiepour"), \
37   proper_name ("David MacKenzie")
38
39 /* True if any of the files read were the standard input. */
40 static bool have_read_stdin;
41
42 static const struct option const longopts[] =
43 {
44   {"sysv", no_argument, NULL, 's'},
45   {GETOPT_HELP_OPTION_DECL},
46   {GETOPT_VERSION_OPTION_DECL},
47   {NULL, 0, NULL, 0}
48 };
49
50 void
51 usage (int status)
52 {
53   if (status != EXIT_SUCCESS)
54     fprintf (stderr, _("Try `%s --help' for more information.\n"),
55              program_name);
56   else
57     {
58       printf (_("\
59 Usage: %s [OPTION]... [FILE]...\n\
60 "),
61               program_name);
62       fputs (_("\
63 Print checksum and block counts for each FILE.\n\
64 \n\
65   -r              defeat -s, use BSD sum algorithm, use 1K blocks\n\
66   -s, --sysv      use System V sum algorithm, use 512 bytes blocks\n\
67 "), stdout);
68       fputs (HELP_OPTION_DESCRIPTION, stdout);
69       fputs (VERSION_OPTION_DESCRIPTION, stdout);
70       fputs (_("\
71 \n\
72 With no FILE, or when FILE is -, read standard input.\n\
73 "), stdout);
74       emit_bug_reporting_address ();
75     }
76   exit (status);
77 }
78
79 /* Calculate and print the rotated checksum and the size in 1K blocks
80    of file FILE, or of the standard input if FILE is "-".
81    If PRINT_NAME is >1, print FILE next to the checksum and size.
82    The checksum varies depending on sizeof (int).
83    Return true if successful.  */
84
85 static bool
86 bsd_sum_file (const char *file, int print_name)
87 {
88   FILE *fp;
89   int checksum = 0;     /* The checksum mod 2^16. */
90   uintmax_t total_bytes = 0;    /* The number of bytes. */
91   int ch;               /* Each character read. */
92   char hbuf[LONGEST_HUMAN_READABLE + 1];
93   bool is_stdin = STREQ (file, "-");
94
95   if (is_stdin)
96     {
97       fp = stdin;
98       have_read_stdin = true;
99       if (O_BINARY && ! isatty (STDIN_FILENO))
100         freopen (NULL, "rb", stdin);
101     }
102   else
103     {
104       fp = fopen (file, (O_BINARY ? "rb" : "r"));
105       if (fp == NULL)
106         {
107           error (0, errno, "%s", file);
108           return false;
109         }
110     }
111
112   while ((ch = getc (fp)) != EOF)
113     {
114       total_bytes++;
115       checksum = (checksum >> 1) + ((checksum & 1) << 15);
116       checksum += ch;
117       checksum &= 0xffff;       /* Keep it within bounds. */
118     }
119
120   if (ferror (fp))
121     {
122       error (0, errno, "%s", file);
123       if (!is_stdin)
124         fclose (fp);
125       return false;
126     }
127
128   if (!is_stdin && fclose (fp) != 0)
129     {
130       error (0, errno, "%s", file);
131       return false;
132     }
133
134   printf ("%05d %5s", checksum,
135           human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
136   if (print_name > 1)
137     printf (" %s", file);
138   putchar ('\n');
139
140   return true;
141 }
142
143 /* Calculate and print the checksum and the size in 512-byte blocks
144    of file FILE, or of the standard input if FILE is "-".
145    If PRINT_NAME is >0, print FILE next to the checksum and size.
146    Return true if successful.  */
147
148 static bool
149 sysv_sum_file (const char *file, int print_name)
150 {
151   int fd;
152   unsigned char buf[8192];
153   uintmax_t total_bytes = 0;
154   char hbuf[LONGEST_HUMAN_READABLE + 1];
155   int r;
156   int checksum;
157
158   /* The sum of all the input bytes, modulo (UINT_MAX + 1).  */
159   unsigned int s = 0;
160
161   bool is_stdin = STREQ (file, "-");
162
163   if (is_stdin)
164     {
165       fd = STDIN_FILENO;
166       have_read_stdin = true;
167       if (O_BINARY && ! isatty (STDIN_FILENO))
168         freopen (NULL, "rb", stdin);
169     }
170   else
171     {
172       fd = open (file, O_RDONLY | O_BINARY);
173       if (fd == -1)
174         {
175           error (0, errno, "%s", file);
176           return false;
177         }
178     }
179
180   while (1)
181     {
182       size_t i;
183       size_t bytes_read = safe_read (fd, buf, sizeof buf);
184
185       if (bytes_read == 0)
186         break;
187
188       if (bytes_read == SAFE_READ_ERROR)
189         {
190           error (0, errno, "%s", file);
191           if (!is_stdin)
192             close (fd);
193           return false;
194         }
195
196       for (i = 0; i < bytes_read; i++)
197         s += buf[i];
198       total_bytes += bytes_read;
199     }
200
201   if (!is_stdin && close (fd) != 0)
202     {
203       error (0, errno, "%s", file);
204       return false;
205     }
206
207   r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
208   checksum = (r & 0xffff) + (r >> 16);
209
210   printf ("%d %s", checksum,
211           human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
212   if (print_name)
213     printf (" %s", file);
214   putchar ('\n');
215
216   return true;
217 }
218
219 int
220 main (int argc, char **argv)
221 {
222   bool ok;
223   int optc;
224   int files_given;
225   bool (*sum_func) (const char *, int) = bsd_sum_file;
226
227   initialize_main (&argc, &argv);
228   set_program_name (argv[0]);
229   setlocale (LC_ALL, "");
230   bindtextdomain (PACKAGE, LOCALEDIR);
231   textdomain (PACKAGE);
232
233   atexit (close_stdout);
234
235   have_read_stdin = false;
236
237   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
238     {
239       switch (optc)
240         {
241         case 'r':               /* For SysV compatibility. */
242           sum_func = bsd_sum_file;
243           break;
244
245         case 's':
246           sum_func = sysv_sum_file;
247           break;
248
249         case_GETOPT_HELP_CHAR;
250
251         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
252
253         default:
254           usage (EXIT_FAILURE);
255         }
256     }
257
258   files_given = argc - optind;
259   if (files_given <= 0)
260     ok = sum_func ("-", files_given);
261   else
262     for (ok = true; optind < argc; optind++)
263       ok &= sum_func (argv[optind], files_given);
264
265   if (have_read_stdin && fclose (stdin) == EOF)
266     error (EXIT_FAILURE, errno, "-");
267   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
268 }