ls: --color now highlights hard linked files, too
[coreutils/bo.git] / src / split.c
blob85687c407bb614d339dfe9e1fbd77e00d22072e8
1 /* split.c -- split a file into pieces.
2 Copyright (C) 1988, 1991, 1995-2008 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 /* By tege@sics.se, with rms.
19 To do:
20 * Implement -t CHAR or -t REGEX to specify break characters other
21 than newline. */
23 #include <config.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include <sys/types.h>
29 #include "system.h"
30 #include "error.h"
31 #include "fd-reopen.h"
32 #include "fcntl--.h"
33 #include "full-read.h"
34 #include "full-write.h"
35 #include "quote.h"
36 #include "safe-read.h"
37 #include "xstrtol.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "split"
42 #define AUTHORS \
43 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
44 proper_name ("Richard M. Stallman")
46 #define DEFAULT_SUFFIX_LENGTH 2
48 /* Base name of output files. */
49 static char const *outbase;
51 /* Name of output files. */
52 static char *outfile;
54 /* Pointer to the end of the prefix in OUTFILE.
55 Suffixes are inserted here. */
56 static char *outfile_mid;
58 /* Length of OUTFILE's suffix. */
59 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
61 /* Alphabet of characters to use in suffix. */
62 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
64 /* Name of input file. May be "-". */
65 static char *infile;
67 /* Descriptor on which output file is open. */
68 static int output_desc;
70 /* If true, print a diagnostic on standard error just before each
71 output file is opened. */
72 static bool verbose;
74 /* For long options that have no equivalent short option, use a
75 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
76 enum
78 VERBOSE_OPTION = CHAR_MAX + 1
81 static struct option const longopts[] =
83 {"bytes", required_argument, NULL, 'b'},
84 {"lines", required_argument, NULL, 'l'},
85 {"line-bytes", required_argument, NULL, 'C'},
86 {"suffix-length", required_argument, NULL, 'a'},
87 {"numeric-suffixes", no_argument, NULL, 'd'},
88 {"verbose", no_argument, NULL, VERBOSE_OPTION},
89 {GETOPT_HELP_OPTION_DECL},
90 {GETOPT_VERSION_OPTION_DECL},
91 {NULL, 0, NULL, 0}
94 void
95 usage (int status)
97 if (status != EXIT_SUCCESS)
98 fprintf (stderr, _("Try `%s --help' for more information.\n"),
99 program_name);
100 else
102 printf (_("\
103 Usage: %s [OPTION]... [INPUT [PREFIX]]\n\
105 program_name);
106 fputs (_("\
107 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
108 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
109 is -, read standard input.\n\
111 "), stdout);
112 fputs (_("\
113 Mandatory arguments to long options are mandatory for short options too.\n\
114 "), stdout);
115 fprintf (stdout, _("\
116 -a, --suffix-length=N use suffixes of length N (default %d)\n\
117 -b, --bytes=SIZE put SIZE bytes per output file\n\
118 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
119 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
120 -l, --lines=NUMBER put NUMBER lines per output file\n\
121 "), DEFAULT_SUFFIX_LENGTH);
122 fputs (_("\
123 --verbose print a diagnostic just before each\n\
124 output file is opened\n\
125 "), stdout);
126 fputs (HELP_OPTION_DESCRIPTION, stdout);
127 fputs (VERSION_OPTION_DESCRIPTION, stdout);
128 fputs (_("\
130 SIZE may have a multiplier suffix:\n\
131 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
132 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
133 "), stdout);
134 emit_bug_reporting_address ();
136 exit (status);
139 /* Compute the next sequential output file name and store it into the
140 string `outfile'. */
142 static void
143 next_file_name (void)
145 /* Index in suffix_alphabet of each character in the suffix. */
146 static size_t *sufindex;
148 if (! outfile)
150 /* Allocate and initialize the first file name. */
152 size_t outbase_length = strlen (outbase);
153 size_t outfile_length = outbase_length + suffix_length;
154 if (outfile_length + 1 < outbase_length)
155 xalloc_die ();
156 outfile = xmalloc (outfile_length + 1);
157 outfile_mid = outfile + outbase_length;
158 memcpy (outfile, outbase, outbase_length);
159 memset (outfile_mid, suffix_alphabet[0], suffix_length);
160 outfile[outfile_length] = 0;
161 sufindex = xcalloc (suffix_length, sizeof *sufindex);
163 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
164 /* POSIX requires that if the output file name is too long for
165 its directory, `split' must fail without creating any files.
166 This must be checked for explicitly on operating systems that
167 silently truncate file names. */
169 char *dir = dir_name (outfile);
170 long name_max = pathconf (dir, _PC_NAME_MAX);
171 if (0 <= name_max && name_max < base_len (last_component (outfile)))
172 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
173 free (dir);
175 #endif
177 else
179 /* Increment the suffix in place, if possible. */
181 size_t i = suffix_length;
182 while (i-- != 0)
184 sufindex[i]++;
185 outfile_mid[i] = suffix_alphabet[sufindex[i]];
186 if (outfile_mid[i])
187 return;
188 sufindex[i] = 0;
189 outfile_mid[i] = suffix_alphabet[sufindex[i]];
191 error (EXIT_FAILURE, 0, _("output file suffixes exhausted"));
195 /* Write BYTES bytes at BP to an output file.
196 If NEW_FILE_FLAG is true, open the next output file.
197 Otherwise add to the same output file already in use. */
199 static void
200 cwrite (bool new_file_flag, const char *bp, size_t bytes)
202 if (new_file_flag)
204 if (output_desc >= 0 && close (output_desc) < 0)
205 error (EXIT_FAILURE, errno, "%s", outfile);
207 next_file_name ();
208 if (verbose)
209 fprintf (stdout, _("creating file %s\n"), quote (outfile));
210 output_desc = open (outfile,
211 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
212 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
213 | S_IROTH | S_IWOTH));
214 if (output_desc < 0)
215 error (EXIT_FAILURE, errno, "%s", outfile);
217 if (full_write (output_desc, bp, bytes) != bytes)
218 error (EXIT_FAILURE, errno, "%s", outfile);
221 /* Split into pieces of exactly N_BYTES bytes.
222 Use buffer BUF, whose size is BUFSIZE. */
224 static void
225 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
227 size_t n_read;
228 bool new_file_flag = true;
229 size_t to_read;
230 uintmax_t to_write = n_bytes;
231 char *bp_out;
235 n_read = full_read (STDIN_FILENO, buf, bufsize);
236 if (n_read == SAFE_READ_ERROR)
237 error (EXIT_FAILURE, errno, "%s", infile);
238 bp_out = buf;
239 to_read = n_read;
240 for (;;)
242 if (to_read < to_write)
244 if (to_read) /* do not write 0 bytes! */
246 cwrite (new_file_flag, bp_out, to_read);
247 to_write -= to_read;
248 new_file_flag = false;
250 break;
252 else
254 size_t w = to_write;
255 cwrite (new_file_flag, bp_out, w);
256 bp_out += w;
257 to_read -= w;
258 new_file_flag = true;
259 to_write = n_bytes;
263 while (n_read == bufsize);
266 /* Split into pieces of exactly N_LINES lines.
267 Use buffer BUF, whose size is BUFSIZE. */
269 static void
270 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
272 size_t n_read;
273 char *bp, *bp_out, *eob;
274 bool new_file_flag = true;
275 uintmax_t n = 0;
279 n_read = full_read (STDIN_FILENO, buf, bufsize);
280 if (n_read == SAFE_READ_ERROR)
281 error (EXIT_FAILURE, errno, "%s", infile);
282 bp = bp_out = buf;
283 eob = bp + n_read;
284 *eob = '\n';
285 for (;;)
287 bp = memchr (bp, '\n', eob - bp + 1);
288 if (bp == eob)
290 if (eob != bp_out) /* do not write 0 bytes! */
292 size_t len = eob - bp_out;
293 cwrite (new_file_flag, bp_out, len);
294 new_file_flag = false;
296 break;
299 ++bp;
300 if (++n >= n_lines)
302 cwrite (new_file_flag, bp_out, bp - bp_out);
303 bp_out = bp;
304 new_file_flag = true;
305 n = 0;
309 while (n_read == bufsize);
312 /* Split into pieces that are as large as possible while still not more
313 than N_BYTES bytes, and are split on line boundaries except
314 where lines longer than N_BYTES bytes occur.
315 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
316 buffer of size N_BYTES, in case N_BYTES is very large. */
318 static void
319 line_bytes_split (size_t n_bytes)
321 size_t n_read;
322 char *bp;
323 bool eof = false;
324 size_t n_buffered = 0;
325 char *buf = xmalloc (n_bytes);
329 /* Fill up the full buffer size from the input file. */
331 n_read = full_read (STDIN_FILENO, buf + n_buffered, n_bytes - n_buffered);
332 if (n_read == SAFE_READ_ERROR)
333 error (EXIT_FAILURE, errno, "%s", infile);
335 n_buffered += n_read;
336 if (n_buffered != n_bytes)
338 if (n_buffered == 0)
339 break;
340 eof = true;
343 /* Find where to end this chunk. */
344 bp = buf + n_buffered;
345 if (n_buffered == n_bytes)
347 while (bp > buf && bp[-1] != '\n')
348 bp--;
351 /* If chunk has no newlines, use all the chunk. */
352 if (bp == buf)
353 bp = buf + n_buffered;
355 /* Output the chars as one output file. */
356 cwrite (true, buf, bp - buf);
358 /* Discard the chars we just output; move rest of chunk
359 down to be the start of the next chunk. Source and
360 destination probably overlap. */
361 n_buffered -= bp - buf;
362 if (n_buffered > 0)
363 memmove (buf, bp, n_buffered);
365 while (!eof);
366 free (buf);
369 #define FAIL_ONLY_ONE_WAY() \
370 do \
372 error (0, 0, _("cannot split in more than one way")); \
373 usage (EXIT_FAILURE); \
375 while (0)
378 main (int argc, char **argv)
380 struct stat stat_buf;
381 enum
383 type_undef, type_bytes, type_byteslines, type_lines, type_digits
384 } split_type = type_undef;
385 size_t in_blk_size; /* optimal block size of input file device */
386 char *buf; /* file i/o buffer */
387 size_t page_size = getpagesize ();
388 uintmax_t n_units;
389 static char const multipliers[] = "bEGKkMmPTYZ0";
390 int c;
391 int digits_optind = 0;
393 initialize_main (&argc, &argv);
394 set_program_name (argv[0]);
395 setlocale (LC_ALL, "");
396 bindtextdomain (PACKAGE, LOCALEDIR);
397 textdomain (PACKAGE);
399 atexit (close_stdout);
401 /* Parse command line options. */
403 infile = "-";
404 outbase = "x";
406 while (1)
408 /* This is the argv-index of the option we will read next. */
409 int this_optind = optind ? optind : 1;
411 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
412 if (c == -1)
413 break;
415 switch (c)
417 case 'a':
419 unsigned long tmp;
420 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
421 || SIZE_MAX / sizeof (size_t) < tmp)
423 error (0, 0, _("%s: invalid suffix length"), optarg);
424 usage (EXIT_FAILURE);
426 suffix_length = tmp;
428 break;
430 case 'b':
431 if (split_type != type_undef)
432 FAIL_ONLY_ONE_WAY ();
433 split_type = type_bytes;
434 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
435 || n_units == 0)
437 error (0, 0, _("%s: invalid number of bytes"), optarg);
438 usage (EXIT_FAILURE);
440 break;
442 case 'l':
443 if (split_type != type_undef)
444 FAIL_ONLY_ONE_WAY ();
445 split_type = type_lines;
446 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
447 || n_units == 0)
449 error (0, 0, _("%s: invalid number of lines"), optarg);
450 usage (EXIT_FAILURE);
452 break;
454 case 'C':
455 if (split_type != type_undef)
456 FAIL_ONLY_ONE_WAY ();
457 split_type = type_byteslines;
458 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
459 || n_units == 0 || SIZE_MAX < n_units)
461 error (0, 0, _("%s: invalid number of bytes"), optarg);
462 usage (EXIT_FAILURE);
464 break;
466 case '0':
467 case '1':
468 case '2':
469 case '3':
470 case '4':
471 case '5':
472 case '6':
473 case '7':
474 case '8':
475 case '9':
476 if (split_type == type_undef)
478 split_type = type_digits;
479 n_units = 0;
481 if (split_type != type_undef && split_type != type_digits)
482 FAIL_ONLY_ONE_WAY ();
483 if (digits_optind != 0 && digits_optind != this_optind)
484 n_units = 0; /* More than one number given; ignore other. */
485 digits_optind = this_optind;
486 if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t))
488 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
489 error (EXIT_FAILURE, 0,
490 _("line count option -%s%c... is too large"),
491 umaxtostr (n_units, buffer), c);
493 break;
495 case 'd':
496 suffix_alphabet = "0123456789";
497 break;
499 case VERBOSE_OPTION:
500 verbose = true;
501 break;
503 case_GETOPT_HELP_CHAR;
505 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
507 default:
508 usage (EXIT_FAILURE);
512 /* Handle default case. */
513 if (split_type == type_undef)
515 split_type = type_lines;
516 n_units = 1000;
519 if (n_units == 0)
521 error (0, 0, _("invalid number of lines: 0"));
522 usage (EXIT_FAILURE);
525 /* Get out the filename arguments. */
527 if (optind < argc)
528 infile = argv[optind++];
530 if (optind < argc)
531 outbase = argv[optind++];
533 if (optind < argc)
535 error (0, 0, _("extra operand %s"), quote (argv[optind]));
536 usage (EXIT_FAILURE);
539 /* Open the input file. */
540 if (! STREQ (infile, "-")
541 && fd_reopen (STDIN_FILENO, infile, O_RDONLY, 0) < 0)
542 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
543 quote (infile));
545 /* Binary I/O is safer when bytecounts are used. */
546 if (O_BINARY && ! isatty (STDIN_FILENO))
547 freopen (NULL, "rb", stdin);
549 /* No output file is open now. */
550 output_desc = -1;
552 /* Get the optimal block size of input device and make a buffer. */
554 if (fstat (STDIN_FILENO, &stat_buf) != 0)
555 error (EXIT_FAILURE, errno, "%s", infile);
556 in_blk_size = ST_BLKSIZE (stat_buf);
558 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
560 switch (split_type)
562 case type_digits:
563 case type_lines:
564 lines_split (n_units, buf, in_blk_size);
565 break;
567 case type_bytes:
568 bytes_split (n_units, buf, in_blk_size);
569 break;
571 case type_byteslines:
572 line_bytes_split (n_units);
573 break;
575 default:
576 abort ();
579 if (close (STDIN_FILENO) != 0)
580 error (EXIT_FAILURE, errno, "%s", infile);
581 if (output_desc >= 0 && close (output_desc) < 0)
582 error (EXIT_FAILURE, errno, "%s", outfile);
584 exit (EXIT_SUCCESS);