1 /* split.c -- split a file into pieces.
2 Copyright (C) 88, 91, 1995-2004 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 "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 input file is open. */
70 static int input_desc
;
72 /* Descriptor on which output file is open. */
73 static int output_desc
;
75 /* If nonzero, print a diagnostic on standard error just before each
76 output file is opened. */
79 static struct option
const longopts
[] =
81 {"bytes", required_argument
, NULL
, 'b'},
82 {"lines", required_argument
, NULL
, 'l'},
83 {"line-bytes", required_argument
, NULL
, 'C'},
84 {"suffix-length", required_argument
, NULL
, 'a'},
85 {"numeric-suffixes", no_argument
, NULL
, 'd'},
86 {"verbose", no_argument
, &verbose
, 1},
87 {GETOPT_HELP_OPTION_DECL
},
88 {GETOPT_VERSION_OPTION_DECL
},
95 if (status
!= EXIT_SUCCESS
)
96 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
101 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
105 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
106 PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input.\n\
110 Mandatory arguments to long options are mandatory for short options too.\n\
112 fprintf (stdout
, _("\
113 -a, --suffix-length=N use suffixes of length N (default %d)\n\
114 -b, --bytes=SIZE put SIZE bytes per output file\n\
115 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
116 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
117 -l, --lines=NUMBER put NUMBER lines per output file\n\
118 "), DEFAULT_SUFFIX_LENGTH
);
120 --verbose print a diagnostic to standard error just\n\
121 before each output file is opened\n\
123 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
124 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
127 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
129 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT
);
134 /* Compute the next sequential output file name and store it into the
138 next_file_name (void)
140 /* Index in suffix_alphabet of each character in the suffix. */
141 static size_t *sufindex
;
145 /* Allocate and initialize the first file name. */
147 size_t outbase_length
= strlen (outbase
);
148 size_t outfile_length
= outbase_length
+ suffix_length
;
149 if (outfile_length
+ 1 < outbase_length
)
151 outfile
= xmalloc (outfile_length
+ 1);
152 outfile_mid
= outfile
+ outbase_length
;
153 memcpy (outfile
, outbase
, outbase_length
);
154 memset (outfile_mid
, suffix_alphabet
[0], suffix_length
);
155 outfile
[outfile_length
] = 0;
156 sufindex
= xcalloc (suffix_length
, sizeof *sufindex
);
158 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
159 /* POSIX requires that if the output file name is too long for
160 its directory, `split' must fail without creating any files.
161 This must be checked for explicitly on operating systems that
162 silently truncate file names. */
164 char *dir
= dir_name (outfile
);
165 long name_max
= pathconf (dir
, _PC_NAME_MAX
);
166 if (0 <= name_max
&& name_max
< base_len (base_name (outfile
)))
167 error (EXIT_FAILURE
, ENAMETOOLONG
, "%s", outfile
);
174 /* Increment the suffix in place, if possible. */
176 size_t i
= suffix_length
;
180 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
184 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
186 error (EXIT_FAILURE
, 0, _("Output file suffixes exhausted"));
190 /* Write BYTES bytes at BP to an output file.
191 If NEW_FILE_FLAG is nonzero, open the next output file.
192 Otherwise add to the same output file already in use. */
195 cwrite (int new_file_flag
, const char *bp
, size_t bytes
)
199 if (output_desc
>= 0 && close (output_desc
) < 0)
200 error (EXIT_FAILURE
, errno
, "%s", outfile
);
204 fprintf (stderr
, _("creating file `%s'\n"), outfile
);
205 output_desc
= open (outfile
,
206 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
, 0666);
208 error (EXIT_FAILURE
, errno
, "%s", outfile
);
210 if (full_write (output_desc
, bp
, bytes
) != bytes
)
211 error (EXIT_FAILURE
, errno
, "%s", outfile
);
214 /* Split into pieces of exactly N_BYTES bytes.
215 Use buffer BUF, whose size is BUFSIZE. */
218 bytes_split (uintmax_t n_bytes
, char *buf
, size_t bufsize
)
221 int new_file_flag
= 1;
223 uintmax_t to_write
= n_bytes
;
228 n_read
= full_read (input_desc
, buf
, bufsize
);
229 if (n_read
== SAFE_READ_ERROR
)
230 error (EXIT_FAILURE
, errno
, "%s", infile
);
235 if (to_read
< to_write
)
237 if (to_read
) /* do not write 0 bytes! */
239 cwrite (new_file_flag
, bp_out
, to_read
);
248 cwrite (new_file_flag
, bp_out
, w
);
256 while (n_read
== bufsize
);
259 /* Split into pieces of exactly N_LINES lines.
260 Use buffer BUF, whose size is BUFSIZE. */
263 lines_split (uintmax_t n_lines
, char *buf
, size_t bufsize
)
266 char *bp
, *bp_out
, *eob
;
267 int new_file_flag
= 1;
272 n_read
= full_read (input_desc
, buf
, bufsize
);
273 if (n_read
== SAFE_READ_ERROR
)
274 error (EXIT_FAILURE
, errno
, "%s", infile
);
280 bp
= memchr (bp
, '\n', eob
- bp
+ 1);
283 if (eob
!= bp_out
) /* do not write 0 bytes! */
285 size_t len
= eob
- bp_out
;
286 cwrite (new_file_flag
, bp_out
, len
);
295 cwrite (new_file_flag
, bp_out
, bp
- bp_out
);
302 while (n_read
== bufsize
);
305 /* Split into pieces that are as large as possible while still not more
306 than N_BYTES bytes, and are split on line boundaries except
307 where lines longer than N_BYTES bytes occur.
308 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
309 buffer of size N_BYTES, in case N_BYTES is very large. */
312 line_bytes_split (size_t n_bytes
)
317 size_t n_buffered
= 0;
318 char *buf
= xmalloc (n_bytes
);
322 /* Fill up the full buffer size from the input file. */
324 n_read
= full_read (input_desc
, buf
+ n_buffered
, n_bytes
- n_buffered
);
325 if (n_read
== SAFE_READ_ERROR
)
326 error (EXIT_FAILURE
, errno
, "%s", infile
);
328 n_buffered
+= n_read
;
329 if (n_buffered
!= n_bytes
)
332 /* Find where to end this chunk. */
333 bp
= buf
+ n_buffered
;
334 if (n_buffered
== n_bytes
)
336 while (bp
> buf
&& bp
[-1] != '\n')
340 /* If chunk has no newlines, use all the chunk. */
342 bp
= buf
+ n_buffered
;
344 /* Output the chars as one output file. */
345 cwrite (1, buf
, bp
- buf
);
347 /* Discard the chars we just output; move rest of chunk
348 down to be the start of the next chunk. Source and
349 destination probably overlap. */
350 n_buffered
-= bp
- buf
;
352 memmove (buf
, bp
, n_buffered
);
358 #define FAIL_ONLY_ONE_WAY() \
361 error (0, 0, _("cannot split in more than one way")); \
362 usage (EXIT_FAILURE); \
367 main (int argc
, char **argv
)
369 struct stat stat_buf
;
372 type_undef
, type_bytes
, type_byteslines
, type_lines
, type_digits
373 } split_type
= type_undef
;
374 size_t in_blk_size
; /* optimal block size of input file device */
375 char *buf
; /* file i/o buffer */
378 int digits_optind
= 0;
380 initialize_main (&argc
, &argv
);
381 program_name
= argv
[0];
382 setlocale (LC_ALL
, "");
383 bindtextdomain (PACKAGE
, LOCALEDIR
);
384 textdomain (PACKAGE
);
386 atexit (close_stdout
);
388 /* Parse command line options. */
395 /* This is the argv-index of the option we will read next. */
396 int this_optind
= optind
? optind
: 1;
398 c
= getopt_long (argc
, argv
, "0123456789C:a:b:dl:", longopts
, NULL
);
410 if (xstrtoul (optarg
, NULL
, 10, &tmp
, "") != LONGINT_OK
411 || SIZE_MAX
/ sizeof (size_t) < tmp
)
413 error (0, 0, _("%s: invalid suffix length"), optarg
);
414 usage (EXIT_FAILURE
);
421 if (split_type
!= type_undef
)
422 FAIL_ONLY_ONE_WAY ();
423 split_type
= type_bytes
;
424 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, "bkm") != LONGINT_OK
427 error (0, 0, _("%s: invalid number of bytes"), optarg
);
428 usage (EXIT_FAILURE
);
433 if (split_type
!= type_undef
)
434 FAIL_ONLY_ONE_WAY ();
435 split_type
= type_lines
;
436 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, "") != LONGINT_OK
439 error (0, 0, _("%s: invalid number of lines"), optarg
);
440 usage (EXIT_FAILURE
);
445 if (split_type
!= type_undef
)
446 FAIL_ONLY_ONE_WAY ();
447 split_type
= type_byteslines
;
448 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, "bkm") != LONGINT_OK
449 || n_units
== 0 || SIZE_MAX
< n_units
)
451 error (0, 0, _("%s: invalid number of bytes"), optarg
);
452 usage (EXIT_FAILURE
);
466 if (split_type
== type_undef
)
468 split_type
= type_digits
;
471 if (split_type
!= type_undef
&& split_type
!= type_digits
)
472 FAIL_ONLY_ONE_WAY ();
473 if (digits_optind
!= 0 && digits_optind
!= this_optind
)
474 n_units
= 0; /* More than one number given; ignore other. */
475 digits_optind
= this_optind
;
476 if (UINTMAX_MAX
/ 10 < n_units
477 || n_units
* 10 + c
- '0' < n_units
* 10)
479 char buffer
[INT_BUFSIZE_BOUND (uintmax_t)];
480 error (EXIT_FAILURE
, 0,
481 _("line count option -%s%c... is too large"),
482 umaxtostr (n_units
, buffer
), c
);
484 n_units
= n_units
* 10 + c
- '0';
488 suffix_alphabet
= "0123456789";
491 case_GETOPT_HELP_CHAR
;
493 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
496 usage (EXIT_FAILURE
);
500 if (digits_optind
&& 200112 <= posix2_version ())
502 char buffer
[INT_BUFSIZE_BOUND (uintmax_t)];
503 char const *a
= umaxtostr (n_units
, buffer
);
504 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a
, a
);
505 usage (EXIT_FAILURE
);
508 /* Handle default case. */
509 if (split_type
== type_undef
)
511 split_type
= type_lines
;
517 /* FIXME: be sure to remove this block when removing
518 support for obsolete options like `-10'. */
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, _("too many arguments"));
534 usage (EXIT_FAILURE
);
537 /* Open the input file. */
538 if (STREQ (infile
, "-"))
539 input_desc
= STDIN_FILENO
;
542 input_desc
= open (infile
, O_RDONLY
);
544 error (EXIT_FAILURE
, errno
, "%s", infile
);
546 /* Binary I/O is safer when bytecounts are used. */
547 SET_BINARY (input_desc
);
549 /* No output file is open now. */
552 /* Get the optimal block size of input device and make a buffer. */
554 if (fstat (input_desc
, &stat_buf
) < 0)
555 error (EXIT_FAILURE
, errno
, "%s", infile
);
556 in_blk_size
= ST_BLKSIZE (stat_buf
);
558 buf
= xmalloc (in_blk_size
+ 1);
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 (input_desc
) < 0)
580 error (EXIT_FAILURE
, errno
, "%s", infile
);
581 if (output_desc
>= 0 && close (output_desc
) < 0)
582 error (EXIT_FAILURE
, errno
, "%s", outfile
);