3e405bb51b356b22cb5334dbafc0a3068bab8892
[platform/upstream/coreutils.git] / src / sum.c
1 /* sum -- checksum and count the blocks in a file
2    Copyright (C) 86, 89, 91, 1995-2001 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       printf (_("\
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       --help      display this help and exit\n\
70       --version   output version information and exit\n\
71 \n\
72 With no FILE, or when FILE is -, read standard input.\n\
73 "));
74       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
75     }
76   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
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 0 if successful, -1 if an error occurs. */
84
85 static int
86 bsd_sum_file (const char *file, int print_name)
87 {
88   register FILE *fp;
89   register int checksum = 0;    /* The checksum mod 2^16. */
90   register uintmax_t total_bytes = 0;   /* The number of bytes. */
91   register int ch;              /* Each character read. */
92   char hbuf[LONGEST_HUMAN_READABLE + 1];
93
94   if (STREQ (file, "-"))
95     {
96       fp = stdin;
97       have_read_stdin = 1;
98     }
99   else
100     {
101       fp = fopen (file, "r");
102       if (fp == NULL)
103         {
104           error (0, errno, "%s", file);
105           return -1;
106         }
107     }
108   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
109   SET_BINARY (fileno(fp));
110
111   while ((ch = getc (fp)) != EOF)
112     {
113       total_bytes++;
114       checksum = (checksum >> 1) + ((checksum & 1) << 15);
115       checksum += ch;
116       checksum &= 0xffff;       /* Keep it within bounds. */
117     }
118
119   if (ferror (fp))
120     {
121       error (0, errno, "%s", file);
122       if (!STREQ (file, "-"))
123         fclose (fp);
124       return -1;
125     }
126
127   if (!STREQ (file, "-") && fclose (fp) == EOF)
128     {
129       error (0, errno, "%s", file);
130       return -1;
131     }
132
133   printf ("%05d %5s", checksum,
134           human_readable_inexact (total_bytes, hbuf, 1, 1024, human_ceiling));
135   if (print_name > 1)
136     printf (" %s", file);
137   putchar ('\n');
138
139   return 0;
140 }
141
142 /* Calculate and print the checksum and the size in 512-byte blocks
143    of file FILE, or of the standard input if FILE is "-".
144    If PRINT_NAME is >0, print FILE next to the checksum and size.
145    Return 0 if successful, -1 if an error occurs. */
146
147 static int
148 sysv_sum_file (const char *file, int print_name)
149 {
150   int fd;
151   unsigned char buf[8192];
152   register int bytes_read;
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   register unsigned int s = 0;
160
161   if (STREQ (file, "-"))
162     {
163       fd = 0;
164       have_read_stdin = 1;
165     }
166   else
167     {
168       fd = open (file, O_RDONLY);
169       if (fd == -1)
170         {
171           error (0, errno, "%s", file);
172           return -1;
173         }
174     }
175   /* Need binary I/O, or else byte counts and checksums are incorrect.  */
176   SET_BINARY (fd);
177
178   while ((bytes_read = safe_read (fd, buf, sizeof buf)) > 0)
179     {
180       register int i;
181
182       for (i = 0; i < bytes_read; i++)
183         s += buf[i];
184       total_bytes += bytes_read;
185     }
186
187   if (bytes_read < 0)
188     {
189       error (0, errno, "%s", file);
190       if (!STREQ (file, "-"))
191         close (fd);
192       return -1;
193     }
194
195   if (!STREQ (file, "-") && close (fd) == -1)
196     {
197       error (0, errno, "%s", file);
198       return -1;
199     }
200
201   r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
202   checksum = (r & 0xffff) + (r >> 16);
203
204   printf ("%d %s", checksum,
205           human_readable_inexact (total_bytes, hbuf, 1, 512, human_ceiling));
206   if (print_name)
207     printf (" %s", file);
208   putchar ('\n');
209
210   return 0;
211 }
212
213 int
214 main (int argc, char **argv)
215 {
216   int errors = 0;
217   int optc;
218   int files_given;
219   int (*sum_func) PARAMS ((const char *, int)) = bsd_sum_file;
220
221   program_name = argv[0];
222   setlocale (LC_ALL, "");
223   bindtextdomain (PACKAGE, LOCALEDIR);
224   textdomain (PACKAGE);
225
226   atexit (close_stdout);
227
228   have_read_stdin = 0;
229
230   while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
231     {
232       switch (optc)
233         {
234         case 0:
235           break;
236
237         case 'r':               /* For SysV compatibility. */
238           sum_func = bsd_sum_file;
239           break;
240
241         case 's':
242           sum_func = sysv_sum_file;
243           break;
244
245         case_GETOPT_HELP_CHAR;
246
247         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
248
249         default:
250           usage (1);
251         }
252     }
253
254   files_given = argc - optind;
255   if (files_given == 0)
256     {
257       if ((*sum_func) ("-", files_given) < 0)
258         errors = 1;
259     }
260   else
261     for (; optind < argc; optind++)
262       if ((*sum_func) (argv[optind], files_given) < 0)
263         errors = 1;
264
265   if (have_read_stdin && fclose (stdin) == EOF)
266     error (EXIT_FAILURE, errno, "-");
267   exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
268 }