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.
20 * Implement -t CHAR or -t REGEX to specify break characters other
27 #include <sys/types.h>
31 #include "fd-reopen.h"
33 #include "full-read.h"
34 #include "full-write.h"
37 #include "safe-read.h"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "split"
43 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
45 #define DEFAULT_SUFFIX_LENGTH 2
47 /* The name this program was run with. */
50 /* Base name of output files. */
51 static char const *outbase;
53 /* Name of output files. */
56 /* Pointer to the end of the prefix in OUTFILE.
57 Suffixes are inserted here. */
58 static char *outfile_mid;
60 /* Length of OUTFILE's suffix. */
61 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
63 /* Alphabet of characters to use in suffix. */
64 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
66 /* Name of input file. May be "-". */
69 /* Descriptor on which output file is open. */
70 static int output_desc;
72 /* If true, print a diagnostic on standard error just before each
73 output file is opened. */
76 /* For long options that have no equivalent short option, use a
77 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
80 VERBOSE_OPTION = CHAR_MAX + 1
83 static struct option const longopts[] =
85 {"bytes", required_argument, NULL, 'b'},
86 {"lines", required_argument, NULL, 'l'},
87 {"line-bytes", required_argument, NULL, 'C'},
88 {"suffix-length", required_argument, NULL, 'a'},
89 {"numeric-suffixes", no_argument, NULL, 'd'},
90 {"verbose", no_argument, NULL, VERBOSE_OPTION},
91 {GETOPT_HELP_OPTION_DECL},
92 {GETOPT_VERSION_OPTION_DECL},
99 if (status != EXIT_SUCCESS)
100 fprintf (stderr, _("Try `%s --help' for more information.\n"),
105 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
109 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
110 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
111 is -, read standard input.\n\
115 Mandatory arguments to long options are mandatory for short options too.\n\
117 fprintf (stdout, _("\
118 -a, --suffix-length=N use suffixes of length N (default %d)\n\
119 -b, --bytes=SIZE put SIZE bytes per output file\n\
120 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
121 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
122 -l, --lines=NUMBER put NUMBER lines per output file\n\
123 "), DEFAULT_SUFFIX_LENGTH);
125 --verbose print a diagnostic just before each\n\
126 output file is opened\n\
128 fputs (HELP_OPTION_DESCRIPTION, stdout);
129 fputs (VERSION_OPTION_DESCRIPTION, stdout);
132 SIZE may have a multiplier suffix:\n\
133 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
134 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
136 emit_bug_reporting_address ();
141 /* Compute the next sequential output file name and store it into the
145 next_file_name (void)
147 /* Index in suffix_alphabet of each character in the suffix. */
148 static size_t *sufindex;
152 /* Allocate and initialize the first file name. */
154 size_t outbase_length = strlen (outbase);
155 size_t outfile_length = outbase_length + suffix_length;
156 if (outfile_length + 1 < outbase_length)
158 outfile = xmalloc (outfile_length + 1);
159 outfile_mid = outfile + outbase_length;
160 memcpy (outfile, outbase, outbase_length);
161 memset (outfile_mid, suffix_alphabet[0], suffix_length);
162 outfile[outfile_length] = 0;
163 sufindex = xcalloc (suffix_length, sizeof *sufindex);
165 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
166 /* POSIX requires that if the output file name is too long for
167 its directory, `split' must fail without creating any files.
168 This must be checked for explicitly on operating systems that
169 silently truncate file names. */
171 char *dir = dir_name (outfile);
172 long name_max = pathconf (dir, _PC_NAME_MAX);
173 if (0 <= name_max && name_max < base_len (last_component (outfile)))
174 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
181 /* Increment the suffix in place, if possible. */
183 size_t i = suffix_length;
187 outfile_mid[i] = suffix_alphabet[sufindex[i]];
191 outfile_mid[i] = suffix_alphabet[sufindex[i]];
193 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
197 /* Write BYTES bytes at BP to an output file.
198 If NEW_FILE_FLAG is true, open the next output file.
199 Otherwise add to the same output file already in use. */
202 cwrite (bool new_file_flag, const char *bp, size_t bytes)
206 if (output_desc >= 0 && close (output_desc) < 0)
207 error (EXIT_FAILURE, errno, "%s", outfile);
211 fprintf (stdout, _("creating file %s\n"), quote (outfile));
212 output_desc = open (outfile,
213 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
214 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
215 | S_IROTH | S_IWOTH));
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 (STDIN_FILENO, 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 (STDIN_FILENO, 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 (STDIN_FILENO, 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)
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 ();
391 static char const multipliers[] = "bEGKkMmPTYZ0";
393 int digits_optind = 0;
395 initialize_main (&argc, &argv);
396 program_name = argv[0];
397 setlocale (LC_ALL, "");
398 bindtextdomain (PACKAGE, LOCALEDIR);
399 textdomain (PACKAGE);
401 atexit (close_stdout);
403 /* Parse command line options. */
410 /* This is the argv-index of the option we will read next. */
411 int this_optind = optind ? optind : 1;
413 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
422 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
423 || SIZE_MAX / sizeof (size_t) < tmp)
425 error (0, 0, _("%s: invalid suffix length"), optarg);
426 usage (EXIT_FAILURE);
433 if (split_type != type_undef)
434 FAIL_ONLY_ONE_WAY ();
435 split_type = type_bytes;
436 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
439 error (0, 0, _("%s: invalid number of bytes"), optarg);
440 usage (EXIT_FAILURE);
445 if (split_type != type_undef)
446 FAIL_ONLY_ONE_WAY ();
447 split_type = type_lines;
448 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
451 error (0, 0, _("%s: invalid number of lines"), optarg);
452 usage (EXIT_FAILURE);
457 if (split_type != type_undef)
458 FAIL_ONLY_ONE_WAY ();
459 split_type = type_byteslines;
460 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
461 || n_units == 0 || SIZE_MAX < n_units)
463 error (0, 0, _("%s: invalid number of bytes"), optarg);
464 usage (EXIT_FAILURE);
478 if (split_type == type_undef)
480 split_type = type_digits;
483 if (split_type != type_undef && split_type != type_digits)
484 FAIL_ONLY_ONE_WAY ();
485 if (digits_optind != 0 && digits_optind != this_optind)
486 n_units = 0; /* More than one number given; ignore other. */
487 digits_optind = this_optind;
488 if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t))
490 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
491 error (EXIT_FAILURE, 0,
492 _("line count option -%s%c... is too large"),
493 umaxtostr (n_units, buffer), c);
498 suffix_alphabet = "0123456789";
505 case_GETOPT_HELP_CHAR;
507 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
510 usage (EXIT_FAILURE);
514 /* Handle default case. */
515 if (split_type == type_undef)
517 split_type = type_lines;
523 error (0, 0, _("invalid number of lines: 0"));
524 usage (EXIT_FAILURE);
527 /* Get out the filename arguments. */
530 infile = argv[optind++];
533 outbase = argv[optind++];
537 error (0, 0, _("extra operand %s"), quote (argv[optind]));
538 usage (EXIT_FAILURE);
541 /* Open the input file. */
542 if (! STREQ (infile, "-")
543 && fd_reopen (STDIN_FILENO, infile, O_RDONLY, 0) < 0)
544 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
547 /* Binary I/O is safer when bytecounts are used. */
548 if (O_BINARY && ! isatty (STDIN_FILENO))
549 freopen (NULL, "rb", stdin);
551 /* No output file is open now. */
554 /* Get the optimal block size of input device and make a buffer. */
556 if (fstat (STDIN_FILENO, &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 (STDIN_FILENO) != 0)
582 error (EXIT_FAILURE, errno, "%s", infile);
583 if (output_desc >= 0 && close (output_desc) < 0)
584 error (EXIT_FAILURE, errno, "%s", outfile);