tests: cleanup trapping of signal names
[coreutils.git] / src / sum.c
blob407cb5d5b49d11979102555179476bc79db8a1ad
1 /* sum -- checksum and count the blocks in a file
2 Copyright (C) 1986-2015 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Like BSD sum or SysV sum -r, except like SysV sum if -s option is given. */
19 /* Written by Kayvan Aghaiepour and David MacKenzie. */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
26 #include "system.h"
27 #include "error.h"
28 #include "fadvise.h"
29 #include "human.h"
30 #include "safe-read.h"
31 #include "xfreopen.h"
33 /* The official name of this program (e.g., no 'g' prefix). */
34 #define PROGRAM_NAME "sum"
36 #define AUTHORS \
37 proper_name ("Kayvan Aghaiepour"), \
38 proper_name ("David MacKenzie")
40 /* True if any of the files read were the standard input. */
41 static bool have_read_stdin;
43 static struct option const longopts[] =
45 {"sysv", no_argument, NULL, 's'},
46 {GETOPT_HELP_OPTION_DECL},
47 {GETOPT_VERSION_OPTION_DECL},
48 {NULL, 0, NULL, 0}
51 void
52 usage (int status)
54 if (status != EXIT_SUCCESS)
55 emit_try_help ();
56 else
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 "), stdout);
66 emit_stdin_note ();
68 fputs (_("\
69 \n\
70 -r use BSD sum algorithm, use 1K blocks\n\
71 -s, --sysv use System V sum algorithm, use 512 bytes blocks\n\
72 "), stdout);
73 fputs (HELP_OPTION_DESCRIPTION, stdout);
74 fputs (VERSION_OPTION_DESCRIPTION, stdout);
75 emit_ancillary_info (PROGRAM_NAME);
77 exit (status);
80 /* Calculate and print the rotated checksum and the size in 1K blocks
81 of file FILE, or of the standard input if FILE is "-".
82 If PRINT_NAME is >1, print FILE next to the checksum and size.
83 The checksum varies depending on sizeof (int).
84 Return true if successful. */
86 static bool
87 bsd_sum_file (const char *file, int print_name)
89 FILE *fp;
90 int checksum = 0; /* The checksum mod 2^16. */
91 uintmax_t total_bytes = 0; /* The number of bytes. */
92 int ch; /* Each character read. */
93 char hbuf[LONGEST_HUMAN_READABLE + 1];
94 bool is_stdin = STREQ (file, "-");
96 if (is_stdin)
98 fp = stdin;
99 have_read_stdin = true;
100 if (O_BINARY && ! isatty (STDIN_FILENO))
101 xfreopen (NULL, "rb", stdin);
103 else
105 fp = fopen (file, (O_BINARY ? "rb" : "r"));
106 if (fp == NULL)
108 error (0, errno, "%s", quotef (file));
109 return false;
113 fadvise (fp, FADVISE_SEQUENTIAL);
115 while ((ch = getc (fp)) != EOF)
117 total_bytes++;
118 checksum = (checksum >> 1) + ((checksum & 1) << 15);
119 checksum += ch;
120 checksum &= 0xffff; /* Keep it within bounds. */
123 if (ferror (fp))
125 error (0, errno, "%s", quotef (file));
126 if (!is_stdin)
127 fclose (fp);
128 return false;
131 if (!is_stdin && fclose (fp) != 0)
133 error (0, errno, "%s", quotef (file));
134 return false;
137 printf ("%05d %5s", checksum,
138 human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
139 if (print_name > 1)
140 printf (" %s", file);
141 putchar ('\n');
143 return true;
146 /* Calculate and print the checksum and the size in 512-byte blocks
147 of file FILE, or of the standard input if FILE is "-".
148 If PRINT_NAME is >0, print FILE next to the checksum and size.
149 Return true if successful. */
151 static bool
152 sysv_sum_file (const char *file, int print_name)
154 int fd;
155 unsigned char buf[8192];
156 uintmax_t total_bytes = 0;
157 char hbuf[LONGEST_HUMAN_READABLE + 1];
158 int r;
159 int checksum;
161 /* The sum of all the input bytes, modulo (UINT_MAX + 1). */
162 unsigned int s = 0;
164 bool is_stdin = STREQ (file, "-");
166 if (is_stdin)
168 fd = STDIN_FILENO;
169 have_read_stdin = true;
170 if (O_BINARY && ! isatty (STDIN_FILENO))
171 xfreopen (NULL, "rb", stdin);
173 else
175 fd = open (file, O_RDONLY | O_BINARY);
176 if (fd == -1)
178 error (0, errno, "%s", quotef (file));
179 return false;
183 while (1)
185 size_t i;
186 size_t bytes_read = safe_read (fd, buf, sizeof buf);
188 if (bytes_read == 0)
189 break;
191 if (bytes_read == SAFE_READ_ERROR)
193 error (0, errno, "%s", quotef (file));
194 if (!is_stdin)
195 close (fd);
196 return false;
199 for (i = 0; i < bytes_read; i++)
200 s += buf[i];
201 total_bytes += bytes_read;
204 if (!is_stdin && close (fd) != 0)
206 error (0, errno, "%s", quotef (file));
207 return false;
210 r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
211 checksum = (r & 0xffff) + (r >> 16);
213 printf ("%d %s", checksum,
214 human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
215 if (print_name)
216 printf (" %s", file);
217 putchar ('\n');
219 return true;
223 main (int argc, char **argv)
225 bool ok;
226 int optc;
227 int files_given;
228 bool (*sum_func) (const char *, int) = bsd_sum_file;
230 initialize_main (&argc, &argv);
231 set_program_name (argv[0]);
232 setlocale (LC_ALL, "");
233 bindtextdomain (PACKAGE, LOCALEDIR);
234 textdomain (PACKAGE);
236 atexit (close_stdout);
238 /* Line buffer stdout to ensure lines are written atomically and immediately
239 so that processes running in parallel do not intersperse their output. */
240 setvbuf (stdout, NULL, _IOLBF, 0);
242 have_read_stdin = false;
244 while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
246 switch (optc)
248 case 'r': /* For SysV compatibility. */
249 sum_func = bsd_sum_file;
250 break;
252 case 's':
253 sum_func = sysv_sum_file;
254 break;
256 case_GETOPT_HELP_CHAR;
258 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
260 default:
261 usage (EXIT_FAILURE);
265 files_given = argc - optind;
266 if (files_given <= 0)
267 ok = sum_func ("-", files_given);
268 else
269 for (ok = true; optind < argc; optind++)
270 ok &= sum_func (argv[optind], files_given);
272 if (have_read_stdin && fclose (stdin) == EOF)
273 error (EXIT_FAILURE, errno, "%s", quotef ("-"));
274 return ok ? EXIT_SUCCESS : EXIT_FAILURE;