(main): Call initialize_main.
[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 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 /* 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 "closeout.h"
29 #include "error.h"
30 #include "human.h"
31 #include "safe-read.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "sum"
35
36 #define AUTHORS N_ ("Kayvan Aghaiepour and David MacKenzie")
37
38 /* The name this program was run with. */
39 char *program_name;
40
41 /* Nonzero if any of the files read were the standard input. */
42 static int have_read_stdin;
43
44 static struct option const longopts[] =
45 {
46   {"sysv", no_argument, NULL, 's'},
47   {GETOPT_HELP_OPTION_DECL},
48   {GETOPT_VERSION_OPTION_DECL},
49   {NULL, 0, NULL, 0}
50 };
51
52 void
53 usage (int status)
54 {
55   if (status != 0)
56     fprintf (stderr, _("Try `%s --help' for more information.\n"),
57              program_name);
58   else
59     {
60       printf (_("\
61 Usage: %s [OPTION]... [FILE]...\n\
62 "),
63               program_name);
64       fputs (_("\
65 Print checksum and block counts for each FILE.\n\
66 \n\
67   -r              defeat -s, use BSD sum algorithm, use 1K blocks\n\
68   -s, --sysv      use System V sum algorithm, use 512 bytes blocks\n\
69 "), stdout);
70       fputs (HELP_OPTION_DESCRIPTION, stdout);
71       fputs (VERSION_OPTION_DESCRIPTION, stdout);
72       fputs (_("\
73 \n\
74 With no FILE, or when FILE is -, read standard input.\n\
75 "), stdout);
76       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
77     }
78   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
79 }
80
81 /* Calculate and print the rotated checksum and the size in 1K blocks
82    of file FILE, or of the standard input if FILE is "-".
83    If PRINT_NAME is >1, print FILE next to the checksum and size.
84    The checksum varies depending on sizeof(int).
85    Return 0 if successful, -1 if an error occurs. */
86
87 static int
88 bsd_sum_file (const char *file, int print_name)
89 {
90   register FILE *fp;
91   register int checksum = 0;    /* The checksum mod 2^16. */
92   register uintmax_t total_bytes = 0;   /* The number of bytes. */
93   register int ch;              /* Each character read. */
94   char hbuf[LONGEST_HUMAN_READABLE + 1];
95
96   if (STREQ (file, "-"))
97     {
98       fp = stdin;
99       have_read_stdin = 1;
100     }
101   else
102     {
103       fp = fopen (file, "r");
104       if (fp == NULL)
105         {
106           error (0, errno, "%s", file);
107           return -1;
108         }
109     }
110   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
111   SET_BINARY (fileno(fp));
112
113   while ((ch = getc (fp)) != EOF)
114     {
115       total_bytes++;
116       checksum = (checksum >> 1) + ((checksum & 1) << 15);
117       checksum += ch;
118       checksum &= 0xffff;       /* Keep it within bounds. */
119     }
120
121   if (ferror (fp))
122     {
123       error (0, errno, "%s", file);
124       if (!STREQ (file, "-"))
125         fclose (fp);
126       return -1;
127     }
128
129   if (!STREQ (file, "-") && fclose (fp) == EOF)
130     {
131       error (0, errno, "%s", file);
132       return -1;
133     }
134
135   printf ("%05d %5s", checksum,
136           human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
137   if (print_name > 1)
138     printf (" %s", file);
139   putchar ('\n');
140
141   return 0;
142 }
143
144 /* Calculate and print the checksum and the size in 512-byte blocks
145    of file FILE, or of the standard input if FILE is "-".
146    If PRINT_NAME is >0, print FILE next to the checksum and size.
147    Return 0 if successful, -1 if an error occurs. */
148
149 static int
150 sysv_sum_file (const char *file, int print_name)
151 {
152   int fd;
153   unsigned char buf[8192];
154   uintmax_t total_bytes = 0;
155   char hbuf[LONGEST_HUMAN_READABLE + 1];
156   int r;
157   int checksum;
158
159   /* The sum of all the input bytes, modulo (UINT_MAX + 1).  */
160   unsigned int s = 0;
161
162   if (STREQ (file, "-"))
163     {
164       fd = 0;
165       have_read_stdin = 1;
166     }
167   else
168     {
169       fd = open (file, O_RDONLY);
170       if (fd == -1)
171         {
172           error (0, errno, "%s", file);
173           return -1;
174         }
175     }
176   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
177   SET_BINARY (fd);
178
179   while (1)
180     {
181       size_t i;
182       size_t bytes_read = safe_read (fd, buf, sizeof buf);
183
184       if (bytes_read == 0)
185         break;
186
187       if (bytes_read == SAFE_READ_ERROR)
188         {
189           error (0, errno, "%s", file);
190           if (!STREQ (file, "-"))
191             close (fd);
192           return -1;
193         }
194
195       for (i = 0; i < bytes_read; i++)
196         s += buf[i];
197       total_bytes += bytes_read;
198     }
199
200   if (!STREQ (file, "-") && close (fd) == -1)
201     {
202       error (0, errno, "%s", file);
203       return -1;
204     }
205
206   r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
207   checksum = (r & 0xffff) + (r >> 16);
208
209   printf ("%d %s", checksum,
210           human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
211   if (print_name)
212     printf (" %s", file);
213   putchar ('\n');
214
215   return 0;
216 }
217
218 int
219 main (int argc, char **argv)
220 {
221   int errors = 0;
222   int optc;
223   int files_given;
224   int (*sum_func) (const char *, int) = bsd_sum_file;
225
226   initialize_main (&argc, &argv);
227   program_name = argv[0];
228   setlocale (LC_ALL, "");
229   bindtextdomain (PACKAGE, LOCALEDIR);
230   textdomain (PACKAGE);
231
232   atexit (close_stdout);
233
234   have_read_stdin = 0;
235
236   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
237     {
238       switch (optc)
239         {
240         case 0:
241           break;
242
243         case 'r':               /* For SysV compatibility. */
244           sum_func = bsd_sum_file;
245           break;
246
247         case 's':
248           sum_func = sysv_sum_file;
249           break;
250
251         case_GETOPT_HELP_CHAR;
252
253         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
254
255         default:
256           usage (EXIT_FAILURE);
257         }
258     }
259
260   files_given = argc - optind;
261   if (files_given == 0)
262     {
263       if ((*sum_func) ("-", files_given) < 0)
264         errors = 1;
265     }
266   else
267     for (; optind < argc; optind++)
268       if ((*sum_func) (argv[optind], files_given) < 0)
269         errors = 1;
270
271   if (have_read_stdin && fclose (stdin) == EOF)
272     error (EXIT_FAILURE, errno, "-");
273   exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
274 }