Also check for the log_user method, to avoid
[coreutils.git] / src / cut.c
blob960917394262ed30dd4295e311fc2259c154b664
1 /* cut - remove parts of lines of files
2 Copyright (C) 1984, 1997, 1998, 1999, 2000, 2001, 2002, 2003 by David M. Ihnat
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.
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 David Ihnat. */
20 /* POSIX changes, bug fixes, long-named options, and cleanup
21 by David MacKenzie <djm@gnu.ai.mit.edu>.
23 Rewrite cut_fields and cut_bytes -- Jim Meyering. */
25 #include <config.h>
27 #include <stdio.h>
28 #include <assert.h>
29 #include <getopt.h>
30 #include <sys/types.h>
31 #include "system.h"
32 #include "getstr.h"
33 #include "closeout.h"
34 #include "error.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "cut"
39 #define AUTHORS N_ ("David Ihnat, David MacKenzie, and Jim Meyering")
41 #define FATAL_ERROR(Message) \
42 do \
43 { \
44 error (0, 0, (Message)); \
45 usage (2); \
46 } \
47 while (0)
49 /* Append LOW, HIGH to the list RP of range pairs, allocating additional
50 space if necessary. Update local variable N_RP. When allocating,
51 update global variable N_RP_ALLOCATED. */
53 #define ADD_RANGE_PAIR(rp, low, high) \
54 do \
55 { \
56 if (n_rp >= n_rp_allocated) \
57 { \
58 n_rp_allocated *= 2; \
59 (rp) = (struct range_pair *) xrealloc ((char *) (rp), \
60 n_rp_allocated * sizeof (*(rp))); \
61 } \
62 rp[n_rp].lo = (low); \
63 rp[n_rp].hi = (high); \
64 ++n_rp; \
65 } \
66 while (0)
68 struct range_pair
70 unsigned int lo;
71 unsigned int hi;
74 /* This buffer is used to support the semantics of the -s option
75 (or lack of same) when the specified field list includes (does
76 not include) the first field. In both of those cases, the entire
77 first field must be read into this buffer to determine whether it
78 is followed by a delimiter or a newline before any of it may be
79 output. Otherwise, cut_fields can do the job without using this
80 buffer. */
81 static char *field_1_buffer;
83 /* The number of bytes allocated for FIELD_1_BUFFER. */
84 static size_t field_1_bufsize;
86 /* The largest field or byte index used as an endpoint of a closed
87 or degenerate range specification; this doesn't include the starting
88 index of right-open-ended ranges. For example, with either range spec
89 `2-5,9-', `2-3,5,9-' this variable would be set to 5. */
90 static unsigned int max_range_endpoint;
92 /* If nonzero, this is the index of the first field in a range that goes
93 to end of line. */
94 static unsigned int eol_range_start;
96 /* A nonzero, non-1 value with which to distinguish the index
97 corresponding to the lower bound of a range. */
98 #define RANGE_START_SENTINEL 2
100 /* In byte mode, which bytes to output.
101 In field mode, which DELIM-separated fields to output.
102 Both bytes and fields are numbered starting with 1,
103 so the zeroth element of this array is unused.
104 A field or byte K has been selected if
105 (K <= MAX_RANGE_ENDPOINT and PRINTABLE_FIELD[K])
106 || (EOL_RANGE_START > 0 && K >= EOL_RANGE_START). */
107 static int *printable_field;
109 enum operating_mode
111 undefined_mode,
113 /* Output characters that are in the given bytes. */
114 byte_mode,
116 /* Output the given delimeter-separated fields. */
117 field_mode
120 /* The name this program was run with. */
121 char *program_name;
123 static enum operating_mode operating_mode;
125 /* If nonzero do not output lines containing no delimeter characters.
126 Otherwise, all such lines are printed. This option is valid only
127 with field mode. */
128 static int suppress_non_delimited;
130 /* The delimeter character for field mode. */
131 static int delim;
133 /* Nonzero if the --output-delimiter=STRING option was specified. */
134 static int output_delimiter_specified;
136 /* The length of output_delimiter_string. */
137 static size_t output_delimiter_length;
139 /* The output field separator string. Defaults to the 1-character
140 string consisting of the input delimiter. */
141 static char *output_delimiter_string;
143 /* Nonzero if we have ever read standard input. */
144 static int have_read_stdin;
146 /* For long options that have no equivalent short option, use a
147 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
148 enum
150 OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1
153 static struct option const longopts[] =
155 {"bytes", required_argument, 0, 'b'},
156 {"characters", required_argument, 0, 'c'},
157 {"fields", required_argument, 0, 'f'},
158 {"delimiter", required_argument, 0, 'd'},
159 {"only-delimited", no_argument, 0, 's'},
160 {"output-delimiter", required_argument, 0, OUTPUT_DELIMITER_OPTION},
161 {GETOPT_HELP_OPTION_DECL},
162 {GETOPT_VERSION_OPTION_DECL},
163 {0, 0, 0, 0}
166 void
167 usage (int status)
169 if (status != 0)
170 fprintf (stderr, _("Try `%s --help' for more information.\n"),
171 program_name);
172 else
174 printf (_("\
175 Usage: %s [OPTION]... [FILE]...\n\
177 program_name);
178 fputs (_("\
179 Print selected parts of lines from each FILE to standard output.\n\
181 "), stdout);
182 fputs (_("\
183 Mandatory arguments to long options are mandatory for short options too.\n\
184 "), stdout);
185 fputs (_("\
186 -b, --bytes=LIST output only these bytes\n\
187 -c, --characters=LIST output only these characters\n\
188 -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter\n\
189 "), stdout);
190 fputs (_("\
191 -f, --fields=LIST output only these fields; also print any line\n\
192 that contains no delimiter character, unless\n\
193 the -s option is specified\n\
194 -n (ignored)\n\
195 "), stdout);
196 fputs (_("\
197 -s, --only-delimited do not print lines not containing delimiters\n\
198 --output-delimiter=STRING use STRING as the output delimiter\n\
199 the default is to use the input delimiter\n\
200 "), stdout);
201 fputs (HELP_OPTION_DESCRIPTION, stdout);
202 fputs (VERSION_OPTION_DESCRIPTION, stdout);
203 fputs (_("\
205 Use one, and only one of -b, -c or -f. Each LIST is made up of one\n\
206 range, or many ranges separated by commas. Each range is one of:\n\
208 N N'th byte, character or field, counted from 1\n\
209 N- from N'th byte, character or field, to end of line\n\
210 N-M from N'th to M'th (included) byte, character or field\n\
211 -M from first to M'th (included) byte, character or field\n\
213 With no FILE, or when FILE is -, read standard input.\n\
214 "), stdout);
215 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
217 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
220 /* Return nonzero if the K'th field or byte is printable.
221 When returning nonzero, if RANGE_START is non-NULL,
222 set *RANGE_START to nonzero if K is the beginning of a range, and
223 set *RANGE_START to zero if K is not the beginning of a range. */
225 static int
226 print_kth (unsigned int k, int *range_start)
228 if (0 < eol_range_start && eol_range_start <= k)
230 if (range_start)
231 *range_start = (k == eol_range_start);
232 return 1;
235 if (k <= max_range_endpoint && printable_field[k])
237 if (range_start)
238 *range_start = (printable_field[k] == RANGE_START_SENTINEL);
239 return 1;
242 return 0;
245 /* Given the list of field or byte range specifications FIELDSTR, set
246 MAX_RANGE_ENDPOINT and allocate and initialize the PRINTABLE_FIELD
247 array. If there is a right-open-ended range, set EOL_RANGE_START
248 to its starting index. FIELDSTR should be composed of one or more
249 numbers or ranges of numbers, separated by blanks or commas.
250 Incomplete ranges may be given: `-m' means `1-m'; `n-' means `n'
251 through end of line. Return nonzero if FIELDSTR contains at least
252 one field specification, zero otherwise. */
254 /* FIXME-someday: What if the user wants to cut out the 1,000,000-th field
255 of some huge input file? This function shouldn't have to allocate a table
256 of a million ints just so we can test every field < 10^6 with an array
257 dereference. Instead, consider using a dynamic hash table. It would be
258 simpler and nearly as good a solution to use a 32K x 4-byte table with
259 one bit per field index instead of a whole `int' per index. */
261 static int
262 set_fields (const char *fieldstr)
264 unsigned int initial = 1; /* Value of first number in a range. */
265 unsigned int value = 0; /* If nonzero, a number being accumulated. */
266 int dash_found = 0; /* Nonzero if a '-' is found in this field. */
267 int field_found = 0; /* Non-zero if at least one field spec
268 has been processed. */
270 struct range_pair *rp;
271 unsigned int n_rp;
272 unsigned int n_rp_allocated;
273 unsigned int i;
275 n_rp = 0;
276 n_rp_allocated = 16;
277 rp = (struct range_pair *) xmalloc (n_rp_allocated * sizeof (*rp));
279 /* Collect and store in RP the range end points.
280 It also sets EOL_RANGE_START if appropriate. */
282 for (;;)
284 if (*fieldstr == '-')
286 /* Starting a range. */
287 if (dash_found)
288 FATAL_ERROR (_("invalid byte or field list"));
289 dash_found++;
290 fieldstr++;
292 if (value)
294 initial = value;
295 value = 0;
297 else
298 initial = 1;
300 else if (*fieldstr == ',' || ISBLANK (*fieldstr) || *fieldstr == '\0')
302 /* Ending the string, or this field/byte sublist. */
303 if (dash_found)
305 dash_found = 0;
307 /* A range. Possibilites: -n, m-n, n-.
308 In any case, `initial' contains the start of the range. */
309 if (value == 0)
311 /* `n-'. From `initial' to end of line. */
312 eol_range_start = initial;
313 field_found = 1;
315 else
317 /* `m-n' or `-n' (1-n). */
318 if (value < initial)
319 FATAL_ERROR (_("invalid byte or field list"));
321 /* Is there already a range going to end of line? */
322 if (eol_range_start != 0)
324 /* Yes. Is the new sequence already contained
325 in the old one? If so, no processing is
326 necessary. */
327 if (initial < eol_range_start)
329 /* No, the new sequence starts before the
330 old. Does the old range going to end of line
331 extend into the new range? */
332 if (eol_range_start <= value)
334 /* Yes. Simply move the end of line marker. */
335 eol_range_start = initial;
337 else
339 /* No. A simple range, before and disjoint from
340 the range going to end of line. Fill it. */
341 ADD_RANGE_PAIR (rp, initial, value);
344 /* In any case, some fields were selected. */
345 field_found = 1;
348 else
350 /* There is no range going to end of line. */
351 ADD_RANGE_PAIR (rp, initial, value);
352 field_found = 1;
354 value = 0;
357 else if (value != 0)
359 /* A simple field number, not a range. */
360 ADD_RANGE_PAIR (rp, value, value);
361 value = 0;
362 field_found = 1;
365 if (*fieldstr == '\0')
367 break;
370 fieldstr++;
372 else if (ISDIGIT (*fieldstr))
374 /* FIXME: detect overflow? */
375 value = 10 * value + *fieldstr - '0';
376 fieldstr++;
378 else
379 FATAL_ERROR (_("invalid byte or field list"));
382 max_range_endpoint = 0;
383 for (i = 0; i < n_rp; i++)
385 if (rp[i].hi > max_range_endpoint)
386 max_range_endpoint = rp[i].hi;
389 /* Allocate an array large enough so that it may be indexed by
390 the field numbers corresponding to all finite ranges
391 (i.e. `2-6' or `-4', but not `5-') in FIELDSTR. */
393 printable_field = (int *) xmalloc ((max_range_endpoint + 1) * sizeof (int));
394 memset (printable_field, 0, (max_range_endpoint + 1) * sizeof (int));
396 /* Set the array entries corresponding to integers in the ranges of RP. */
397 for (i = 0; i < n_rp; i++)
399 unsigned int j = rp[i].lo;
401 /* Mark the first position of field or range with a sentinel,
402 but not if it's already part of another range. */
403 if (j <= rp[i].hi && ! printable_field[j])
404 printable_field[j] = RANGE_START_SENTINEL;
405 for (++j; j <= rp[i].hi; j++)
407 printable_field[j] = 1;
411 free (rp);
413 return field_found;
416 /* Read from stream STREAM, printing to standard output any selected bytes. */
418 static void
419 cut_bytes (FILE *stream)
421 unsigned int byte_idx; /* Number of bytes in the line so far. */
422 /* Whether to begin printing delimiters between ranges for the current line.
423 Set after we've begun printing data corresponding to the first range. */
424 int print_delimiter;
426 byte_idx = 0;
427 print_delimiter = 0;
428 while (1)
430 register int c; /* Each character from the file. */
432 c = getc (stream);
434 if (c == '\n')
436 putchar ('\n');
437 byte_idx = 0;
438 print_delimiter = 0;
440 else if (c == EOF)
442 if (byte_idx > 0)
443 putchar ('\n');
444 break;
446 else
448 int range_start;
449 if (print_kth (++byte_idx, &range_start))
451 if (range_start && print_delimiter && output_delimiter_specified)
453 fwrite (output_delimiter_string, sizeof (char),
454 output_delimiter_length, stdout);
456 print_delimiter = 1;
457 putchar (c);
463 /* Read from stream STREAM, printing to standard output any selected fields. */
465 static void
466 cut_fields (FILE *stream)
468 int c;
469 unsigned int field_idx;
470 int found_any_selected_field;
471 int buffer_first_field;
472 int empty_input;
474 found_any_selected_field = 0;
475 field_idx = 1;
477 c = getc (stream);
478 empty_input = (c == EOF);
479 if (c != EOF)
480 ungetc (c, stream);
482 /* To support the semantics of the -s flag, we may have to buffer
483 all of the first field to determine whether it is `delimited.'
484 But that is unnecessary if all non-delimited lines must be printed
485 and the first field has been selected, or if non-delimited lines
486 must be suppressed and the first field has *not* been selected.
487 That is because a non-delimited line has exactly one field. */
488 buffer_first_field = (suppress_non_delimited ^ !print_kth (1, NULL));
490 while (1)
492 if (field_idx == 1 && buffer_first_field)
494 int len;
495 size_t n_bytes;
497 len = getstr (&field_1_buffer, &field_1_bufsize, stream,
498 delim, '\n', 0);
499 if (len < 0)
501 if (ferror (stream) || feof (stream))
502 break;
503 xalloc_die ();
506 n_bytes = len;
507 assert (n_bytes != 0);
509 /* If the first field extends to the end of line (it is not
510 delimited) and we are printing all non-delimited lines,
511 print this one. */
512 if ((unsigned char) field_1_buffer[n_bytes - 1] != delim)
514 if (suppress_non_delimited)
516 /* Empty. */
518 else
520 fwrite (field_1_buffer, sizeof (char), n_bytes, stdout);
521 /* Make sure the output line is newline terminated. */
522 if (field_1_buffer[n_bytes - 1] != '\n')
523 putchar ('\n');
525 continue;
527 if (print_kth (1, NULL))
529 /* Print the field, but not the trailing delimiter. */
530 fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout);
531 found_any_selected_field = 1;
533 ++field_idx;
536 if (c != EOF)
538 if (print_kth (field_idx, NULL))
540 if (found_any_selected_field)
542 fwrite (output_delimiter_string, sizeof (char),
543 output_delimiter_length, stdout);
545 found_any_selected_field = 1;
547 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
549 putchar (c);
552 else
554 while ((c = getc (stream)) != delim && c != '\n' && c != EOF)
556 /* Empty. */
561 if (c == '\n')
563 c = getc (stream);
564 if (c != EOF)
566 ungetc (c, stream);
567 c = '\n';
571 if (c == delim)
572 ++field_idx;
573 else if (c == '\n' || c == EOF)
575 if (found_any_selected_field
576 || (!empty_input && !(suppress_non_delimited && field_idx == 1)))
577 putchar ('\n');
578 if (c == EOF)
579 break;
580 field_idx = 1;
581 found_any_selected_field = 0;
586 static void
587 cut_stream (FILE *stream)
589 if (operating_mode == byte_mode)
590 cut_bytes (stream);
591 else
592 cut_fields (stream);
595 /* Process file FILE to standard output.
596 Return 0 if successful, 1 if not. */
598 static int
599 cut_file (char *file)
601 FILE *stream;
603 if (STREQ (file, "-"))
605 have_read_stdin = 1;
606 stream = stdin;
608 else
610 stream = fopen (file, "r");
611 if (stream == NULL)
613 error (0, errno, "%s", file);
614 return 1;
618 cut_stream (stream);
620 if (ferror (stream))
622 error (0, errno, "%s", file);
623 return 1;
625 if (STREQ (file, "-"))
626 clearerr (stream); /* Also clear EOF. */
627 else if (fclose (stream) == EOF)
629 error (0, errno, "%s", file);
630 return 1;
632 return 0;
636 main (int argc, char **argv)
638 int optc, exit_status = 0;
639 int delim_specified = 0;
641 program_name = argv[0];
642 setlocale (LC_ALL, "");
643 bindtextdomain (PACKAGE, LOCALEDIR);
644 textdomain (PACKAGE);
646 atexit (close_stdout);
648 operating_mode = undefined_mode;
650 /* By default, all non-delimited lines are printed. */
651 suppress_non_delimited = 0;
653 delim = '\0';
654 have_read_stdin = 0;
656 while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1)
658 switch (optc)
660 case 0:
661 break;
663 case 'b':
664 case 'c':
665 /* Build the byte list. */
666 if (operating_mode != undefined_mode)
667 FATAL_ERROR (_("only one type of list may be specified"));
668 operating_mode = byte_mode;
669 if (set_fields (optarg) == 0)
670 FATAL_ERROR (_("missing list of positions"));
671 break;
673 case 'f':
674 /* Build the field list. */
675 if (operating_mode != undefined_mode)
676 FATAL_ERROR (_("only one type of list may be specified"));
677 operating_mode = field_mode;
678 if (set_fields (optarg) == 0)
679 FATAL_ERROR (_("missing list of fields"));
680 break;
682 case 'd':
683 /* New delimiter. */
684 /* Interpret -d '' to mean `use the NUL byte as the delimiter.' */
685 if (optarg[0] != '\0' && optarg[1] != '\0')
686 FATAL_ERROR (_("the delimiter must be a single character"));
687 delim = (unsigned char) optarg[0];
688 delim_specified = 1;
689 break;
691 case OUTPUT_DELIMITER_OPTION:
692 output_delimiter_specified = 1;
693 /* Interpret --output-delimiter='' to mean
694 `use the NUL byte as the delimiter.' */
695 output_delimiter_length = (optarg[0] == '\0'
696 ? 1 : strlen (optarg));
697 output_delimiter_string = xstrdup (optarg);
698 break;
700 case 'n':
701 break;
703 case 's':
704 suppress_non_delimited = 1;
705 break;
707 case_GETOPT_HELP_CHAR;
709 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
711 default:
712 usage (2);
716 if (operating_mode == undefined_mode)
717 FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
719 if (delim != '\0' && operating_mode != field_mode)
720 FATAL_ERROR (_("an input delimiter may be specified only\
721 when operating on fields"));
723 if (suppress_non_delimited && operating_mode != field_mode)
724 FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
725 \tonly when operating on fields"));
727 if (!delim_specified)
728 delim = '\t';
730 if (output_delimiter_string == NULL)
732 static char dummy[2];
733 dummy[0] = delim;
734 dummy[1] = '\0';
735 output_delimiter_string = dummy;
736 output_delimiter_length = 1;
739 if (optind == argc)
740 exit_status |= cut_file ("-");
741 else
742 for (; optind < argc; optind++)
743 exit_status |= cut_file (argv[optind]);
745 if (have_read_stdin && fclose (stdin) == EOF)
747 error (0, errno, "-");
748 exit_status = 1;
751 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);