1 /* split.c -- split a file into pieces.
2 Copyright (C) 1988, 1991, 1995-2010 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
);
130 emit_ancillary_info ();
135 /* Compute the next sequential output file name and store it into the
139 next_file_name (void)
141 /* Index in suffix_alphabet of each character in the suffix. */
142 static size_t *sufindex
;
146 /* Allocate and initialize the first file name. */
148 size_t outbase_length
= strlen (outbase
);
149 size_t outfile_length
= outbase_length
+ suffix_length
;
150 if (outfile_length
+ 1 < outbase_length
)
152 outfile
= xmalloc (outfile_length
+ 1);
153 outfile_mid
= outfile
+ outbase_length
;
154 memcpy (outfile
, outbase
, outbase_length
);
155 memset (outfile_mid
, suffix_alphabet
[0], suffix_length
);
156 outfile
[outfile_length
] = 0;
157 sufindex
= xcalloc (suffix_length
, sizeof *sufindex
);
159 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
160 /* POSIX requires that if the output file name is too long for
161 its directory, `split' must fail without creating any files.
162 This must be checked for explicitly on operating systems that
163 silently truncate file names. */
165 char *dir
= dir_name (outfile
);
166 long name_max
= pathconf (dir
, _PC_NAME_MAX
);
167 if (0 <= name_max
&& name_max
< base_len (last_component (outfile
)))
168 error (EXIT_FAILURE
, ENAMETOOLONG
, "%s", outfile
);
175 /* Increment the suffix in place, if possible. */
177 size_t i
= suffix_length
;
181 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
185 outfile_mid
[i
] = suffix_alphabet
[sufindex
[i
]];
187 error (EXIT_FAILURE
, 0, _("output file suffixes exhausted"));
191 /* Write BYTES bytes at BP to an output file.
192 If NEW_FILE_FLAG is true, open the next output file.
193 Otherwise add to the same output file already in use. */
196 cwrite (bool new_file_flag
, const char *bp
, size_t bytes
)
200 if (output_desc
>= 0 && close (output_desc
) < 0)
201 error (EXIT_FAILURE
, errno
, "%s", outfile
);
205 fprintf (stdout
, _("creating file %s\n"), quote (outfile
));
206 output_desc
= open (outfile
,
207 O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
208 (S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
209 | S_IROTH
| S_IWOTH
));
211 error (EXIT_FAILURE
, errno
, "%s", outfile
);
213 if (full_write (output_desc
, bp
, bytes
) != bytes
)
214 error (EXIT_FAILURE
, errno
, "%s", outfile
);
217 /* Split into pieces of exactly N_BYTES bytes.
218 Use buffer BUF, whose size is BUFSIZE. */
221 bytes_split (uintmax_t n_bytes
, char *buf
, size_t bufsize
)
224 bool new_file_flag
= true;
226 uintmax_t to_write
= n_bytes
;
231 n_read
= full_read (STDIN_FILENO
, buf
, bufsize
);
232 if (n_read
== SAFE_READ_ERROR
)
233 error (EXIT_FAILURE
, errno
, "%s", infile
);
238 if (to_read
< to_write
)
240 if (to_read
) /* do not write 0 bytes! */
242 cwrite (new_file_flag
, bp_out
, to_read
);
244 new_file_flag
= false;
251 cwrite (new_file_flag
, bp_out
, w
);
254 new_file_flag
= true;
259 while (n_read
== bufsize
);
262 /* Split into pieces of exactly N_LINES lines.
263 Use buffer BUF, whose size is BUFSIZE. */
266 lines_split (uintmax_t n_lines
, char *buf
, size_t bufsize
)
269 char *bp
, *bp_out
, *eob
;
270 bool new_file_flag
= true;
275 n_read
= full_read (STDIN_FILENO
, buf
, bufsize
);
276 if (n_read
== SAFE_READ_ERROR
)
277 error (EXIT_FAILURE
, errno
, "%s", infile
);
283 bp
= memchr (bp
, '\n', eob
- bp
+ 1);
286 if (eob
!= bp_out
) /* do not write 0 bytes! */
288 size_t len
= eob
- bp_out
;
289 cwrite (new_file_flag
, bp_out
, len
);
290 new_file_flag
= false;
298 cwrite (new_file_flag
, bp_out
, bp
- bp_out
);
300 new_file_flag
= true;
305 while (n_read
== bufsize
);
308 /* Split into pieces that are as large as possible while still not more
309 than N_BYTES bytes, and are split on line boundaries except
310 where lines longer than N_BYTES bytes occur.
311 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
312 buffer of size N_BYTES, in case N_BYTES is very large. */
315 line_bytes_split (size_t n_bytes
)
320 size_t n_buffered
= 0;
321 char *buf
= xmalloc (n_bytes
);
325 /* Fill up the full buffer size from the input file. */
327 n_read
= full_read (STDIN_FILENO
, buf
+ n_buffered
, n_bytes
- n_buffered
);
328 if (n_read
== SAFE_READ_ERROR
)
329 error (EXIT_FAILURE
, errno
, "%s", infile
);
331 n_buffered
+= n_read
;
332 if (n_buffered
!= n_bytes
)
339 /* Find where to end this chunk. */
340 bp
= buf
+ n_buffered
;
341 if (n_buffered
== n_bytes
)
343 while (bp
> buf
&& bp
[-1] != '\n')
347 /* If chunk has no newlines, use all the chunk. */
349 bp
= buf
+ n_buffered
;
351 /* Output the chars as one output file. */
352 cwrite (true, buf
, bp
- buf
);
354 /* Discard the chars we just output; move rest of chunk
355 down to be the start of the next chunk. Source and
356 destination probably overlap. */
357 n_buffered
-= bp
- buf
;
359 memmove (buf
, bp
, n_buffered
);
365 #define FAIL_ONLY_ONE_WAY() \
368 error (0, 0, _("cannot split in more than one way")); \
369 usage (EXIT_FAILURE); \
374 main (int argc
, char **argv
)
376 struct stat stat_buf
;
379 type_undef
, type_bytes
, type_byteslines
, type_lines
, type_digits
380 } split_type
= type_undef
;
381 size_t in_blk_size
; /* optimal block size of input file device */
382 char *buf
; /* file i/o buffer */
383 size_t page_size
= getpagesize ();
385 static char const multipliers
[] = "bEGKkMmPTYZ0";
387 int digits_optind
= 0;
389 initialize_main (&argc
, &argv
);
390 set_program_name (argv
[0]);
391 setlocale (LC_ALL
, "");
392 bindtextdomain (PACKAGE
, LOCALEDIR
);
393 textdomain (PACKAGE
);
395 atexit (close_stdout
);
397 /* Parse command line options. */
399 infile
= bad_cast ( "-");
400 outbase
= bad_cast ("x");
404 /* This is the argv-index of the option we will read next. */
405 int this_optind
= optind
? optind
: 1;
407 c
= getopt_long (argc
, argv
, "0123456789C:a:b:dl:", longopts
, NULL
);
416 if (xstrtoul (optarg
, NULL
, 10, &tmp
, "") != LONGINT_OK
417 || SIZE_MAX
/ sizeof (size_t) < tmp
)
419 error (0, 0, _("%s: invalid suffix length"), optarg
);
420 usage (EXIT_FAILURE
);
427 if (split_type
!= type_undef
)
428 FAIL_ONLY_ONE_WAY ();
429 split_type
= type_bytes
;
430 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, multipliers
) != LONGINT_OK
433 error (0, 0, _("%s: invalid number of bytes"), optarg
);
434 usage (EXIT_FAILURE
);
439 if (split_type
!= type_undef
)
440 FAIL_ONLY_ONE_WAY ();
441 split_type
= type_lines
;
442 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, "") != LONGINT_OK
445 error (0, 0, _("%s: invalid number of lines"), optarg
);
446 usage (EXIT_FAILURE
);
451 if (split_type
!= type_undef
)
452 FAIL_ONLY_ONE_WAY ();
453 split_type
= type_byteslines
;
454 if (xstrtoumax (optarg
, NULL
, 10, &n_units
, multipliers
) != LONGINT_OK
455 || n_units
== 0 || SIZE_MAX
< n_units
)
457 error (0, 0, _("%s: invalid number of bytes"), optarg
);
458 usage (EXIT_FAILURE
);
472 if (split_type
== type_undef
)
474 split_type
= type_digits
;
477 if (split_type
!= type_undef
&& split_type
!= type_digits
)
478 FAIL_ONLY_ONE_WAY ();
479 if (digits_optind
!= 0 && digits_optind
!= this_optind
)
480 n_units
= 0; /* More than one number given; ignore other. */
481 digits_optind
= this_optind
;
482 if (!DECIMAL_DIGIT_ACCUMULATE (n_units
, c
- '0', uintmax_t))
484 char buffer
[INT_BUFSIZE_BOUND (uintmax_t)];
485 error (EXIT_FAILURE
, 0,
486 _("line count option -%s%c... is too large"),
487 umaxtostr (n_units
, buffer
), c
);
492 suffix_alphabet
= "0123456789";
499 case_GETOPT_HELP_CHAR
;
501 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
504 usage (EXIT_FAILURE
);
508 /* Handle default case. */
509 if (split_type
== type_undef
)
511 split_type
= type_lines
;
517 error (0, 0, _("invalid number of lines: 0"));
518 usage (EXIT_FAILURE
);
521 /* Get out the filename arguments. */
524 infile
= argv
[optind
++];
527 outbase
= argv
[optind
++];
531 error (0, 0, _("extra operand %s"), quote (argv
[optind
]));
532 usage (EXIT_FAILURE
);
535 /* Open the input file. */
536 if (! STREQ (infile
, "-")
537 && fd_reopen (STDIN_FILENO
, infile
, O_RDONLY
, 0) < 0)
538 error (EXIT_FAILURE
, errno
, _("cannot open %s for reading"),
541 /* Binary I/O is safer when bytecounts are used. */
542 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
543 xfreopen (NULL
, "rb", stdin
);
545 /* No output file is open now. */
548 /* Get the optimal block size of input device and make a buffer. */
550 if (fstat (STDIN_FILENO
, &stat_buf
) != 0)
551 error (EXIT_FAILURE
, errno
, "%s", infile
);
552 in_blk_size
= io_blksize (stat_buf
);
554 buf
= ptr_align (xmalloc (in_blk_size
+ 1 + page_size
- 1), page_size
);
560 lines_split (n_units
, buf
, in_blk_size
);
564 bytes_split (n_units
, buf
, in_blk_size
);
567 case type_byteslines
:
568 line_bytes_split (n_units
);
575 if (close (STDIN_FILENO
) != 0)
576 error (EXIT_FAILURE
, errno
, "%s", infile
);
577 if (output_desc
>= 0 && close (output_desc
) < 0)
578 error (EXIT_FAILURE
, errno
, "%s", outfile
);