1 /* split.c -- split a file into pieces.
2 Copyright (C) 88, 91, 1995-2005 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"
40 #include "unistd-safer.h"
43 /* The official name of this program (e.g., no `g' prefix). */
44 #define PROGRAM_NAME "split"
46 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
48 #define DEFAULT_SUFFIX_LENGTH 2
50 /* The name this program was run with. */
53 /* Base name of output files. */
54 static char const *outbase;
56 /* Name of output files. */
59 /* Pointer to the end of the prefix in OUTFILE.
60 Suffixes are inserted here. */
61 static char *outfile_mid;
63 /* Length of OUTFILE's suffix. */
64 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
66 /* Alphabet of characters to use in suffix. */
67 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
69 /* Name of input file. May be "-". */
72 /* Descriptor on which input file is open. */
73 static int input_desc;
75 /* Descriptor on which output file is open. */
76 static int output_desc;
78 /* If true, print a diagnostic on standard error just before each
79 output file is opened. */
82 /* For long options that have no equivalent short option, use a
83 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
86 VERBOSE_OPTION = CHAR_MAX + 1
89 static struct option const longopts[] =
91 {"bytes", required_argument, NULL, 'b'},
92 {"lines", required_argument, NULL, 'l'},
93 {"line-bytes", required_argument, NULL, 'C'},
94 {"suffix-length", required_argument, NULL, 'a'},
95 {"numeric-suffixes", no_argument, NULL, 'd'},
96 {"verbose", no_argument, NULL, VERBOSE_OPTION},
97 {GETOPT_HELP_OPTION_DECL},
98 {GETOPT_VERSION_OPTION_DECL},
105 if (status != EXIT_SUCCESS)
106 fprintf (stderr, _("Try `%s --help' for more information.\n"),
111 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
115 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
116 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
117 is -, read standard input.\n\
121 Mandatory arguments to long options are mandatory for short options too.\n\
123 fprintf (stdout, _("\
124 -a, --suffix-length=N use suffixes of length N (default %d)\n\
125 -b, --bytes=SIZE put SIZE bytes per output file\n\
126 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
127 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
128 -l, --lines=NUMBER put NUMBER lines per output file\n\
129 "), DEFAULT_SUFFIX_LENGTH);
131 --verbose print a diagnostic to standard error just\n\
132 before each output file is opened\n\
134 fputs (HELP_OPTION_DESCRIPTION, stdout);
135 fputs (VERSION_OPTION_DESCRIPTION, stdout);
138 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
140 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
145 /* Compute the next sequential output file name and store it into the
149 next_file_name (void)
151 /* Index in suffix_alphabet of each character in the suffix. */
152 static size_t *sufindex;
156 /* Allocate and initialize the first file name. */
158 size_t outbase_length = strlen (outbase);
159 size_t outfile_length = outbase_length + suffix_length;
160 if (outfile_length + 1 < outbase_length)
162 outfile = xmalloc (outfile_length + 1);
163 outfile_mid = outfile + outbase_length;
164 memcpy (outfile, outbase, outbase_length);
165 memset (outfile_mid, suffix_alphabet[0], suffix_length);
166 outfile[outfile_length] = 0;
167 sufindex = xcalloc (suffix_length, sizeof *sufindex);
169 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
170 /* POSIX requires that if the output file name is too long for
171 its directory, `split' must fail without creating any files.
172 This must be checked for explicitly on operating systems that
173 silently truncate file names. */
175 char *dir = dir_name (outfile);
176 long name_max = pathconf (dir, _PC_NAME_MAX);
177 if (0 <= name_max && name_max < base_len (base_name (outfile)))
178 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
185 /* Increment the suffix in place, if possible. */
187 size_t i = suffix_length;
191 outfile_mid[i] = suffix_alphabet[sufindex[i]];
195 outfile_mid[i] = suffix_alphabet[sufindex[i]];
197 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
201 /* Write BYTES bytes at BP to an output file.
202 If NEW_FILE_FLAG is true, open the next output file.
203 Otherwise add to the same output file already in use. */
206 cwrite (bool new_file_flag, const char *bp, size_t bytes)
210 if (output_desc >= 0 && close (output_desc) < 0)
211 error (EXIT_FAILURE, errno, "%s", outfile);
215 fprintf (stderr, _("creating file `%s'\n"), outfile);
216 output_desc = fd_safer (open (outfile,
217 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
218 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
219 | S_IROTH | S_IWOTH)));
221 error (EXIT_FAILURE, errno, "%s", outfile);
223 if (full_write (output_desc, bp, bytes) != bytes)
224 error (EXIT_FAILURE, errno, "%s", outfile);
227 /* Split into pieces of exactly N_BYTES bytes.
228 Use buffer BUF, whose size is BUFSIZE. */
231 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
234 bool new_file_flag = true;
236 uintmax_t to_write = n_bytes;
241 n_read = full_read (input_desc, buf, bufsize);
242 if (n_read == SAFE_READ_ERROR)
243 error (EXIT_FAILURE, errno, "%s", infile);
248 if (to_read < to_write)
250 if (to_read) /* do not write 0 bytes! */
252 cwrite (new_file_flag, bp_out, to_read);
254 new_file_flag = false;
261 cwrite (new_file_flag, bp_out, w);
264 new_file_flag = true;
269 while (n_read == bufsize);
272 /* Split into pieces of exactly N_LINES lines.
273 Use buffer BUF, whose size is BUFSIZE. */
276 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
279 char *bp, *bp_out, *eob;
280 bool new_file_flag = true;
285 n_read = full_read (input_desc, buf, bufsize);
286 if (n_read == SAFE_READ_ERROR)
287 error (EXIT_FAILURE, errno, "%s", infile);
293 bp = memchr (bp, '\n', eob - bp + 1);
296 if (eob != bp_out) /* do not write 0 bytes! */
298 size_t len = eob - bp_out;
299 cwrite (new_file_flag, bp_out, len);
300 new_file_flag = false;
308 cwrite (new_file_flag, bp_out, bp - bp_out);
310 new_file_flag = true;
315 while (n_read == bufsize);
318 /* Split into pieces that are as large as possible while still not more
319 than N_BYTES bytes, and are split on line boundaries except
320 where lines longer than N_BYTES bytes occur.
321 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
322 buffer of size N_BYTES, in case N_BYTES is very large. */
325 line_bytes_split (size_t n_bytes)
330 size_t n_buffered = 0;
331 char *buf = xmalloc (n_bytes);
335 /* Fill up the full buffer size from the input file. */
337 n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
338 if (n_read == SAFE_READ_ERROR)
339 error (EXIT_FAILURE, errno, "%s", infile);
341 n_buffered += n_read;
342 if (n_buffered != n_bytes)
345 /* Find where to end this chunk. */
346 bp = buf + n_buffered;
347 if (n_buffered == n_bytes)
349 while (bp > buf && bp[-1] != '\n')
353 /* If chunk has no newlines, use all the chunk. */
355 bp = buf + n_buffered;
357 /* Output the chars as one output file. */
358 cwrite (true, buf, bp - buf);
360 /* Discard the chars we just output; move rest of chunk
361 down to be the start of the next chunk. Source and
362 destination probably overlap. */
363 n_buffered -= bp - buf;
365 memmove (buf, bp, n_buffered);
371 #define FAIL_ONLY_ONE_WAY() \
374 error (0, 0, _("cannot split in more than one way")); \
375 usage (EXIT_FAILURE); \
380 main (int argc, char **argv)
382 struct stat stat_buf;
385 type_undef, type_bytes, type_byteslines, type_lines, type_digits
386 } split_type = type_undef;
387 size_t in_blk_size; /* optimal block size of input file device */
388 char *buf; /* file i/o buffer */
389 size_t page_size = getpagesize ();
392 int digits_optind = 0;
394 initialize_main (&argc, &argv);
395 program_name = argv[0];
396 setlocale (LC_ALL, "");
397 bindtextdomain (PACKAGE, LOCALEDIR);
398 textdomain (PACKAGE);
400 atexit (close_stdout);
402 /* Parse command line options. */
409 /* This is the argv-index of the option we will read next. */
410 int this_optind = optind ? optind : 1;
412 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
421 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
422 || SIZE_MAX / sizeof (size_t) < tmp)
424 error (0, 0, _("%s: invalid suffix length"), optarg);
425 usage (EXIT_FAILURE);
432 if (split_type != type_undef)
433 FAIL_ONLY_ONE_WAY ();
434 split_type = type_bytes;
435 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
438 error (0, 0, _("%s: invalid number of bytes"), optarg);
439 usage (EXIT_FAILURE);
444 if (split_type != type_undef)
445 FAIL_ONLY_ONE_WAY ();
446 split_type = type_lines;
447 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
450 error (0, 0, _("%s: invalid number of lines"), optarg);
451 usage (EXIT_FAILURE);
456 if (split_type != type_undef)
457 FAIL_ONLY_ONE_WAY ();
458 split_type = type_byteslines;
459 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
460 || n_units == 0 || SIZE_MAX < n_units)
462 error (0, 0, _("%s: invalid number of bytes"), optarg);
463 usage (EXIT_FAILURE);
477 if (split_type == type_undef)
479 split_type = type_digits;
482 if (split_type != type_undef && split_type != type_digits)
483 FAIL_ONLY_ONE_WAY ();
484 if (digits_optind != 0 && digits_optind != this_optind)
485 n_units = 0; /* More than one number given; ignore other. */
486 digits_optind = this_optind;
487 if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', UINTMAX_MAX))
489 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
490 error (EXIT_FAILURE, 0,
491 _("line count option -%s%c... is too large"),
492 umaxtostr (n_units, buffer), c);
497 suffix_alphabet = "0123456789";
504 case_GETOPT_HELP_CHAR;
506 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
509 usage (EXIT_FAILURE);
513 if (digits_optind && 200112 <= posix2_version ())
515 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
516 char const *a = umaxtostr (n_units, buffer);
517 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
518 usage (EXIT_FAILURE);
521 /* Handle default case. */
522 if (split_type == type_undef)
524 split_type = type_lines;
530 /* FIXME: be sure to remove this block when removing
531 support for obsolete options like `-10'. */
532 error (0, 0, _("invalid number of lines: 0"));
533 usage (EXIT_FAILURE);
536 /* Get out the filename arguments. */
539 infile = argv[optind++];
542 outbase = argv[optind++];
546 error (0, 0, _("extra operand %s"), quote (argv[optind]));
547 usage (EXIT_FAILURE);
550 /* Open the input file. */
551 if (STREQ (infile, "-"))
552 input_desc = STDIN_FILENO;
555 input_desc = open (infile, O_RDONLY);
557 error (EXIT_FAILURE, errno, "%s", infile);
559 /* Binary I/O is safer when bytecounts are used. */
560 SET_BINARY (input_desc);
562 /* No output file is open now. */
565 /* Get the optimal block size of input device and make a buffer. */
567 if (fstat (input_desc, &stat_buf) < 0)
568 error (EXIT_FAILURE, errno, "%s", infile);
569 in_blk_size = ST_BLKSIZE (stat_buf);
571 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
577 lines_split (n_units, buf, in_blk_size);
581 bytes_split (n_units, buf, in_blk_size);
584 case type_byteslines:
585 line_bytes_split (n_units);
592 if (close (input_desc) < 0)
593 error (EXIT_FAILURE, errno, "%s", infile);
594 if (output_desc >= 0 && close (output_desc) < 0)
595 error (EXIT_FAILURE, errno, "%s", outfile);