1 /* split.c -- split a file into pieces.
2 Copyright (C) 88, 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 /* By tege@sics.se, with rms.
21 * Implement -t CHAR or -t REGEX to specify break characters other
28 #include <sys/types.h>
33 #include "getpagesize.h"
34 #include "full-read.h"
35 #include "full-write.h"
39 #include "safe-read.h"
42 /* The official name of this program (e.g., no `g' prefix). */
43 #define PROGRAM_NAME "split"
45 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
47 #define DEFAULT_SUFFIX_LENGTH 2
49 /* The name this program was run with. */
52 /* Base name of output files. */
53 static char const *outbase;
55 /* Name of output files. */
58 /* Pointer to the end of the prefix in OUTFILE.
59 Suffixes are inserted here. */
60 static char *outfile_mid;
62 /* Length of OUTFILE's suffix. */
63 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
65 /* Alphabet of characters to use in suffix. */
66 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
68 /* Name of input file. May be "-". */
71 /* Descriptor on which input file is open. */
72 static int input_desc;
74 /* Descriptor on which output file is open. */
75 static int output_desc;
77 /* If true, print a diagnostic on standard error just before each
78 output file is opened. */
81 /* For long options that have no equivalent short option, use a
82 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
85 VERBOSE_OPTION = CHAR_MAX + 1
88 static struct option const longopts[] =
90 {"bytes", required_argument, NULL, 'b'},
91 {"lines", required_argument, NULL, 'l'},
92 {"line-bytes", required_argument, NULL, 'C'},
93 {"suffix-length", required_argument, NULL, 'a'},
94 {"numeric-suffixes", no_argument, NULL, 'd'},
95 {"verbose", no_argument, NULL, VERBOSE_OPTION},
96 {GETOPT_HELP_OPTION_DECL},
97 {GETOPT_VERSION_OPTION_DECL},
104 if (status != EXIT_SUCCESS)
105 fprintf (stderr, _("Try `%s --help' for more information.\n"),
110 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
114 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
115 PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input.\n\
119 Mandatory arguments to long options are mandatory for short options too.\n\
121 fprintf (stdout, _("\
122 -a, --suffix-length=N use suffixes of length N (default %d)\n\
123 -b, --bytes=SIZE put SIZE bytes per output file\n\
124 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
125 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
126 -l, --lines=NUMBER put NUMBER lines per output file\n\
127 "), DEFAULT_SUFFIX_LENGTH);
129 --verbose print a diagnostic to standard error just\n\
130 before each output file is opened\n\
132 fputs (HELP_OPTION_DESCRIPTION, stdout);
133 fputs (VERSION_OPTION_DESCRIPTION, stdout);
136 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
138 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
143 /* Compute the next sequential output file name and store it into the
147 next_file_name (void)
149 /* Index in suffix_alphabet of each character in the suffix. */
150 static size_t *sufindex;
154 /* Allocate and initialize the first file name. */
156 size_t outbase_length = strlen (outbase);
157 size_t outfile_length = outbase_length + suffix_length;
158 if (outfile_length + 1 < outbase_length)
160 outfile = xmalloc (outfile_length + 1);
161 outfile_mid = outfile + outbase_length;
162 memcpy (outfile, outbase, outbase_length);
163 memset (outfile_mid, suffix_alphabet[0], suffix_length);
164 outfile[outfile_length] = 0;
165 sufindex = xcalloc (suffix_length, sizeof *sufindex);
167 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
168 /* POSIX requires that if the output file name is too long for
169 its directory, `split' must fail without creating any files.
170 This must be checked for explicitly on operating systems that
171 silently truncate file names. */
173 char *dir = dir_name (outfile);
174 long name_max = pathconf (dir, _PC_NAME_MAX);
175 if (0 <= name_max && name_max < base_len (base_name (outfile)))
176 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
183 /* Increment the suffix in place, if possible. */
185 size_t i = suffix_length;
189 outfile_mid[i] = suffix_alphabet[sufindex[i]];
193 outfile_mid[i] = suffix_alphabet[sufindex[i]];
195 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
199 /* Write BYTES bytes at BP to an output file.
200 If NEW_FILE_FLAG is true, open the next output file.
201 Otherwise add to the same output file already in use. */
204 cwrite (bool new_file_flag, const char *bp, size_t bytes)
208 if (output_desc >= 0 && close (output_desc) < 0)
209 error (EXIT_FAILURE, errno, "%s", outfile);
213 fprintf (stderr, _("creating file `%s'\n"), outfile);
214 output_desc = open (outfile,
215 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
217 error (EXIT_FAILURE, errno, "%s", outfile);
219 if (full_write (output_desc, bp, bytes) != bytes)
220 error (EXIT_FAILURE, errno, "%s", outfile);
223 /* Split into pieces of exactly N_BYTES bytes.
224 Use buffer BUF, whose size is BUFSIZE. */
227 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
230 bool new_file_flag = true;
232 uintmax_t to_write = n_bytes;
237 n_read = full_read (input_desc, buf, bufsize);
238 if (n_read == SAFE_READ_ERROR)
239 error (EXIT_FAILURE, errno, "%s", infile);
244 if (to_read < to_write)
246 if (to_read) /* do not write 0 bytes! */
248 cwrite (new_file_flag, bp_out, to_read);
250 new_file_flag = false;
257 cwrite (new_file_flag, bp_out, w);
260 new_file_flag = true;
265 while (n_read == bufsize);
268 /* Split into pieces of exactly N_LINES lines.
269 Use buffer BUF, whose size is BUFSIZE. */
272 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
275 char *bp, *bp_out, *eob;
276 bool new_file_flag = true;
281 n_read = full_read (input_desc, buf, bufsize);
282 if (n_read == SAFE_READ_ERROR)
283 error (EXIT_FAILURE, errno, "%s", infile);
289 bp = memchr (bp, '\n', eob - bp + 1);
292 if (eob != bp_out) /* do not write 0 bytes! */
294 size_t len = eob - bp_out;
295 cwrite (new_file_flag, bp_out, len);
296 new_file_flag = false;
304 cwrite (new_file_flag, bp_out, bp - bp_out);
306 new_file_flag = true;
311 while (n_read == bufsize);
314 /* Split into pieces that are as large as possible while still not more
315 than N_BYTES bytes, and are split on line boundaries except
316 where lines longer than N_BYTES bytes occur.
317 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
318 buffer of size N_BYTES, in case N_BYTES is very large. */
321 line_bytes_split (size_t n_bytes)
326 size_t n_buffered = 0;
327 char *buf = xmalloc (n_bytes);
331 /* Fill up the full buffer size from the input file. */
333 n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
334 if (n_read == SAFE_READ_ERROR)
335 error (EXIT_FAILURE, errno, "%s", infile);
337 n_buffered += n_read;
338 if (n_buffered != n_bytes)
341 /* Find where to end this chunk. */
342 bp = buf + n_buffered;
343 if (n_buffered == n_bytes)
345 while (bp > buf && bp[-1] != '\n')
349 /* If chunk has no newlines, use all the chunk. */
351 bp = buf + n_buffered;
353 /* Output the chars as one output file. */
354 cwrite (true, buf, bp - buf);
356 /* Discard the chars we just output; move rest of chunk
357 down to be the start of the next chunk. Source and
358 destination probably overlap. */
359 n_buffered -= bp - buf;
361 memmove (buf, bp, n_buffered);
367 #define FAIL_ONLY_ONE_WAY() \
370 error (0, 0, _("cannot split in more than one way")); \
371 usage (EXIT_FAILURE); \
376 main (int argc, char **argv)
378 struct stat stat_buf;
381 type_undef, type_bytes, type_byteslines, type_lines, type_digits
382 } split_type = type_undef;
383 size_t in_blk_size; /* optimal block size of input file device */
384 char *buf; /* file i/o buffer */
385 size_t page_size = getpagesize ();
388 int digits_optind = 0;
390 initialize_main (&argc, &argv);
391 program_name = argv[0];
392 setlocale (LC_ALL, "");
393 bindtextdomain (PACKAGE, LOCALEDIR);
394 textdomain (PACKAGE);
396 atexit (close_stdout);
398 /* Parse command line options. */
405 /* This is the argv-index of the option we will read next. */
406 int this_optind = optind ? optind : 1;
408 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
417 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
418 || SIZE_MAX / sizeof (size_t) < tmp)
420 error (0, 0, _("%s: invalid suffix length"), optarg);
421 usage (EXIT_FAILURE);
428 if (split_type != type_undef)
429 FAIL_ONLY_ONE_WAY ();
430 split_type = type_bytes;
431 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
434 error (0, 0, _("%s: invalid number of bytes"), optarg);
435 usage (EXIT_FAILURE);
440 if (split_type != type_undef)
441 FAIL_ONLY_ONE_WAY ();
442 split_type = type_lines;
443 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
446 error (0, 0, _("%s: invalid number of lines"), optarg);
447 usage (EXIT_FAILURE);
452 if (split_type != type_undef)
453 FAIL_ONLY_ONE_WAY ();
454 split_type = type_byteslines;
455 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
456 || n_units == 0 || SIZE_MAX < n_units)
458 error (0, 0, _("%s: invalid number of bytes"), optarg);
459 usage (EXIT_FAILURE);
473 if (split_type == type_undef)
475 split_type = type_digits;
478 if (split_type != type_undef && split_type != type_digits)
479 FAIL_ONLY_ONE_WAY ();
480 if (digits_optind != 0 && digits_optind != this_optind)
481 n_units = 0; /* More than one number given; ignore other. */
482 digits_optind = this_optind;
483 if (UINTMAX_MAX / 10 < n_units
484 || n_units * 10 + c - '0' < n_units * 10)
486 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
487 error (EXIT_FAILURE, 0,
488 _("line count option -%s%c... is too large"),
489 umaxtostr (n_units, buffer), c);
491 n_units = n_units * 10 + c - '0';
495 suffix_alphabet = "0123456789";
502 case_GETOPT_HELP_CHAR;
504 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
507 usage (EXIT_FAILURE);
511 if (digits_optind && 200112 <= posix2_version ())
513 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
514 char const *a = umaxtostr (n_units, buffer);
515 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
516 usage (EXIT_FAILURE);
519 /* Handle default case. */
520 if (split_type == type_undef)
522 split_type = type_lines;
528 /* FIXME: be sure to remove this block when removing
529 support for obsolete options like `-10'. */
530 error (0, 0, _("invalid number of lines: 0"));
531 usage (EXIT_FAILURE);
534 /* Get out the filename arguments. */
537 infile = argv[optind++];
540 outbase = argv[optind++];
544 error (0, 0, _("extra operand %s"), quote (argv[optind]));
545 usage (EXIT_FAILURE);
548 /* Open the input file. */
549 if (STREQ (infile, "-"))
550 input_desc = STDIN_FILENO;
553 input_desc = open (infile, O_RDONLY);
555 error (EXIT_FAILURE, errno, "%s", infile);
557 /* Binary I/O is safer when bytecounts are used. */
558 SET_BINARY (input_desc);
560 /* No output file is open now. */
563 /* Get the optimal block size of input device and make a buffer. */
565 if (fstat (input_desc, &stat_buf) < 0)
566 error (EXIT_FAILURE, errno, "%s", infile);
567 in_blk_size = ST_BLKSIZE (stat_buf);
569 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
575 lines_split (n_units, buf, in_blk_size);
579 bytes_split (n_units, buf, in_blk_size);
582 case type_byteslines:
583 line_bytes_split (n_units);
590 if (close (input_desc) < 0)
591 error (EXIT_FAILURE, errno, "%s", infile);
592 if (output_desc >= 0 && close (output_desc) < 0)
593 error (EXIT_FAILURE, errno, "%s", outfile);