1 /* split.c -- split a file into pieces.
2 Copyright (C) 88, 91, 1995-2003 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>
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 N_ ("Torbjorn Granlund and 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 /* Name of input file. May be "-". */
67 /* Descriptor on which input file is open. */
68 static int input_desc;
70 /* Descriptor on which output file is open. */
71 static int output_desc;
73 /* If nonzero, print a diagnostic on standard error just before each
74 output file is opened. */
77 static struct option const longopts[] =
79 {"bytes", required_argument, NULL, 'b'},
80 {"lines", required_argument, NULL, 'l'},
81 {"line-bytes", required_argument, NULL, 'C'},
82 {"suffix-length", required_argument, NULL, 'a'},
83 {"verbose", no_argument, &verbose, 0},
84 {GETOPT_HELP_OPTION_DECL},
85 {GETOPT_VERSION_OPTION_DECL},
93 fprintf (stderr, _("Try `%s --help' for more information.\n"),
98 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
102 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
103 PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input.\n\
107 Mandatory arguments to long options are mandatory for short options too.\n\
109 fprintf (stdout, _("\
110 -a, --suffix-length=N use suffixes of length N (default %d)\n\
111 -b, --bytes=SIZE put SIZE bytes per output file\n\
112 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
113 -l, --lines=NUMBER put NUMBER lines per output file\n\
114 "), DEFAULT_SUFFIX_LENGTH);
116 --verbose print a diagnostic to standard error just\n\
117 before each output file is opened\n\
119 fputs (HELP_OPTION_DESCRIPTION, stdout);
120 fputs (VERSION_OPTION_DESCRIPTION, stdout);
123 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
125 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
127 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
130 /* Compute the next sequential output file name and store it into the
134 next_file_name (void)
138 /* Allocate and initialize the first file name. */
140 size_t outbase_length = strlen (outbase);
141 size_t outfile_length = outbase_length + suffix_length;
142 if (outfile_length + 1 < outbase_length)
144 outfile = xmalloc (outfile_length + 1);
145 outfile_mid = outfile + outbase_length;
146 memcpy (outfile, outbase, outbase_length);
147 memset (outfile_mid, 'a', suffix_length);
148 outfile[outfile_length] = 0;
150 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
151 /* POSIX requires that if the output file name is too long for
152 its directory, `split' must fail without creating any files.
153 This must be checked for explicitly on operating systems that
154 silently truncate file names. */
156 char *dir = dir_name (outfile);
157 long name_max = pathconf (dir, _PC_NAME_MAX);
158 if (0 <= name_max && name_max < base_len (base_name (outfile)))
159 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
166 /* Increment the suffix in place, if possible. */
169 for (p = outfile_mid + suffix_length; outfile_mid < p; *--p = 'a')
172 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
176 /* Write BYTES bytes at BP to an output file.
177 If NEW_FILE_FLAG is nonzero, open the next output file.
178 Otherwise add to the same output file already in use. */
181 cwrite (int new_file_flag, const char *bp, size_t bytes)
185 if (output_desc >= 0 && close (output_desc) < 0)
186 error (EXIT_FAILURE, errno, "%s", outfile);
190 fprintf (stderr, _("creating file `%s'\n"), outfile);
191 output_desc = open (outfile,
192 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
194 error (EXIT_FAILURE, errno, "%s", outfile);
196 if (full_write (output_desc, bp, bytes) != bytes)
197 error (EXIT_FAILURE, errno, "%s", outfile);
200 /* Split into pieces of exactly N_BYTES bytes.
201 Use buffer BUF, whose size is BUFSIZE. */
204 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
207 int new_file_flag = 1;
209 uintmax_t to_write = n_bytes;
214 n_read = full_read (input_desc, buf, bufsize);
215 if (n_read == SAFE_READ_ERROR)
216 error (EXIT_FAILURE, errno, "%s", infile);
221 if (to_read < to_write)
223 if (to_read) /* do not write 0 bytes! */
225 cwrite (new_file_flag, bp_out, to_read);
234 cwrite (new_file_flag, bp_out, w);
242 while (n_read == bufsize);
245 /* Split into pieces of exactly N_LINES lines.
246 Use buffer BUF, whose size is BUFSIZE. */
249 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
252 char *bp, *bp_out, *eob;
253 int new_file_flag = 1;
258 n_read = full_read (input_desc, buf, bufsize);
259 if (n_read == SAFE_READ_ERROR)
260 error (EXIT_FAILURE, errno, "%s", infile);
266 bp = memchr (bp, '\n', eob - bp + 1);
269 if (eob != bp_out) /* do not write 0 bytes! */
271 size_t len = eob - bp_out;
272 cwrite (new_file_flag, bp_out, len);
281 cwrite (new_file_flag, bp_out, bp - bp_out);
288 while (n_read == bufsize);
291 /* Split into pieces that are as large as possible while still not more
292 than N_BYTES bytes, and are split on line boundaries except
293 where lines longer than N_BYTES bytes occur.
294 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
295 buffer of size N_BYTES, in case N_BYTES is very large. */
298 line_bytes_split (size_t n_bytes)
303 size_t n_buffered = 0;
304 char *buf = xmalloc (n_bytes);
308 /* Fill up the full buffer size from the input file. */
310 n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
311 if (n_read == SAFE_READ_ERROR)
312 error (EXIT_FAILURE, errno, "%s", infile);
314 n_buffered += n_read;
315 if (n_buffered != n_bytes)
318 /* Find where to end this chunk. */
319 bp = buf + n_buffered;
320 if (n_buffered == n_bytes)
322 while (bp > buf && bp[-1] != '\n')
326 /* If chunk has no newlines, use all the chunk. */
328 bp = buf + n_buffered;
330 /* Output the chars as one output file. */
331 cwrite (1, buf, bp - buf);
333 /* Discard the chars we just output; move rest of chunk
334 down to be the start of the next chunk. Source and
335 destination probably overlap. */
336 n_buffered -= bp - buf;
338 memmove (buf, bp, n_buffered);
344 #define FAIL_ONLY_ONE_WAY() \
347 error (0, 0, _("cannot split in more than one way")); \
348 usage (EXIT_FAILURE); \
353 main (int argc, char **argv)
355 struct stat stat_buf;
358 type_undef, type_bytes, type_byteslines, type_lines, type_digits
359 } split_type = type_undef;
360 size_t in_blk_size; /* optimal block size of input file device */
361 char *buf; /* file i/o buffer */
364 int digits_optind = 0;
366 program_name = argv[0];
367 setlocale (LC_ALL, "");
368 bindtextdomain (PACKAGE, LOCALEDIR);
369 textdomain (PACKAGE);
371 atexit (close_stdout);
373 /* Parse command line options. */
380 /* This is the argv-index of the option we will read next. */
381 int this_optind = optind ? optind : 1;
383 c = getopt_long (argc, argv, "0123456789C:a:b:l:", longopts, NULL);
395 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
396 || tmp == 0 || SIZE_MAX < tmp)
398 error (0, 0, _("%s: invalid suffix length"), optarg);
399 usage (EXIT_FAILURE);
406 if (split_type != type_undef)
407 FAIL_ONLY_ONE_WAY ();
408 split_type = type_bytes;
409 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
412 error (0, 0, _("%s: invalid number of bytes"), optarg);
413 usage (EXIT_FAILURE);
418 if (split_type != type_undef)
419 FAIL_ONLY_ONE_WAY ();
420 split_type = type_lines;
421 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
424 error (0, 0, _("%s: invalid number of lines"), optarg);
425 usage (EXIT_FAILURE);
430 if (split_type != type_undef)
431 FAIL_ONLY_ONE_WAY ();
432 split_type = type_byteslines;
433 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
434 || n_units == 0 || SIZE_MAX < n_units)
436 error (0, 0, _("%s: invalid number of bytes"), optarg);
437 usage (EXIT_FAILURE);
451 if (split_type == type_undef)
453 split_type = type_digits;
456 if (split_type != type_undef && split_type != type_digits)
457 FAIL_ONLY_ONE_WAY ();
458 if (digits_optind != 0 && digits_optind != this_optind)
459 n_units = 0; /* More than one number given; ignore other. */
460 digits_optind = this_optind;
461 if (UINTMAX_MAX / 10 < n_units
462 || n_units * 10 + c - '0' < n_units * 10)
464 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
465 error (EXIT_FAILURE, 0,
466 _("line count option -%s%c... is too large"),
467 umaxtostr (n_units, buffer), c);
469 n_units = n_units * 10 + c - '0';
472 case_GETOPT_HELP_CHAR;
474 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
477 usage (EXIT_FAILURE);
481 if (digits_optind && 200112 <= posix2_version ())
483 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
484 char const *a = umaxtostr (n_units, buffer);
485 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
486 usage (EXIT_FAILURE);
489 /* Handle default case. */
490 if (split_type == type_undef)
492 split_type = type_lines;
498 /* FIXME: be sure to remove this block when removing
499 support for obsolete options like `-10'. */
500 error (0, 0, _("invalid number of lines: 0"));
501 usage (EXIT_FAILURE);
504 /* Get out the filename arguments. */
507 infile = argv[optind++];
510 outbase = argv[optind++];
514 error (0, 0, _("too many arguments"));
515 usage (EXIT_FAILURE);
518 /* Open the input file. */
519 if (STREQ (infile, "-"))
520 input_desc = STDIN_FILENO;
523 input_desc = open (infile, O_RDONLY);
525 error (EXIT_FAILURE, errno, "%s", infile);
527 /* Binary I/O is safer when bytecounts are used. */
528 SET_BINARY (input_desc);
530 /* No output file is open now. */
533 /* Get the optimal block size of input device and make a buffer. */
535 if (fstat (input_desc, &stat_buf) < 0)
536 error (EXIT_FAILURE, errno, "%s", infile);
537 in_blk_size = ST_BLKSIZE (stat_buf);
539 buf = xmalloc (in_blk_size + 1);
545 lines_split (n_units, buf, in_blk_size);
549 bytes_split (n_units, buf, in_blk_size);
552 case type_byteslines:
553 line_bytes_split (n_units);
560 if (close (input_desc) < 0)
561 error (EXIT_FAILURE, errno, "%s", infile);
562 if (output_desc >= 0 && close (output_desc) < 0)
563 error (EXIT_FAILURE, errno, "%s", outfile);