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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 "fd-reopen.h"
35 #include "getpagesize.h"
36 #include "full-read.h"
37 #include "full-write.h"
40 #include "safe-read.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 output file is open. */
73 static int output_desc;
75 /* If true, print a diagnostic on standard error just before each
76 output file is opened. */
79 /* For long options that have no equivalent short option, use a
80 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
83 VERBOSE_OPTION = CHAR_MAX + 1
86 static struct option const longopts[] =
88 {"bytes", required_argument, NULL, 'b'},
89 {"lines", required_argument, NULL, 'l'},
90 {"line-bytes", required_argument, NULL, 'C'},
91 {"suffix-length", required_argument, NULL, 'a'},
92 {"numeric-suffixes", no_argument, NULL, 'd'},
93 {"verbose", no_argument, NULL, VERBOSE_OPTION},
94 {GETOPT_HELP_OPTION_DECL},
95 {GETOPT_VERSION_OPTION_DECL},
102 if (status != EXIT_SUCCESS)
103 fprintf (stderr, _("Try `%s --help' for more information.\n"),
108 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
112 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
113 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
114 is -, read standard input.\n\
118 Mandatory arguments to long options are mandatory for short options too.\n\
120 fprintf (stdout, _("\
121 -a, --suffix-length=N use suffixes of length N (default %d)\n\
122 -b, --bytes=SIZE put SIZE bytes per output file\n\
123 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
124 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
125 -l, --lines=NUMBER put NUMBER lines per output file\n\
126 "), DEFAULT_SUFFIX_LENGTH);
128 --verbose print a diagnostic to standard error just\n\
129 before each output file is opened\n\
131 fputs (HELP_OPTION_DESCRIPTION, stdout);
132 fputs (VERSION_OPTION_DESCRIPTION, stdout);
135 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
137 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
142 /* Compute the next sequential output file name and store it into the
146 next_file_name (void)
148 /* Index in suffix_alphabet of each character in the suffix. */
149 static size_t *sufindex;
153 /* Allocate and initialize the first file name. */
155 size_t outbase_length = strlen (outbase);
156 size_t outfile_length = outbase_length + suffix_length;
157 if (outfile_length + 1 < outbase_length)
159 outfile = xmalloc (outfile_length + 1);
160 outfile_mid = outfile + outbase_length;
161 memcpy (outfile, outbase, outbase_length);
162 memset (outfile_mid, suffix_alphabet[0], suffix_length);
163 outfile[outfile_length] = 0;
164 sufindex = xcalloc (suffix_length, sizeof *sufindex);
166 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
167 /* POSIX requires that if the output file name is too long for
168 its directory, `split' must fail without creating any files.
169 This must be checked for explicitly on operating systems that
170 silently truncate file names. */
172 char *dir = dir_name (outfile);
173 long name_max = pathconf (dir, _PC_NAME_MAX);
174 if (0 <= name_max && name_max < base_len (base_name (outfile)))
175 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
182 /* Increment the suffix in place, if possible. */
184 size_t i = suffix_length;
188 outfile_mid[i] = suffix_alphabet[sufindex[i]];
192 outfile_mid[i] = suffix_alphabet[sufindex[i]];
194 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
198 /* Write BYTES bytes at BP to an output file.
199 If NEW_FILE_FLAG is true, open the next output file.
200 Otherwise add to the same output file already in use. */
203 cwrite (bool new_file_flag, const char *bp, size_t bytes)
207 if (output_desc >= 0 && close (output_desc) < 0)
208 error (EXIT_FAILURE, errno, "%s", outfile);
212 fprintf (stderr, _("creating file %s\n"), quote (outfile));
213 output_desc = open (outfile,
214 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
215 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
216 | S_IROTH | S_IWOTH));
218 error (EXIT_FAILURE, errno, "%s", outfile);
220 if (full_write (output_desc, bp, bytes) != bytes)
221 error (EXIT_FAILURE, errno, "%s", outfile);
224 /* Split into pieces of exactly N_BYTES bytes.
225 Use buffer BUF, whose size is BUFSIZE. */
228 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
231 bool new_file_flag = true;
233 uintmax_t to_write = n_bytes;
238 n_read = full_read (STDIN_FILENO, buf, bufsize);
239 if (n_read == SAFE_READ_ERROR)
240 error (EXIT_FAILURE, errno, "%s", infile);
245 if (to_read < to_write)
247 if (to_read) /* do not write 0 bytes! */
249 cwrite (new_file_flag, bp_out, to_read);
251 new_file_flag = false;
258 cwrite (new_file_flag, bp_out, w);
261 new_file_flag = true;
266 while (n_read == bufsize);
269 /* Split into pieces of exactly N_LINES lines.
270 Use buffer BUF, whose size is BUFSIZE. */
273 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
276 char *bp, *bp_out, *eob;
277 bool new_file_flag = true;
282 n_read = full_read (STDIN_FILENO, buf, bufsize);
283 if (n_read == SAFE_READ_ERROR)
284 error (EXIT_FAILURE, errno, "%s", infile);
290 bp = memchr (bp, '\n', eob - bp + 1);
293 if (eob != bp_out) /* do not write 0 bytes! */
295 size_t len = eob - bp_out;
296 cwrite (new_file_flag, bp_out, len);
297 new_file_flag = false;
305 cwrite (new_file_flag, bp_out, bp - bp_out);
307 new_file_flag = true;
312 while (n_read == bufsize);
315 /* Split into pieces that are as large as possible while still not more
316 than N_BYTES bytes, and are split on line boundaries except
317 where lines longer than N_BYTES bytes occur.
318 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
319 buffer of size N_BYTES, in case N_BYTES is very large. */
322 line_bytes_split (size_t n_bytes)
327 size_t n_buffered = 0;
328 char *buf = xmalloc (n_bytes);
332 /* Fill up the full buffer size from the input file. */
334 n_read = full_read (STDIN_FILENO, buf + n_buffered, n_bytes - n_buffered);
335 if (n_read == SAFE_READ_ERROR)
336 error (EXIT_FAILURE, errno, "%s", infile);
338 n_buffered += n_read;
339 if (n_buffered != n_bytes)
342 /* Find where to end this chunk. */
343 bp = buf + n_buffered;
344 if (n_buffered == n_bytes)
346 while (bp > buf && bp[-1] != '\n')
350 /* If chunk has no newlines, use all the chunk. */
352 bp = buf + n_buffered;
354 /* Output the chars as one output file. */
355 cwrite (true, buf, bp - buf);
357 /* Discard the chars we just output; move rest of chunk
358 down to be the start of the next chunk. Source and
359 destination probably overlap. */
360 n_buffered -= bp - buf;
362 memmove (buf, bp, n_buffered);
368 #define FAIL_ONLY_ONE_WAY() \
371 error (0, 0, _("cannot split in more than one way")); \
372 usage (EXIT_FAILURE); \
377 main (int argc, char **argv)
379 struct stat stat_buf;
382 type_undef, type_bytes, type_byteslines, type_lines, type_digits
383 } split_type = type_undef;
384 size_t in_blk_size; /* optimal block size of input file device */
385 char *buf; /* file i/o buffer */
386 size_t page_size = getpagesize ();
389 int digits_optind = 0;
391 initialize_main (&argc, &argv);
392 program_name = argv[0];
393 setlocale (LC_ALL, "");
394 bindtextdomain (PACKAGE, LOCALEDIR);
395 textdomain (PACKAGE);
397 atexit (close_stdout);
399 /* Parse command line options. */
406 /* This is the argv-index of the option we will read next. */
407 int this_optind = optind ? optind : 1;
409 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
418 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
419 || SIZE_MAX / sizeof (size_t) < tmp)
421 error (0, 0, _("%s: invalid suffix length"), optarg);
422 usage (EXIT_FAILURE);
429 if (split_type != type_undef)
430 FAIL_ONLY_ONE_WAY ();
431 split_type = type_bytes;
432 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
435 error (0, 0, _("%s: invalid number of bytes"), optarg);
436 usage (EXIT_FAILURE);
441 if (split_type != type_undef)
442 FAIL_ONLY_ONE_WAY ();
443 split_type = type_lines;
444 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
447 error (0, 0, _("%s: invalid number of lines"), optarg);
448 usage (EXIT_FAILURE);
453 if (split_type != type_undef)
454 FAIL_ONLY_ONE_WAY ();
455 split_type = type_byteslines;
456 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
457 || n_units == 0 || SIZE_MAX < n_units)
459 error (0, 0, _("%s: invalid number of bytes"), optarg);
460 usage (EXIT_FAILURE);
474 if (split_type == type_undef)
476 split_type = type_digits;
479 if (split_type != type_undef && split_type != type_digits)
480 FAIL_ONLY_ONE_WAY ();
481 if (digits_optind != 0 && digits_optind != this_optind)
482 n_units = 0; /* More than one number given; ignore other. */
483 digits_optind = this_optind;
484 if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t))
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);
494 suffix_alphabet = "0123456789";
501 case_GETOPT_HELP_CHAR;
503 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
506 usage (EXIT_FAILURE);
510 /* Handle default case. */
511 if (split_type == type_undef)
513 split_type = type_lines;
519 error (0, 0, _("invalid number of lines: 0"));
520 usage (EXIT_FAILURE);
523 /* Get out the filename arguments. */
526 infile = argv[optind++];
529 outbase = argv[optind++];
533 error (0, 0, _("extra operand %s"), quote (argv[optind]));
534 usage (EXIT_FAILURE);
537 /* Open the input file. */
538 if (! STREQ (infile, "-")
539 && fd_reopen (STDIN_FILENO, infile, O_RDONLY, 0) < 0)
540 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
543 /* Binary I/O is safer when bytecounts are used. */
544 if (O_BINARY && ! isatty (STDIN_FILENO))
545 freopen (NULL, "rb", stdin);
547 /* No output file is open now. */
550 /* Get the optimal block size of input device and make a buffer. */
552 if (fstat (STDIN_FILENO, &stat_buf) != 0)
553 error (EXIT_FAILURE, errno, "%s", infile);
554 in_blk_size = ST_BLKSIZE (stat_buf);
556 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
562 lines_split (n_units, buf, in_blk_size);
566 bytes_split (n_units, buf, in_blk_size);
569 case type_byteslines:
570 line_bytes_split (n_units);
577 if (close (STDIN_FILENO) != 0)
578 error (EXIT_FAILURE, errno, "%s", infile);
579 if (output_desc >= 0 && close (output_desc) < 0)
580 error (EXIT_FAILURE, errno, "%s", outfile);