1 /* split.c -- split a file into pieces.
2 Copyright (C) 1988, 1991, 1995-2009 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"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "split"
44 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
45 proper_name ("Richard M. Stallman")
47 #define DEFAULT_SUFFIX_LENGTH 2
49 /* Base name of output files. */
50 static char const *outbase
;
52 /* Name of output files. */
55 /* Pointer to the end of the prefix in OUTFILE.
56 Suffixes are inserted here. */
57 static char *outfile_mid
;
59 /* Length of OUTFILE's suffix. */
60 static size_t suffix_length
= DEFAULT_SUFFIX_LENGTH
;
62 /* Alphabet of characters to use in suffix. */
63 static char const *suffix_alphabet
= "abcdefghijklmnopqrstuvwxyz";
65 /* Name of input file. May be "-". */
68 /* Descriptor on which output file is open. */
69 static int output_desc
;
71 /* If true, print a diagnostic on standard error just before each
72 output file is opened. */
75 /* For long options that have no equivalent short option, use a
76 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
79 VERBOSE_OPTION
= CHAR_MAX
+ 1
82 static struct option
const longopts
[] =
84 {"bytes", required_argument
, NULL
, 'b'},
85 {"lines", required_argument
, NULL
, 'l'},
86 {"line-bytes", required_argument
, NULL
, 'C'},
87 {"suffix-length", required_argument
, NULL
, 'a'},
88 {"numeric-suffixes", no_argument
, NULL
, 'd'},
89 {"verbose", no_argument
, NULL
, VERBOSE_OPTION
},
90 {GETOPT_HELP_OPTION_DECL
},
91 {GETOPT_VERSION_OPTION_DECL
},
98 if (status
!= EXIT_SUCCESS
)
99 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
104 Usage: %s [OPTION]... [INPUT [PREFIX]]\n\
108 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
109 size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\
110 is -, read standard input.\n\
114 Mandatory arguments to long options are mandatory for short options too.\n\
116 fprintf (stdout
, _("\
117 -a, --suffix-length=N use suffixes of length N (default %d)\n\
118 -b, --bytes=SIZE put SIZE bytes per output file\n\
119 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
120 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
121 -l, --lines=NUMBER put NUMBER lines per output file\n\
122 "), DEFAULT_SUFFIX_LENGTH
);
124 --verbose print a diagnostic just before each\n\
125 output file is opened\n\
127 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
128 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
131 SIZE may have a multiplier suffix:\n\
132 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
133 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
135 emit_bug_reporting_address ();
140 /* Compute the next sequential output file name and store it into the
144 next_file_name (void)
146 /* Index in suffix_alphabet of each character in the suffix. */
147 static size_t *sufindex
;
151 /* Allocate and initialize the first file name. */
153 size_t outbase_length
= strlen (outbase
);
154 size_t outfile_length
= outbase_length
+ suffix_length
;
155 if (outfile_length
+ 1 < outbase_length
)
157 outfile
= xmalloc (outfile_length
+ 1);
158 outfile_mid
= outfile
+ outbase_length
;
159 memcpy (outfile
, outbase
, outbase_length
);
160 memset (outfile_mid
, suffix_alphabet
[0], suffix_length
);
161 outfile
[outfile_length
] = 0;
162 sufindex
= xcalloc (suffix_length
, sizeof *sufindex
);
164 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
165 /* POSIX requires that if the output file name is too long for
166 its directory, `split' must fail without creating any files.
167 This must be checked for explicitly on operating systems that
168 silently truncate file names. */
170 char *dir
= dir_name (outfile
);
171 long name_max
= pathconf (dir
, _PC_NAME_MAX
);
172 if (0 <= name_max
&& name_max
< base_len (last_component (outfile
)))
173 error (EXIT_FAILURE
, ENAMETOOLONG
, "%s", outfile
);
180 /* Increment the suffix in place, if possible. */
182 size_t i
= suffix_length
;
186 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
190 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
192 error (EXIT_FAILURE
, 0, _("output file suffixes exhausted"));
196 /* Write BYTES bytes at BP to an output file.
197 If NEW_FILE_FLAG is true, open the next output file.
198 Otherwise add to the same output file already in use. */
201 cwrite (bool new_file_flag
, const char *bp
, size_t bytes
)
205 if (output_desc
>= 0 && close (output_desc
) < 0)
206 error (EXIT_FAILURE
, errno
, "%s", outfile
);
210 fprintf (stdout
, _("creating file %s\n"), quote (outfile
));
211 output_desc
= open (outfile
,
212 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
213 (S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
214 | S_IROTH
| S_IWOTH
));
216 error (EXIT_FAILURE
, errno
, "%s", outfile
);
218 if (full_write (output_desc
, bp
, bytes
) != bytes
)
219 error (EXIT_FAILURE
, errno
, "%s", outfile
);
222 /* Split into pieces of exactly N_BYTES bytes.
223 Use buffer BUF, whose size is BUFSIZE. */
226 bytes_split (uintmax_t n_bytes
, char *buf
, size_t bufsize
)
229 bool new_file_flag
= true;
231 uintmax_t to_write
= n_bytes
;
236 n_read
= full_read (STDIN_FILENO
, buf
, bufsize
);
237 if (n_read
== SAFE_READ_ERROR
)
238 error (EXIT_FAILURE
, errno
, "%s", infile
);
243 if (to_read
< to_write
)
245 if (to_read
) /* do not write 0 bytes! */
247 cwrite (new_file_flag
, bp_out
, to_read
);
249 new_file_flag
= false;
256 cwrite (new_file_flag
, bp_out
, w
);
259 new_file_flag
= true;
264 while (n_read
== bufsize
);
267 /* Split into pieces of exactly N_LINES lines.
268 Use buffer BUF, whose size is BUFSIZE. */
271 lines_split (uintmax_t n_lines
, char *buf
, size_t bufsize
)
274 char *bp
, *bp_out
, *eob
;
275 bool new_file_flag
= true;
280 n_read
= full_read (STDIN_FILENO
, buf
, bufsize
);
281 if (n_read
== SAFE_READ_ERROR
)
282 error (EXIT_FAILURE
, errno
, "%s", infile
);
288 bp
= memchr (bp
, '\n', eob
- bp
+ 1);
291 if (eob
!= bp_out
) /* do not write 0 bytes! */
293 size_t len
= eob
- bp_out
;
294 cwrite (new_file_flag
, bp_out
, len
);
295 new_file_flag
= false;
303 cwrite (new_file_flag
, bp_out
, bp
- bp_out
);
305 new_file_flag
= true;
310 while (n_read
== bufsize
);
313 /* Split into pieces that are as large as possible while still not more
314 than N_BYTES bytes, and are split on line boundaries except
315 where lines longer than N_BYTES bytes occur.
316 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
317 buffer of size N_BYTES, in case N_BYTES is very large. */
320 line_bytes_split (size_t n_bytes
)
325 size_t n_buffered
= 0;
326 char *buf
= xmalloc (n_bytes
);
330 /* Fill up the full buffer size from the input file. */
332 n_read
= full_read (STDIN_FILENO
, buf
+ n_buffered
, n_bytes
- n_buffered
);
333 if (n_read
== SAFE_READ_ERROR
)
334 error (EXIT_FAILURE
, errno
, "%s", infile
);
336 n_buffered
+= n_read
;
337 if (n_buffered
!= n_bytes
)
344 /* Find where to end this chunk. */
345 bp
= buf
+ n_buffered
;
346 if (n_buffered
== n_bytes
)
348 while (bp
> buf
&& bp
[-1] != '\n')
352 /* If chunk has no newlines, use all the chunk. */
354 bp
= buf
+ n_buffered
;
356 /* Output the chars as one output file. */
357 cwrite (true, buf
, bp
- buf
);
359 /* Discard the chars we just output; move rest of chunk
360 down to be the start of the next chunk. Source and
361 destination probably overlap. */
362 n_buffered
-= bp
- buf
;
364 memmove (buf
, bp
, n_buffered
);
370 #define FAIL_ONLY_ONE_WAY() \
373 error (0, 0, _("cannot split in more than one way")); \
374 usage (EXIT_FAILURE); \
379 main (int argc
, char **argv
)
381 struct stat stat_buf
;
384 type_undef
, type_bytes
, type_byteslines
, type_lines
, type_digits
385 } split_type
= type_undef
;
386 size_t in_blk_size
; /* optimal block size of input file device */
387 char *buf
; /* file i/o buffer */
388 size_t page_size
= getpagesize ();
390 static char const multipliers
[] = "bEGKkMmPTYZ0";
392 int digits_optind
= 0;
394 initialize_main (&argc
, &argv
);
395 set_program_name (argv
[0]);
396 setlocale (LC_ALL
, "");
397 bindtextdomain (PACKAGE
, LOCALEDIR
);
398 textdomain (PACKAGE
);
400 atexit (close_stdout
);
402 /* Parse command line options. */
404 infile
= bad_cast ( "-");
405 outbase
= bad_cast ("x");
409 /* This is the argv-index of the option we will read next. */
410 int this_optind
= optind
? optind
: 1;
412 c
= getopt_long (argc
, argv
, "0123456789C:a:b:dl:", longopts
, NULL
);
421 if (xstrtoul (optarg
, NULL
, 10, &tmp
, "") != LONGINT_OK
422 || SIZE_MAX
/ sizeof (size_t) < tmp
)
424 error (0, 0, _("%s: invalid suffix length"), optarg
);
425 usage (EXIT_FAILURE
);
432 if (split_type
!= type_undef
)
433 FAIL_ONLY_ONE_WAY ();
434 split_type
= type_bytes
;
435 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, multipliers
) != LONGINT_OK
438 error (0, 0, _("%s: invalid number of bytes"), optarg
);
439 usage (EXIT_FAILURE
);
444 if (split_type
!= type_undef
)
445 FAIL_ONLY_ONE_WAY ();
446 split_type
= type_lines
;
447 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, "") != LONGINT_OK
450 error (0, 0, _("%s: invalid number of lines"), optarg
);
451 usage (EXIT_FAILURE
);
456 if (split_type
!= type_undef
)
457 FAIL_ONLY_ONE_WAY ();
458 split_type
= type_byteslines
;
459 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, multipliers
) != LONGINT_OK
460 || n_units
== 0 || SIZE_MAX
< n_units
)
462 error (0, 0, _("%s: invalid number of bytes"), optarg
);
463 usage (EXIT_FAILURE
);
477 if (split_type
== type_undef
)
479 split_type
= type_digits
;
482 if (split_type
!= type_undef
&& split_type
!= type_digits
)
483 FAIL_ONLY_ONE_WAY ();
484 if (digits_optind
!= 0 && digits_optind
!= this_optind
)
485 n_units
= 0; /* More than one number given; ignore other. */
486 digits_optind
= this_optind
;
487 if (!DECIMAL_DIGIT_ACCUMULATE (n_units
, c
- '0', uintmax_t))
489 char buffer
[INT_BUFSIZE_BOUND (uintmax_t)];
490 error (EXIT_FAILURE
, 0,
491 _("line count option -%s%c... is too large"),
492 umaxtostr (n_units
, buffer
), c
);
497 suffix_alphabet
= "0123456789";
504 case_GETOPT_HELP_CHAR
;
506 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
509 usage (EXIT_FAILURE
);
513 /* Handle default case. */
514 if (split_type
== type_undef
)
516 split_type
= type_lines
;
522 error (0, 0, _("invalid number of lines: 0"));
523 usage (EXIT_FAILURE
);
526 /* Get out the filename arguments. */
529 infile
= argv
[optind
++];
532 outbase
= argv
[optind
++];
536 error (0, 0, _("extra operand %s"), quote (argv
[optind
]));
537 usage (EXIT_FAILURE
);
540 /* Open the input file. */
541 if (! STREQ (infile
, "-")
542 && fd_reopen (STDIN_FILENO
, infile
, O_RDONLY
, 0) < 0)
543 error (EXIT_FAILURE
, errno
, _("cannot open %s for reading"),
546 /* Binary I/O is safer when bytecounts are used. */
547 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
548 xfreopen (NULL
, "rb", stdin
);
550 /* No output file is open now. */
553 /* Get the optimal block size of input device and make a buffer. */
555 if (fstat (STDIN_FILENO
, &stat_buf
) != 0)
556 error (EXIT_FAILURE
, errno
, "%s", infile
);
557 in_blk_size
= io_blksize (stat_buf
);
559 buf
= ptr_align (xmalloc (in_blk_size
+ 1 + page_size
- 1), page_size
);
565 lines_split (n_units
, buf
, in_blk_size
);
569 bytes_split (n_units
, buf
, in_blk_size
);
572 case type_byteslines
:
573 line_bytes_split (n_units
);
580 if (close (STDIN_FILENO
) != 0)
581 error (EXIT_FAILURE
, errno
, "%s", infile
);
582 if (output_desc
>= 0 && close (output_desc
) < 0)
583 error (EXIT_FAILURE
, errno
, "%s", outfile
);