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"
36 #include "safe-read.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "split"
43 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
44 proper_name ("Richard M. Stallman")
46 #define DEFAULT_SUFFIX_LENGTH 2
48 /* Base name of output files. */
49 static char const *outbase;
51 /* Name of output files. */
54 /* Pointer to the end of the prefix in OUTFILE.
55 Suffixes are inserted here. */
56 static char *outfile_mid;
58 /* Length of OUTFILE's suffix. */
59 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
61 /* Alphabet of characters to use in suffix. */
62 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
64 /* Name of input file. May be "-". */
67 /* Descriptor on which output file is open. */
68 static int output_desc;
70 /* If true, print a diagnostic on standard error just before each
71 output file is opened. */
74 /* For long options that have no equivalent short option, use a
75 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
78 VERBOSE_OPTION = CHAR_MAX + 1
81 static struct option const longopts[] =
83 {"bytes", required_argument, NULL, 'b'},
84 {"lines", required_argument, NULL, 'l'},
85 {"line-bytes", required_argument, NULL, 'C'},
86 {"suffix-length", required_argument, NULL, 'a'},
87 {"numeric-suffixes", no_argument, NULL, 'd'},
88 {"verbose", no_argument, NULL, VERBOSE_OPTION},
89 {GETOPT_HELP_OPTION_DECL},
90 {GETOPT_VERSION_OPTION_DECL},
97 if (status != EXIT_SUCCESS)
98 fprintf (stderr, _("Try `%s --help' for more information.\n"),
103 Usage: %s [OPTION]... [INPUT [PREFIX]]\n\
107 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
108 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
109 is -, read standard input.\n\
113 Mandatory arguments to long options are mandatory for short options too.\n\
115 fprintf (stdout, _("\
116 -a, --suffix-length=N use suffixes of length N (default %d)\n\
117 -b, --bytes=SIZE put SIZE bytes per output file\n\
118 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
119 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
120 -l, --lines=NUMBER put NUMBER lines per output file\n\
121 "), DEFAULT_SUFFIX_LENGTH);
123 --verbose print a diagnostic just before each\n\
124 output file is opened\n\
126 fputs (HELP_OPTION_DESCRIPTION, stdout);
127 fputs (VERSION_OPTION_DESCRIPTION, stdout);
130 SIZE may have a multiplier suffix:\n\
131 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
132 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
134 emit_bug_reporting_address ();
139 /* Compute the next sequential output file name and store it into the
143 next_file_name (void)
145 /* Index in suffix_alphabet of each character in the suffix. */
146 static size_t *sufindex;
150 /* Allocate and initialize the first file name. */
152 size_t outbase_length = strlen (outbase);
153 size_t outfile_length = outbase_length + suffix_length;
154 if (outfile_length + 1 < outbase_length)
156 outfile = xmalloc (outfile_length + 1);
157 outfile_mid = outfile + outbase_length;
158 memcpy (outfile, outbase, outbase_length);
159 memset (outfile_mid, suffix_alphabet[0], suffix_length);
160 outfile[outfile_length] = 0;
161 sufindex = xcalloc (suffix_length, sizeof *sufindex);
163 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
164 /* POSIX requires that if the output file name is too long for
165 its directory, `split' must fail without creating any files.
166 This must be checked for explicitly on operating systems that
167 silently truncate file names. */
169 char *dir = dir_name (outfile);
170 long name_max = pathconf (dir, _PC_NAME_MAX);
171 if (0 <= name_max && name_max < base_len (last_component (outfile)))
172 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
179 /* Increment the suffix in place, if possible. */
181 size_t i = suffix_length;
185 outfile_mid[i] = suffix_alphabet[sufindex[i]];
189 outfile_mid[i] = suffix_alphabet[sufindex[i]];
191 error (EXIT_FAILURE, 0, _("output file suffixes exhausted"));
195 /* Write BYTES bytes at BP to an output file.
196 If NEW_FILE_FLAG is true, open the next output file.
197 Otherwise add to the same output file already in use. */
200 cwrite (bool new_file_flag, const char *bp, size_t bytes)
204 if (output_desc >= 0 && close (output_desc) < 0)
205 error (EXIT_FAILURE, errno, "%s", outfile);
209 fprintf (stdout, _("creating file %s\n"), quote (outfile));
210 output_desc = open (outfile,
211 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
212 (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
213 | S_IROTH | S_IWOTH));
215 error (EXIT_FAILURE, errno, "%s", outfile);
217 if (full_write (output_desc, bp, bytes) != bytes)
218 error (EXIT_FAILURE, errno, "%s", outfile);
221 /* Split into pieces of exactly N_BYTES bytes.
222 Use buffer BUF, whose size is BUFSIZE. */
225 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
228 bool new_file_flag = true;
230 uintmax_t to_write = n_bytes;
235 n_read = full_read (STDIN_FILENO, buf, bufsize);
236 if (n_read == SAFE_READ_ERROR)
237 error (EXIT_FAILURE, errno, "%s", infile);
242 if (to_read < to_write)
244 if (to_read) /* do not write 0 bytes! */
246 cwrite (new_file_flag, bp_out, to_read);
248 new_file_flag = false;
255 cwrite (new_file_flag, bp_out, w);
258 new_file_flag = true;
263 while (n_read == bufsize);
266 /* Split into pieces of exactly N_LINES lines.
267 Use buffer BUF, whose size is BUFSIZE. */
270 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
273 char *bp, *bp_out, *eob;
274 bool new_file_flag = true;
279 n_read = full_read (STDIN_FILENO, buf, bufsize);
280 if (n_read == SAFE_READ_ERROR)
281 error (EXIT_FAILURE, errno, "%s", infile);
287 bp = memchr (bp, '\n', eob - bp + 1);
290 if (eob != bp_out) /* do not write 0 bytes! */
292 size_t len = eob - bp_out;
293 cwrite (new_file_flag, bp_out, len);
294 new_file_flag = false;
302 cwrite (new_file_flag, bp_out, bp - bp_out);
304 new_file_flag = true;
309 while (n_read == bufsize);
312 /* Split into pieces that are as large as possible while still not more
313 than N_BYTES bytes, and are split on line boundaries except
314 where lines longer than N_BYTES bytes occur.
315 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
316 buffer of size N_BYTES, in case N_BYTES is very large. */
319 line_bytes_split (size_t n_bytes)
324 size_t n_buffered = 0;
325 char *buf = xmalloc (n_bytes);
329 /* Fill up the full buffer size from the input file. */
331 n_read = full_read (STDIN_FILENO, buf + n_buffered, n_bytes - n_buffered);
332 if (n_read == SAFE_READ_ERROR)
333 error (EXIT_FAILURE, errno, "%s", infile);
335 n_buffered += n_read;
336 if (n_buffered != n_bytes)
343 /* Find where to end this chunk. */
344 bp = buf + n_buffered;
345 if (n_buffered == n_bytes)
347 while (bp > buf && bp[-1] != '\n')
351 /* If chunk has no newlines, use all the chunk. */
353 bp = buf + n_buffered;
355 /* Output the chars as one output file. */
356 cwrite (true, buf, bp - buf);
358 /* Discard the chars we just output; move rest of chunk
359 down to be the start of the next chunk. Source and
360 destination probably overlap. */
361 n_buffered -= bp - buf;
363 memmove (buf, bp, n_buffered);
369 #define FAIL_ONLY_ONE_WAY() \
372 error (0, 0, _("cannot split in more than one way")); \
373 usage (EXIT_FAILURE); \
378 main (int argc, char **argv)
380 struct stat stat_buf;
383 type_undef, type_bytes, type_byteslines, type_lines, type_digits
384 } split_type = type_undef;
385 size_t in_blk_size; /* optimal block size of input file device */
386 char *buf; /* file i/o buffer */
387 size_t page_size = getpagesize ();
389 static char const multipliers[] = "bEGKkMmPTYZ0";
391 int digits_optind = 0;
393 initialize_main (&argc, &argv);
394 set_program_name (argv[0]);
395 setlocale (LC_ALL, "");
396 bindtextdomain (PACKAGE, LOCALEDIR);
397 textdomain (PACKAGE);
399 atexit (close_stdout);
401 /* Parse command line options. */
408 /* This is the argv-index of the option we will read next. */
409 int this_optind = optind ? optind : 1;
411 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
420 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
421 || SIZE_MAX / sizeof (size_t) < tmp)
423 error (0, 0, _("%s: invalid suffix length"), optarg);
424 usage (EXIT_FAILURE);
431 if (split_type != type_undef)
432 FAIL_ONLY_ONE_WAY ();
433 split_type = type_bytes;
434 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
437 error (0, 0, _("%s: invalid number of bytes"), optarg);
438 usage (EXIT_FAILURE);
443 if (split_type != type_undef)
444 FAIL_ONLY_ONE_WAY ();
445 split_type = type_lines;
446 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
449 error (0, 0, _("%s: invalid number of lines"), optarg);
450 usage (EXIT_FAILURE);
455 if (split_type != type_undef)
456 FAIL_ONLY_ONE_WAY ();
457 split_type = type_byteslines;
458 if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK
459 || n_units == 0 || SIZE_MAX < n_units)
461 error (0, 0, _("%s: invalid number of bytes"), optarg);
462 usage (EXIT_FAILURE);
476 if (split_type == type_undef)
478 split_type = type_digits;
481 if (split_type != type_undef && split_type != type_digits)
482 FAIL_ONLY_ONE_WAY ();
483 if (digits_optind != 0 && digits_optind != this_optind)
484 n_units = 0; /* More than one number given; ignore other. */
485 digits_optind = this_optind;
486 if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t))
488 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
489 error (EXIT_FAILURE, 0,
490 _("line count option -%s%c... is too large"),
491 umaxtostr (n_units, buffer), c);
496 suffix_alphabet = "0123456789";
503 case_GETOPT_HELP_CHAR;
505 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
508 usage (EXIT_FAILURE);
512 /* Handle default case. */
513 if (split_type == type_undef)
515 split_type = type_lines;
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, _("extra operand %s"), quote (argv[optind]));
536 usage (EXIT_FAILURE);
539 /* Open the input file. */
540 if (! STREQ (infile, "-")
541 && fd_reopen (STDIN_FILENO, infile, O_RDONLY, 0) < 0)
542 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
545 /* Binary I/O is safer when bytecounts are used. */
546 if (O_BINARY && ! isatty (STDIN_FILENO))
547 freopen (NULL, "rb", stdin);
549 /* No output file is open now. */
552 /* Get the optimal block size of input device and make a buffer. */
554 if (fstat (STDIN_FILENO, &stat_buf) != 0)
555 error (EXIT_FAILURE, errno, "%s", infile);
556 in_blk_size = ST_BLKSIZE (stat_buf);
558 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
564 lines_split (n_units, buf, in_blk_size);
568 bytes_split (n_units, buf, in_blk_size);
571 case type_byteslines:
572 line_bytes_split (n_units);
579 if (close (STDIN_FILENO) != 0)
580 error (EXIT_FAILURE, errno, "%s", infile);
581 if (output_desc >= 0 && close (output_desc) < 0)
582 error (EXIT_FAILURE, errno, "%s", outfile);