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"
38 #include "safe-read.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "split"
44 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
46 #define DEFAULT_SUFFIX_LENGTH 2
48 /* The name this program was run with. */
51 /* Base name of output files. */
52 static char const *outbase;
54 /* Name of output files. */
57 /* Pointer to the end of the prefix in OUTFILE.
58 Suffixes are inserted here. */
59 static char *outfile_mid;
61 /* Length of OUTFILE's suffix. */
62 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
64 /* Alphabet of characters to use in suffix. */
65 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
67 /* Name of input file. May be "-". */
70 /* Descriptor on which input file is open. */
71 static int input_desc;
73 /* Descriptor on which output file is open. */
74 static int output_desc;
76 /* If nonzero, print a diagnostic on standard error just before each
77 output file is opened. */
80 static struct option const longopts[] =
82 {"bytes", required_argument, NULL, 'b'},
83 {"lines", required_argument, NULL, 'l'},
84 {"line-bytes", required_argument, NULL, 'C'},
85 {"suffix-length", required_argument, NULL, 'a'},
86 {"numeric-suffixes", no_argument, NULL, 'd'},
87 {"verbose", no_argument, &verbose, 1},
88 {GETOPT_HELP_OPTION_DECL},
89 {GETOPT_VERSION_OPTION_DECL},
96 if (status != EXIT_SUCCESS)
97 fprintf (stderr, _("Try `%s --help' for more information.\n"),
102 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
106 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
107 PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input.\n\
111 Mandatory arguments to long options are mandatory for short options too.\n\
113 fprintf (stdout, _("\
114 -a, --suffix-length=N use suffixes of length N (default %d)\n\
115 -b, --bytes=SIZE put SIZE bytes per output file\n\
116 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
117 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
118 -l, --lines=NUMBER put NUMBER lines per output file\n\
119 "), DEFAULT_SUFFIX_LENGTH);
121 --verbose print a diagnostic to standard error just\n\
122 before each output file is opened\n\
124 fputs (HELP_OPTION_DESCRIPTION, stdout);
125 fputs (VERSION_OPTION_DESCRIPTION, stdout);
128 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
130 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
135 /* Compute the next sequential output file name and store it into the
139 next_file_name (void)
141 /* Index in suffix_alphabet of each character in the suffix. */
142 static size_t *sufindex;
146 /* Allocate and initialize the first file name. */
148 size_t outbase_length = strlen (outbase);
149 size_t outfile_length = outbase_length + suffix_length;
150 if (outfile_length + 1 < outbase_length)
152 outfile = xmalloc (outfile_length + 1);
153 outfile_mid = outfile + outbase_length;
154 memcpy (outfile, outbase, outbase_length);
155 memset (outfile_mid, suffix_alphabet[0], suffix_length);
156 outfile[outfile_length] = 0;
157 sufindex = xcalloc (suffix_length, sizeof *sufindex);
159 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
160 /* POSIX requires that if the output file name is too long for
161 its directory, `split' must fail without creating any files.
162 This must be checked for explicitly on operating systems that
163 silently truncate file names. */
165 char *dir = dir_name (outfile);
166 long name_max = pathconf (dir, _PC_NAME_MAX);
167 if (0 <= name_max && name_max < base_len (base_name (outfile)))
168 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
175 /* Increment the suffix in place, if possible. */
177 size_t i = suffix_length;
181 outfile_mid[i] = suffix_alphabet[sufindex[i]];
185 outfile_mid[i] = suffix_alphabet[sufindex[i]];
187 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
191 /* Write BYTES bytes at BP to an output file.
192 If NEW_FILE_FLAG is nonzero, open the next output file.
193 Otherwise add to the same output file already in use. */
196 cwrite (int new_file_flag, const char *bp, size_t bytes)
200 if (output_desc >= 0 && close (output_desc) < 0)
201 error (EXIT_FAILURE, errno, "%s", outfile);
205 fprintf (stderr, _("creating file `%s'\n"), outfile);
206 output_desc = open (outfile,
207 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
209 error (EXIT_FAILURE, errno, "%s", outfile);
211 if (full_write (output_desc, bp, bytes) != bytes)
212 error (EXIT_FAILURE, errno, "%s", outfile);
215 /* Split into pieces of exactly N_BYTES bytes.
216 Use buffer BUF, whose size is BUFSIZE. */
219 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
222 int new_file_flag = 1;
224 uintmax_t to_write = n_bytes;
229 n_read = full_read (input_desc, buf, bufsize);
230 if (n_read == SAFE_READ_ERROR)
231 error (EXIT_FAILURE, errno, "%s", infile);
236 if (to_read < to_write)
238 if (to_read) /* do not write 0 bytes! */
240 cwrite (new_file_flag, bp_out, to_read);
249 cwrite (new_file_flag, bp_out, w);
257 while (n_read == bufsize);
260 /* Split into pieces of exactly N_LINES lines.
261 Use buffer BUF, whose size is BUFSIZE. */
264 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
267 char *bp, *bp_out, *eob;
268 int new_file_flag = 1;
273 n_read = full_read (input_desc, buf, bufsize);
274 if (n_read == SAFE_READ_ERROR)
275 error (EXIT_FAILURE, errno, "%s", infile);
281 bp = memchr (bp, '\n', eob - bp + 1);
284 if (eob != bp_out) /* do not write 0 bytes! */
286 size_t len = eob - bp_out;
287 cwrite (new_file_flag, bp_out, len);
296 cwrite (new_file_flag, bp_out, bp - bp_out);
303 while (n_read == bufsize);
306 /* Split into pieces that are as large as possible while still not more
307 than N_BYTES bytes, and are split on line boundaries except
308 where lines longer than N_BYTES bytes occur.
309 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
310 buffer of size N_BYTES, in case N_BYTES is very large. */
313 line_bytes_split (size_t n_bytes)
318 size_t n_buffered = 0;
319 char *buf = xmalloc (n_bytes);
323 /* Fill up the full buffer size from the input file. */
325 n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
326 if (n_read == SAFE_READ_ERROR)
327 error (EXIT_FAILURE, errno, "%s", infile);
329 n_buffered += n_read;
330 if (n_buffered != n_bytes)
333 /* Find where to end this chunk. */
334 bp = buf + n_buffered;
335 if (n_buffered == n_bytes)
337 while (bp > buf && bp[-1] != '\n')
341 /* If chunk has no newlines, use all the chunk. */
343 bp = buf + n_buffered;
345 /* Output the chars as one output file. */
346 cwrite (1, buf, bp - buf);
348 /* Discard the chars we just output; move rest of chunk
349 down to be the start of the next chunk. Source and
350 destination probably overlap. */
351 n_buffered -= bp - buf;
353 memmove (buf, bp, n_buffered);
359 #define FAIL_ONLY_ONE_WAY() \
362 error (0, 0, _("cannot split in more than one way")); \
363 usage (EXIT_FAILURE); \
368 main (int argc, char **argv)
370 struct stat stat_buf;
373 type_undef, type_bytes, type_byteslines, type_lines, type_digits
374 } split_type = type_undef;
375 size_t in_blk_size; /* optimal block size of input file device */
376 char *buf; /* file i/o buffer */
377 size_t page_size = getpagesize ();
380 int digits_optind = 0;
382 initialize_main (&argc, &argv);
383 program_name = argv[0];
384 setlocale (LC_ALL, "");
385 bindtextdomain (PACKAGE, LOCALEDIR);
386 textdomain (PACKAGE);
388 atexit (close_stdout);
390 /* Parse command line options. */
397 /* This is the argv-index of the option we will read next. */
398 int this_optind = optind ? optind : 1;
400 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
412 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
413 || SIZE_MAX / sizeof (size_t) < tmp)
415 error (0, 0, _("%s: invalid suffix length"), optarg);
416 usage (EXIT_FAILURE);
423 if (split_type != type_undef)
424 FAIL_ONLY_ONE_WAY ();
425 split_type = type_bytes;
426 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
429 error (0, 0, _("%s: invalid number of bytes"), optarg);
430 usage (EXIT_FAILURE);
435 if (split_type != type_undef)
436 FAIL_ONLY_ONE_WAY ();
437 split_type = type_lines;
438 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
441 error (0, 0, _("%s: invalid number of lines"), optarg);
442 usage (EXIT_FAILURE);
447 if (split_type != type_undef)
448 FAIL_ONLY_ONE_WAY ();
449 split_type = type_byteslines;
450 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
451 || n_units == 0 || SIZE_MAX < n_units)
453 error (0, 0, _("%s: invalid number of bytes"), optarg);
454 usage (EXIT_FAILURE);
468 if (split_type == type_undef)
470 split_type = type_digits;
473 if (split_type != type_undef && split_type != type_digits)
474 FAIL_ONLY_ONE_WAY ();
475 if (digits_optind != 0 && digits_optind != this_optind)
476 n_units = 0; /* More than one number given; ignore other. */
477 digits_optind = this_optind;
478 if (UINTMAX_MAX / 10 < n_units
479 || n_units * 10 + c - '0' < n_units * 10)
481 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
482 error (EXIT_FAILURE, 0,
483 _("line count option -%s%c... is too large"),
484 umaxtostr (n_units, buffer), c);
486 n_units = n_units * 10 + c - '0';
490 suffix_alphabet = "0123456789";
493 case_GETOPT_HELP_CHAR;
495 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
498 usage (EXIT_FAILURE);
502 if (digits_optind && 200112 <= posix2_version ())
504 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
505 char const *a = umaxtostr (n_units, buffer);
506 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
507 usage (EXIT_FAILURE);
510 /* Handle default case. */
511 if (split_type == type_undef)
513 split_type = type_lines;
519 /* FIXME: be sure to remove this block when removing
520 support for obsolete options like `-10'. */
521 error (0, 0, _("invalid number of lines: 0"));
522 usage (EXIT_FAILURE);
525 /* Get out the filename arguments. */
528 infile = argv[optind++];
531 outbase = argv[optind++];
535 error (0, 0, _("too many arguments"));
536 usage (EXIT_FAILURE);
539 /* Open the input file. */
540 if (STREQ (infile, "-"))
541 input_desc = STDIN_FILENO;
544 input_desc = open (infile, O_RDONLY);
546 error (EXIT_FAILURE, errno, "%s", infile);
548 /* Binary I/O is safer when bytecounts are used. */
549 SET_BINARY (input_desc);
551 /* No output file is open now. */
554 /* Get the optimal block size of input device and make a buffer. */
556 if (fstat (input_desc, &stat_buf) < 0)
557 error (EXIT_FAILURE, errno, "%s", infile);
558 in_blk_size = ST_BLKSIZE (stat_buf);
560 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
566 lines_split (n_units, buf, in_blk_size);
570 bytes_split (n_units, buf, in_blk_size);
573 case type_byteslines:
574 line_bytes_split (n_units);
581 if (close (input_desc) < 0)
582 error (EXIT_FAILURE, errno, "%s", infile);
583 if (output_desc >= 0 && close (output_desc) < 0)
584 error (EXIT_FAILURE, errno, "%s", outfile);