Sanitize environment.
[coreutils.git] / src / split.c
blob8ada6002fa7154173f4823cad18bbcc7342e2522
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)
7 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, 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.
20 To do:
21 * Implement -t CHAR or -t REGEX to specify break characters other
22 than newline. */
24 #include <config.h>
26 #include <stdio.h>
27 #include <getopt.h>
28 #include <sys/types.h>
30 #include "system.h"
31 #include "dirname.h"
32 #include "error.h"
33 #include "getpagesize.h"
34 #include "full-read.h"
35 #include "full-write.h"
36 #include "inttostr.h"
37 #include "posixver.h"
38 #include "quote.h"
39 #include "safe-read.h"
40 #include "xstrtol.h"
42 /* The official name of this program (e.g., no `g' prefix). */
43 #define PROGRAM_NAME "split"
45 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
47 #define DEFAULT_SUFFIX_LENGTH 2
49 /* The name this program was run with. */
50 char *program_name;
52 /* Base name of output files. */
53 static char const *outbase;
55 /* Name of output files. */
56 static char *outfile;
58 /* Pointer to the end of the prefix in OUTFILE.
59 Suffixes are inserted here. */
60 static char *outfile_mid;
62 /* Length of OUTFILE's suffix. */
63 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
65 /* Alphabet of characters to use in suffix. */
66 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
68 /* Name of input file. May be "-". */
69 static char *infile;
71 /* Descriptor on which input file is open. */
72 static int input_desc;
74 /* Descriptor on which output file is open. */
75 static int output_desc;
77 /* If true, print a diagnostic on standard error just before each
78 output file is opened. */
79 static bool verbose;
81 /* For long options that have no equivalent short option, use a
82 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
83 enum
85 VERBOSE_OPTION = CHAR_MAX + 1
88 static struct option const longopts[] =
90 {"bytes", required_argument, NULL, 'b'},
91 {"lines", required_argument, NULL, 'l'},
92 {"line-bytes", required_argument, NULL, 'C'},
93 {"suffix-length", required_argument, NULL, 'a'},
94 {"numeric-suffixes", no_argument, NULL, 'd'},
95 {"verbose", no_argument, NULL, VERBOSE_OPTION},
96 {GETOPT_HELP_OPTION_DECL},
97 {GETOPT_VERSION_OPTION_DECL},
98 {NULL, 0, NULL, 0}
101 void
102 usage (int status)
104 if (status != EXIT_SUCCESS)
105 fprintf (stderr, _("Try `%s --help' for more information.\n"),
106 program_name);
107 else
109 printf (_("\
110 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
112 program_name);
113 fputs (_("\
114 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
115 PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input.\n\
117 "), stdout);
118 fputs (_("\
119 Mandatory arguments to long options are mandatory for short options too.\n\
120 "), stdout);
121 fprintf (stdout, _("\
122 -a, --suffix-length=N use suffixes of length N (default %d)\n\
123 -b, --bytes=SIZE put SIZE bytes per output file\n\
124 -C, --line-bytes=SIZE put at most SIZE bytes of lines per output file\n\
125 -d, --numeric-suffixes use numeric suffixes instead of alphabetic\n\
126 -l, --lines=NUMBER put NUMBER lines per output file\n\
127 "), DEFAULT_SUFFIX_LENGTH);
128 fputs (_("\
129 --verbose print a diagnostic to standard error just\n\
130 before each output file is opened\n\
131 "), stdout);
132 fputs (HELP_OPTION_DESCRIPTION, stdout);
133 fputs (VERSION_OPTION_DESCRIPTION, stdout);
134 fputs (_("\
136 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
137 "), stdout);
138 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
140 exit (status);
143 /* Compute the next sequential output file name and store it into the
144 string `outfile'. */
146 static void
147 next_file_name (void)
149 /* Index in suffix_alphabet of each character in the suffix. */
150 static size_t *sufindex;
152 if (! outfile)
154 /* Allocate and initialize the first file name. */
156 size_t outbase_length = strlen (outbase);
157 size_t outfile_length = outbase_length + suffix_length;
158 if (outfile_length + 1 < outbase_length)
159 xalloc_die ();
160 outfile = xmalloc (outfile_length + 1);
161 outfile_mid = outfile + outbase_length;
162 memcpy (outfile, outbase, outbase_length);
163 memset (outfile_mid, suffix_alphabet[0], suffix_length);
164 outfile[outfile_length] = 0;
165 sufindex = xcalloc (suffix_length, sizeof *sufindex);
167 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
168 /* POSIX requires that if the output file name is too long for
169 its directory, `split' must fail without creating any files.
170 This must be checked for explicitly on operating systems that
171 silently truncate file names. */
173 char *dir = dir_name (outfile);
174 long name_max = pathconf (dir, _PC_NAME_MAX);
175 if (0 <= name_max && name_max < base_len (base_name (outfile)))
176 error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
177 free (dir);
179 #endif
181 else
183 /* Increment the suffix in place, if possible. */
185 size_t i = suffix_length;
186 while (i-- != 0)
188 sufindex[i]++;
189 outfile_mid[i] = suffix_alphabet[sufindex[i]];
190 if (outfile_mid[i])
191 return;
192 sufindex[i] = 0;
193 outfile_mid[i] = suffix_alphabet[sufindex[i]];
195 error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
199 /* Write BYTES bytes at BP to an output file.
200 If NEW_FILE_FLAG is true, open the next output file.
201 Otherwise add to the same output file already in use. */
203 static void
204 cwrite (bool new_file_flag, const char *bp, size_t bytes)
206 if (new_file_flag)
208 if (output_desc >= 0 && close (output_desc) < 0)
209 error (EXIT_FAILURE, errno, "%s", outfile);
211 next_file_name ();
212 if (verbose)
213 fprintf (stderr, _("creating file `%s'\n"), outfile);
214 output_desc = open (outfile,
215 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
216 if (output_desc < 0)
217 error (EXIT_FAILURE, errno, "%s", outfile);
219 if (full_write (output_desc, bp, bytes) != bytes)
220 error (EXIT_FAILURE, errno, "%s", outfile);
223 /* Split into pieces of exactly N_BYTES bytes.
224 Use buffer BUF, whose size is BUFSIZE. */
226 static void
227 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
229 size_t n_read;
230 bool new_file_flag = true;
231 size_t to_read;
232 uintmax_t to_write = n_bytes;
233 char *bp_out;
237 n_read = full_read (input_desc, buf, bufsize);
238 if (n_read == SAFE_READ_ERROR)
239 error (EXIT_FAILURE, errno, "%s", infile);
240 bp_out = buf;
241 to_read = n_read;
242 for (;;)
244 if (to_read < to_write)
246 if (to_read) /* do not write 0 bytes! */
248 cwrite (new_file_flag, bp_out, to_read);
249 to_write -= to_read;
250 new_file_flag = false;
252 break;
254 else
256 size_t w = to_write;
257 cwrite (new_file_flag, bp_out, w);
258 bp_out += w;
259 to_read -= w;
260 new_file_flag = true;
261 to_write = n_bytes;
265 while (n_read == bufsize);
268 /* Split into pieces of exactly N_LINES lines.
269 Use buffer BUF, whose size is BUFSIZE. */
271 static void
272 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
274 size_t n_read;
275 char *bp, *bp_out, *eob;
276 bool new_file_flag = true;
277 uintmax_t n = 0;
281 n_read = full_read (input_desc, buf, bufsize);
282 if (n_read == SAFE_READ_ERROR)
283 error (EXIT_FAILURE, errno, "%s", infile);
284 bp = bp_out = buf;
285 eob = bp + n_read;
286 *eob = '\n';
287 for (;;)
289 bp = memchr (bp, '\n', eob - bp + 1);
290 if (bp == eob)
292 if (eob != bp_out) /* do not write 0 bytes! */
294 size_t len = eob - bp_out;
295 cwrite (new_file_flag, bp_out, len);
296 new_file_flag = false;
298 break;
301 ++bp;
302 if (++n >= n_lines)
304 cwrite (new_file_flag, bp_out, bp - bp_out);
305 bp_out = bp;
306 new_file_flag = true;
307 n = 0;
311 while (n_read == bufsize);
314 /* Split into pieces that are as large as possible while still not more
315 than N_BYTES bytes, and are split on line boundaries except
316 where lines longer than N_BYTES bytes occur.
317 FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
318 buffer of size N_BYTES, in case N_BYTES is very large. */
320 static void
321 line_bytes_split (size_t n_bytes)
323 size_t n_read;
324 char *bp;
325 bool eof = false;
326 size_t n_buffered = 0;
327 char *buf = xmalloc (n_bytes);
331 /* Fill up the full buffer size from the input file. */
333 n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
334 if (n_read == SAFE_READ_ERROR)
335 error (EXIT_FAILURE, errno, "%s", infile);
337 n_buffered += n_read;
338 if (n_buffered != n_bytes)
339 eof = true;
341 /* Find where to end this chunk. */
342 bp = buf + n_buffered;
343 if (n_buffered == n_bytes)
345 while (bp > buf && bp[-1] != '\n')
346 bp--;
349 /* If chunk has no newlines, use all the chunk. */
350 if (bp == buf)
351 bp = buf + n_buffered;
353 /* Output the chars as one output file. */
354 cwrite (true, buf, bp - buf);
356 /* Discard the chars we just output; move rest of chunk
357 down to be the start of the next chunk. Source and
358 destination probably overlap. */
359 n_buffered -= bp - buf;
360 if (n_buffered > 0)
361 memmove (buf, bp, n_buffered);
363 while (!eof);
364 free (buf);
367 #define FAIL_ONLY_ONE_WAY() \
368 do \
370 error (0, 0, _("cannot split in more than one way")); \
371 usage (EXIT_FAILURE); \
373 while (0)
376 main (int argc, char **argv)
378 struct stat stat_buf;
379 enum
381 type_undef, type_bytes, type_byteslines, type_lines, type_digits
382 } split_type = type_undef;
383 size_t in_blk_size; /* optimal block size of input file device */
384 char *buf; /* file i/o buffer */
385 size_t page_size = getpagesize ();
386 uintmax_t n_units;
387 int c;
388 int digits_optind = 0;
390 initialize_main (&argc, &argv);
391 program_name = argv[0];
392 setlocale (LC_ALL, "");
393 bindtextdomain (PACKAGE, LOCALEDIR);
394 textdomain (PACKAGE);
396 atexit (close_stdout);
398 /* Parse command line options. */
400 infile = "-";
401 outbase = "x";
403 while (1)
405 /* This is the argv-index of the option we will read next. */
406 int this_optind = optind ? optind : 1;
408 c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
409 if (c == -1)
410 break;
412 switch (c)
414 case 'a':
416 unsigned long tmp;
417 if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
418 || SIZE_MAX / sizeof (size_t) < tmp)
420 error (0, 0, _("%s: invalid suffix length"), optarg);
421 usage (EXIT_FAILURE);
423 suffix_length = tmp;
425 break;
427 case 'b':
428 if (split_type != type_undef)
429 FAIL_ONLY_ONE_WAY ();
430 split_type = type_bytes;
431 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
432 || n_units == 0)
434 error (0, 0, _("%s: invalid number of bytes"), optarg);
435 usage (EXIT_FAILURE);
437 break;
439 case 'l':
440 if (split_type != type_undef)
441 FAIL_ONLY_ONE_WAY ();
442 split_type = type_lines;
443 if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
444 || n_units == 0)
446 error (0, 0, _("%s: invalid number of lines"), optarg);
447 usage (EXIT_FAILURE);
449 break;
451 case 'C':
452 if (split_type != type_undef)
453 FAIL_ONLY_ONE_WAY ();
454 split_type = type_byteslines;
455 if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
456 || n_units == 0 || SIZE_MAX < n_units)
458 error (0, 0, _("%s: invalid number of bytes"), optarg);
459 usage (EXIT_FAILURE);
461 break;
463 case '0':
464 case '1':
465 case '2':
466 case '3':
467 case '4':
468 case '5':
469 case '6':
470 case '7':
471 case '8':
472 case '9':
473 if (split_type == type_undef)
475 split_type = type_digits;
476 n_units = 0;
478 if (split_type != type_undef && split_type != type_digits)
479 FAIL_ONLY_ONE_WAY ();
480 if (digits_optind != 0 && digits_optind != this_optind)
481 n_units = 0; /* More than one number given; ignore other. */
482 digits_optind = this_optind;
483 if (UINTMAX_MAX / 10 < n_units
484 || n_units * 10 + c - '0' < n_units * 10)
486 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
487 error (EXIT_FAILURE, 0,
488 _("line count option -%s%c... is too large"),
489 umaxtostr (n_units, buffer), c);
491 n_units = n_units * 10 + c - '0';
492 break;
494 case 'd':
495 suffix_alphabet = "0123456789";
496 break;
498 case VERBOSE_OPTION:
499 verbose = true;
500 break;
502 case_GETOPT_HELP_CHAR;
504 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
506 default:
507 usage (EXIT_FAILURE);
511 if (digits_optind && 200112 <= posix2_version ())
513 char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
514 char const *a = umaxtostr (n_units, buffer);
515 error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
516 usage (EXIT_FAILURE);
519 /* Handle default case. */
520 if (split_type == type_undef)
522 split_type = type_lines;
523 n_units = 1000;
526 if (n_units == 0)
528 /* FIXME: be sure to remove this block when removing
529 support for obsolete options like `-10'. */
530 error (0, 0, _("invalid number of lines: 0"));
531 usage (EXIT_FAILURE);
534 /* Get out the filename arguments. */
536 if (optind < argc)
537 infile = argv[optind++];
539 if (optind < argc)
540 outbase = argv[optind++];
542 if (optind < argc)
544 error (0, 0, _("extra operand %s"), quote (argv[optind]));
545 usage (EXIT_FAILURE);
548 /* Open the input file. */
549 if (STREQ (infile, "-"))
550 input_desc = STDIN_FILENO;
551 else
553 input_desc = open (infile, O_RDONLY);
554 if (input_desc < 0)
555 error (EXIT_FAILURE, errno, "%s", infile);
557 /* Binary I/O is safer when bytecounts are used. */
558 SET_BINARY (input_desc);
560 /* No output file is open now. */
561 output_desc = -1;
563 /* Get the optimal block size of input device and make a buffer. */
565 if (fstat (input_desc, &stat_buf) < 0)
566 error (EXIT_FAILURE, errno, "%s", infile);
567 in_blk_size = ST_BLKSIZE (stat_buf);
569 buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
571 switch (split_type)
573 case type_digits:
574 case type_lines:
575 lines_split (n_units, buf, in_blk_size);
576 break;
578 case type_bytes:
579 bytes_split (n_units, buf, in_blk_size);
580 break;
582 case type_byteslines:
583 line_bytes_split (n_units);
584 break;
586 default:
587 abort ();
590 if (close (input_desc) < 0)
591 error (EXIT_FAILURE, errno, "%s", infile);
592 if (output_desc >= 0 && close (output_desc) < 0)
593 error (EXIT_FAILURE, errno, "%s", outfile);
595 exit (EXIT_SUCCESS);