1 /* wc - print the number of bytes, words, and lines in files
2 Copyright (C) 85, 91, 1995-2004 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Paul Rubin, phr@ocf.berkeley.edu
19 and David MacKenzie, djm@gnu.ai.mit.edu. */
25 #include <sys/types.h>
27 /* Get mbstate_t, mbrtowc(), wcwidth(). */
32 /* Get iswprint(), iswspace(). */
36 #if !defined iswprint && !HAVE_ISWPRINT
37 # define iswprint(wc) 1
39 #if !defined iswspace && !HAVE_ISWSPACE
40 # define iswspace(wc) \
41 ((wc) == (unsigned char) (wc) && ISSPACE ((unsigned char) (wc)))
44 /* Include this after wctype.h so that we `#undef' ISPRINT
45 (from Solaris's euc.h, from widec.h, from wctype.h) before
46 redefining and using it. */
51 #include "safe-read.h"
53 /* Some systems, like BeOS, have multibyte encodings but lack mbstate_t. */
54 #if HAVE_MBRTOWC && defined mbstate_t
55 # define mbrtowc(pwc, s, n, ps) (mbrtowc) (pwc, s, n, 0)
58 #ifndef HAVE_DECL_WCWIDTH
59 "this configure-time declaration test was not run"
61 #if !HAVE_DECL_WCWIDTH
62 extern int wcwidth ();
65 /* If wcwidth() doesn't exist, assume all printable characters have
67 #if !defined wcwidth && !HAVE_WCWIDTH
68 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
71 /* The official name of this program (e.g., no `g' prefix). */
72 #define PROGRAM_NAME "wc"
74 #define AUTHORS "Paul Rubin", "David MacKenzie"
76 /* Size of atomic reads. */
77 #define BUFFER_SIZE (16 * 1024)
79 /* The name this program was run with. */
82 /* Cumulative number of lines, words, chars and bytes in all files so far.
83 max_line_length is the maximum over all files processed so far. */
84 static uintmax_t total_lines
;
85 static uintmax_t total_words
;
86 static uintmax_t total_chars
;
87 static uintmax_t total_bytes
;
88 static uintmax_t max_line_length
;
90 /* Which counts to print. */
91 static int print_lines
, print_words
, print_chars
, print_bytes
;
92 static int print_linelength
;
94 /* The print width of each count. */
95 static int number_width
;
97 /* Nonzero if we have ever read the standard input. */
98 static int have_read_stdin
;
100 /* The error code to return to the system. */
101 static int exit_status
;
103 /* The result of calling fstat or stat on a file descriptor or file. */
106 /* If positive, fstat or stat has not been called yet. Otherwise,
107 this is the value returned from fstat or stat. */
110 /* If FAILED is zero, this is the file's status. */
115 static struct option
const longopts
[] =
117 {"bytes", no_argument
, NULL
, 'c'},
118 {"chars", no_argument
, NULL
, 'm'},
119 {"lines", no_argument
, NULL
, 'l'},
120 {"words", no_argument
, NULL
, 'w'},
121 {"max-line-length", no_argument
, NULL
, 'L'},
122 {GETOPT_HELP_OPTION_DECL
},
123 {GETOPT_VERSION_OPTION_DECL
},
130 if (status
!= EXIT_SUCCESS
)
131 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
136 Usage: %s [OPTION]... [FILE]...\n\
140 Print newline, word, and byte counts for each FILE, and a total line if\n\
141 more than one FILE is specified. With no FILE, or when FILE is -,\n\
142 read standard input.\n\
143 -c, --bytes print the byte counts\n\
144 -m, --chars print the character counts\n\
145 -l, --lines print the newline counts\n\
148 -L, --max-line-length print the length of the longest line\n\
149 -w, --words print the word counts\n\
151 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
152 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
153 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
158 /* FILE is the name of the file (or NULL for standard input)
159 associated with the specified counters. */
161 write_counts (uintmax_t lines
,
165 uintmax_t linelength
,
168 static char const format_sp_int
[] = " %*s";
169 char const *format_int
= format_sp_int
+ 1;
170 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
174 printf (format_int
, number_width
, umaxtostr (lines
, buf
));
175 format_int
= format_sp_int
;
179 printf (format_int
, number_width
, umaxtostr (words
, buf
));
180 format_int
= format_sp_int
;
184 printf (format_int
, number_width
, umaxtostr (chars
, buf
));
185 format_int
= format_sp_int
;
189 printf (format_int
, number_width
, umaxtostr (bytes
, buf
));
190 format_int
= format_sp_int
;
192 if (print_linelength
)
194 printf (format_int
, number_width
, umaxtostr (linelength
, buf
));
197 printf (" %s", file
);
201 /* FILE_X is the name of the file (or NULL for standard input) that is
202 open on descriptor FD. */
204 wc (int fd
, char const *file_x
, struct fstatus
*fstatus
)
206 char buf
[BUFFER_SIZE
+ 1];
208 uintmax_t lines
, words
, chars
, bytes
, linelength
;
209 int count_bytes
, count_chars
, count_complicated
;
210 char const *file
= file_x
? file_x
: _("standard input");
212 lines
= words
= chars
= bytes
= linelength
= 0;
214 /* If in the current locale, chars are equivalent to bytes, we prefer
215 counting bytes, because that's easier. */
216 #if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
219 count_bytes
= print_bytes
;
220 count_chars
= print_chars
;
225 count_bytes
= print_bytes
+ print_chars
;
228 count_complicated
= print_words
+ print_linelength
;
230 /* We need binary input, since `wc' relies on `lseek' and byte counts. */
233 /* When counting only bytes, save some line- and word-counting
234 overhead. If FD is a `regular' Unix file, using lseek is enough
235 to get its `size' in bytes. Otherwise, read blocks of BUFFER_SIZE
236 bytes at a time until EOF. Note that the `size' (number of bytes)
237 that wc reports is smaller than stats.st_size when the file is not
238 positioned at its beginning. That's why the lseek calls below are
239 necessary. For example the command
240 `(dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group'
241 should make wc report `0' bytes. */
243 if (count_bytes
&& !count_chars
&& !print_lines
&& !count_complicated
)
245 off_t current_pos
, end_pos
;
247 if (0 < fstatus
->failed
)
248 fstatus
->failed
= fstat (fd
, &fstatus
->st
);
250 if (! fstatus
->failed
&& S_ISREG (fstatus
->st
.st_mode
)
251 && (current_pos
= lseek (fd
, (off_t
) 0, SEEK_CUR
)) != -1
252 && (end_pos
= lseek (fd
, (off_t
) 0, SEEK_END
)) != -1)
254 /* Be careful here. The current position may actually be
255 beyond the end of the file. As in the example above. */
256 bytes
= end_pos
< current_pos
? 0 : end_pos
- current_pos
;
260 while ((bytes_read
= safe_read (fd
, buf
, BUFFER_SIZE
)) > 0)
262 if (bytes_read
== SAFE_READ_ERROR
)
264 error (0, errno
, "%s", file
);
272 else if (!count_chars
&& !count_complicated
)
274 /* Use a separate loop when counting only lines or lines and bytes --
275 but not chars or words. */
276 while ((bytes_read
= safe_read (fd
, buf
, BUFFER_SIZE
)) > 0)
278 register char *p
= buf
;
280 if (bytes_read
== SAFE_READ_ERROR
)
282 error (0, errno
, "%s", file
);
287 while ((p
= memchr (p
, '\n', (buf
+ bytes_read
) - p
)))
295 #if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
296 # define SUPPORT_OLD_MBRTOWC 1
297 else if (MB_CUR_MAX
> 1)
300 uintmax_t linepos
= 0;
302 uintmax_t last_error_line
= 0;
303 int last_error_errno
= 0;
304 # if SUPPORT_OLD_MBRTOWC
305 /* Back-up the state before each multibyte character conversion and
306 move the last incomplete character of the buffer to the front
307 of the buffer. This is needed because we don't know whether
308 the `mbrtowc' function updates the state when it returns -2, -
309 this is the ISO C 99 and glibc-2.2 behaviour - or not - amended
310 ANSI C, glibc-2.1 and Solaris 5.7 behaviour. We don't have an
311 autoconf test for this, yet. */
312 size_t prev
= 0; /* number of bytes carried over from previous round */
314 const size_t prev
= 0;
317 memset (&state
, 0, sizeof (mbstate_t));
318 while ((bytes_read
= safe_read (fd
, buf
+ prev
, BUFFER_SIZE
- prev
)) > 0)
321 # if SUPPORT_OLD_MBRTOWC
322 mbstate_t backup_state
;
324 if (bytes_read
== SAFE_READ_ERROR
)
326 error (0, errno
, "%s", file
);
339 # if SUPPORT_OLD_MBRTOWC
340 backup_state
= state
;
342 n
= mbrtowc (&wide_char
, p
, bytes_read
, &state
);
343 if (n
== (size_t) -2)
345 # if SUPPORT_OLD_MBRTOWC
346 state
= backup_state
;
350 if (n
== (size_t) -1)
352 /* Signal repeated errors only once per line. */
353 if (!(lines
+ 1 == last_error_line
354 && errno
== last_error_errno
))
356 char line_number_buf
[INT_BUFSIZE_BOUND (uintmax_t)];
357 last_error_line
= lines
+ 1;
358 last_error_errno
= errno
;
359 error (0, errno
, "%s:%s", file
,
360 umaxtostr (last_error_line
, line_number_buf
));
382 if (linepos
> linelength
)
383 linelength
= linepos
;
385 goto mb_word_separator
;
387 linepos
+= 8 - (linepos
% 8);
388 goto mb_word_separator
;
401 if (iswprint (wide_char
))
403 int width
= wcwidth (wide_char
);
406 if (iswspace (wide_char
))
407 goto mb_word_separator
;
414 while (bytes_read
> 0);
416 # if SUPPORT_OLD_MBRTOWC
419 if (bytes_read
== BUFFER_SIZE
)
421 /* Encountered a very long redundant shift sequence. */
425 memmove (buf
, p
, bytes_read
);
430 if (linepos
> linelength
)
431 linelength
= linepos
;
439 uintmax_t linepos
= 0;
441 while ((bytes_read
= safe_read (fd
, buf
, BUFFER_SIZE
)) > 0)
444 if (bytes_read
== SAFE_READ_ERROR
)
446 error (0, errno
, "%s", file
);
461 if (linepos
> linelength
)
462 linelength
= linepos
;
466 linepos
+= 8 - (linepos
% 8);
480 if (ISPRINT ((unsigned char) p
[-1]))
483 if (ISSPACE ((unsigned char) p
[-1]))
490 while (--bytes_read
);
492 if (linepos
> linelength
)
493 linelength
= linepos
;
498 if (count_chars
< print_chars
)
501 write_counts (lines
, words
, chars
, bytes
, linelength
, file_x
);
502 total_lines
+= lines
;
503 total_words
+= words
;
504 total_chars
+= chars
;
505 total_bytes
+= bytes
;
506 if (linelength
> max_line_length
)
507 max_line_length
= linelength
;
511 wc_file (char const *file
, struct fstatus
*fstatus
)
513 if (STREQ (file
, "-"))
516 wc (STDIN_FILENO
, file
, fstatus
);
520 int fd
= open (file
, O_RDONLY
);
523 error (0, errno
, "%s", file
);
527 wc (fd
, file
, fstatus
);
530 error (0, errno
, "%s", file
);
536 /* Return the file status for the NFILES files addressed by FILE.
537 Optimize the case where only one number is printed, for just one
538 file; in that case we can use a print width of 1, so we don't need
541 static struct fstatus
*
542 get_input_fstatus (int nfiles
, char * const *file
)
544 struct fstatus
*fstatus
= xmalloc (nfiles
* sizeof *fstatus
);
547 && ((print_lines
+ print_words
+ print_chars
548 + print_bytes
+ print_linelength
)
550 fstatus
[0].failed
= 1;
555 for (i
= 0; i
< nfiles
; i
++)
556 fstatus
[i
].failed
= (! file
[i
] || STREQ (file
[i
], "-")
557 ? fstat (STDIN_FILENO
, &fstatus
[i
].st
)
558 : stat (file
[i
], &fstatus
[i
].st
));
564 /* Return a print width suitable for the NFILES files whose status is
565 recorded in FSTATUS. Optimize the same special case that
566 get_input_fstatus optimizes. */
569 compute_number_width (int nfiles
, struct fstatus
const *fstatus
)
573 if (fstatus
[0].failed
<= 0)
575 int minimum_width
= 1;
576 uintmax_t regular_total
= 0;
579 for (i
= 0; i
< nfiles
; i
++)
580 if (! fstatus
[i
].failed
)
582 if (S_ISREG (fstatus
[i
].st
.st_mode
))
583 regular_total
+= fstatus
[i
].st
.st_size
;
588 for (; 10 <= regular_total
; regular_total
/= 10)
590 if (width
< minimum_width
)
591 width
= minimum_width
;
599 main (int argc
, char **argv
)
603 struct fstatus
*fstatus
;
605 initialize_main (&argc
, &argv
);
606 program_name
= argv
[0];
607 setlocale (LC_ALL
, "");
608 bindtextdomain (PACKAGE
, LOCALEDIR
);
609 textdomain (PACKAGE
);
611 atexit (close_stdout
);
614 print_lines
= print_words
= print_chars
= print_bytes
= print_linelength
= 0;
615 total_lines
= total_words
= total_chars
= total_bytes
= max_line_length
= 0;
617 while ((optc
= getopt_long (argc
, argv
, "clLmw", longopts
, NULL
)) != -1)
640 print_linelength
= 1;
643 case_GETOPT_HELP_CHAR
;
645 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
648 usage (EXIT_FAILURE
);
651 if (print_lines
+ print_words
+ print_chars
+ print_bytes
+ print_linelength
653 print_lines
= print_words
= print_bytes
= 1;
655 nfiles
= argc
- optind
;
656 nfiles
+= (nfiles
== 0);
658 fstatus
= get_input_fstatus (nfiles
, argv
+ optind
);
659 number_width
= compute_number_width (nfiles
, fstatus
);
664 wc (STDIN_FILENO
, NULL
, &fstatus
[0]);
669 for (i
= 0; i
< nfiles
; i
++)
670 wc_file (argv
[optind
+ i
], &fstatus
[i
]);
673 write_counts (total_lines
, total_words
, total_chars
, total_bytes
,
674 max_line_length
, _("total"));
679 if (have_read_stdin
&& close (STDIN_FILENO
) != 0)
680 error (EXIT_FAILURE
, errno
, "-");
682 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);