maint: update all copyright year number ranges
[coreutils.git] / src / sum.c
blob91af738dd1037ec89a77ab8549b7835bd2f2ea53
1 /* sum -- checksum and count the blocks in a file
2 Copyright (C) 1986-2017 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 "die.h"
28 #include "error.h"
29 #include "fadvise.h"
30 #include "human.h"
31 #include "safe-read.h"
32 #include "xfreopen.h"
34 /* The official name of this program (e.g., no 'g' prefix). */
35 #define PROGRAM_NAME "sum"
37 #define AUTHORS \
38 proper_name ("Kayvan Aghaiepour"), \
39 proper_name ("David MacKenzie")
41 /* True if any of the files read were the standard input. */
42 static bool have_read_stdin;
44 static struct option const longopts[] =
46 {"sysv", no_argument, NULL, 's'},
47 {GETOPT_HELP_OPTION_DECL},
48 {GETOPT_VERSION_OPTION_DECL},
49 {NULL, 0, NULL, 0}
52 void
53 usage (int status)
55 if (status != EXIT_SUCCESS)
56 emit_try_help ();
57 else
59 printf (_("\
60 Usage: %s [OPTION]... [FILE]...\n\
61 "),
62 program_name);
63 fputs (_("\
64 Print checksum and block counts for each FILE.\n\
65 "), stdout);
67 emit_stdin_note ();
69 fputs (_("\
70 \n\
71 -r use BSD sum algorithm, use 1K blocks\n\
72 -s, --sysv use System V sum algorithm, use 512 bytes blocks\n\
73 "), stdout);
74 fputs (HELP_OPTION_DESCRIPTION, stdout);
75 fputs (VERSION_OPTION_DESCRIPTION, stdout);
76 emit_ancillary_info (PROGRAM_NAME);
78 exit (status);
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 true if successful. */
87 static bool
88 bsd_sum_file (const char *file, int print_name)
90 FILE *fp;
91 int checksum = 0; /* The checksum mod 2^16. */
92 uintmax_t total_bytes = 0; /* The number of bytes. */
93 int ch; /* Each character read. */
94 char hbuf[LONGEST_HUMAN_READABLE + 1];
95 bool is_stdin = STREQ (file, "-");
97 if (is_stdin)
99 fp = stdin;
100 have_read_stdin = true;
101 if (O_BINARY && ! isatty (STDIN_FILENO))
102 xfreopen (NULL, "rb", stdin);
104 else
106 fp = fopen (file, (O_BINARY ? "rb" : "r"));
107 if (fp == NULL)
109 error (0, errno, "%s", quotef (file));
110 return false;
114 fadvise (fp, FADVISE_SEQUENTIAL);
116 while ((ch = getc (fp)) != EOF)
118 total_bytes++;
119 checksum = (checksum >> 1) + ((checksum & 1) << 15);
120 checksum += ch;
121 checksum &= 0xffff; /* Keep it within bounds. */
124 if (ferror (fp))
126 error (0, errno, "%s", quotef (file));
127 if (!is_stdin)
128 fclose (fp);
129 return false;
132 if (!is_stdin && fclose (fp) != 0)
134 error (0, errno, "%s", quotef (file));
135 return false;
138 printf ("%05d %5s", checksum,
139 human_readable (total_bytes, hbuf, human_ceiling, 1, 1024));
140 if (print_name > 1)
141 printf (" %s", file);
142 putchar ('\n');
144 return true;
147 /* Calculate and print the checksum and the size in 512-byte blocks
148 of file FILE, or of the standard input if FILE is "-".
149 If PRINT_NAME is >0, print FILE next to the checksum and size.
150 Return true if successful. */
152 static bool
153 sysv_sum_file (const char *file, int print_name)
155 int fd;
156 unsigned char buf[8192];
157 uintmax_t total_bytes = 0;
158 char hbuf[LONGEST_HUMAN_READABLE + 1];
159 int r;
160 int checksum;
162 /* The sum of all the input bytes, modulo (UINT_MAX + 1). */
163 unsigned int s = 0;
165 bool is_stdin = STREQ (file, "-");
167 if (is_stdin)
169 fd = STDIN_FILENO;
170 have_read_stdin = true;
171 if (O_BINARY && ! isatty (STDIN_FILENO))
172 xfreopen (NULL, "rb", stdin);
174 else
176 fd = open (file, O_RDONLY | O_BINARY);
177 if (fd == -1)
179 error (0, errno, "%s", quotef (file));
180 return false;
184 while (1)
186 size_t i;
187 size_t bytes_read = safe_read (fd, buf, sizeof buf);
189 if (bytes_read == 0)
190 break;
192 if (bytes_read == SAFE_READ_ERROR)
194 error (0, errno, "%s", quotef (file));
195 if (!is_stdin)
196 close (fd);
197 return false;
200 for (i = 0; i < bytes_read; i++)
201 s += buf[i];
202 total_bytes += bytes_read;
205 if (!is_stdin && close (fd) != 0)
207 error (0, errno, "%s", quotef (file));
208 return false;
211 r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
212 checksum = (r & 0xffff) + (r >> 16);
214 printf ("%d %s", checksum,
215 human_readable (total_bytes, hbuf, human_ceiling, 1, 512));
216 if (print_name)
217 printf (" %s", file);
218 putchar ('\n');
220 return true;
224 main (int argc, char **argv)
226 bool ok;
227 int optc;
228 int files_given;
229 bool (*sum_func) (const char *, int) = bsd_sum_file;
231 initialize_main (&argc, &argv);
232 set_program_name (argv[0]);
233 setlocale (LC_ALL, "");
234 bindtextdomain (PACKAGE, LOCALEDIR);
235 textdomain (PACKAGE);
237 atexit (close_stdout);
239 /* Line buffer stdout to ensure lines are written atomically and immediately
240 so that processes running in parallel do not intersperse their output. */
241 setvbuf (stdout, NULL, _IOLBF, 0);
243 have_read_stdin = false;
245 while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1)
247 switch (optc)
249 case 'r': /* For SysV compatibility. */
250 sum_func = bsd_sum_file;
251 break;
253 case 's':
254 sum_func = sysv_sum_file;
255 break;
257 case_GETOPT_HELP_CHAR;
259 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
261 default:
262 usage (EXIT_FAILURE);
266 files_given = argc - optind;
267 if (files_given <= 0)
268 ok = sum_func ("-", files_given);
269 else
270 for (ok = true; optind < argc; optind++)
271 ok &= sum_func (argv[optind], files_given);
273 if (have_read_stdin && fclose (stdin) == EOF)
274 die (EXIT_FAILURE, errno, "%s", quotef ("-"));
275 return ok ? EXIT_SUCCESS : EXIT_FAILURE;