(invalid-j): New partial test for the above fix.
[coreutils.git] / src / split.c
blob49422656bc89812719af9f946ed79d475098e9af
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 "full-read.h"
34 #include "full-write.h"
35 #include "inttostr.h"
36 #include "posixver.h"
37 #include "safe-read.h"
38 #include "xstrtol.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. */
48 char *program_name;
50 /* Base name of output files. */
51 static char const *outbase;
53 /* Name of output files. */
54 static char *outfile;
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 "-". */
67 static char *infile;
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. */
77 static int verbose;
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},
89 {NULL, 0, NULL, 0}
92 void
93 usage (int status)
95 if (status != EXIT_SUCCESS)
96 fprintf (stderr, _("Try `%s --help' for more information.\n"),
97 program_name);
98 else
100 printf (_("\
101 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
103 program_name);
104 fputs (_("\
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\
108 "), stdout);
109 fputs (_("\
110 Mandatory arguments to long options are mandatory for short options too.\n\
111 "), stdout);
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);
119 fputs (_("\
120 --verbose print a diagnostic to standard error just\n\
121 before each output file is opened\n\
122 "), stdout);
123 fputs (HELP_OPTION_DESCRIPTION, stdout);
124 fputs (VERSION_OPTION_DESCRIPTION, stdout);
125 fputs (_("\
127 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
128 "), stdout);
129 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
131 exit (status);
134 /* Compute the next sequential output file name and store it into the
135 string `outfile'. */
137 static void
138 next_file_name (void)
140 /* Index in suffix_alphabet of each character in the suffix. */
141 static size_t *sufindex;
143 if (! outfile)
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)
150 xalloc_die ();
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);
168 free (dir);
170 #endif
172 else
174 /* Increment the suffix in place, if possible. */
176 size_t i = suffix_length;
177 while (i-- != 0)
179 sufindex[i]++;
180 outfile_mid[i] = suffix_alphabet[sufindex[i]];
181 if (outfile_mid[i])
182 return;
183 sufindex[i] = 0;
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. */
194 static void
195 cwrite (int new_file_flag, const char *bp, size_t bytes)
197 if (new_file_flag)
199 if (output_desc >= 0 && close (output_desc) < 0)
200 error (EXIT_FAILURE, errno, "%s", outfile);
202 next_file_name ();
203 if (verbose)
204 fprintf (stderr, _("creating file `%s'\n"), outfile);
205 output_desc = open (outfile,
206 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
207 if (output_desc < 0)
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. */
217 static void
218 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
220 size_t n_read;
221 int new_file_flag = 1;
222 size_t to_read;
223 uintmax_t to_write = n_bytes;
224 char *bp_out;
228 n_read = full_read (input_desc, buf, bufsize);
229 if (n_read == SAFE_READ_ERROR)
230 error (EXIT_FAILURE, errno, "%s", infile);
231 bp_out = buf;
232 to_read = n_read;
233 for (;;)
235 if (to_read < to_write)
237 if (to_read) /* do not write 0 bytes! */
239 cwrite (new_file_flag, bp_out, to_read);
240 to_write -= to_read;
241 new_file_flag = 0;
243 break;
245 else
247 size_t w = to_write;
248 cwrite (new_file_flag, bp_out, w);
249 bp_out += w;
250 to_read -= w;
251 new_file_flag = 1;
252 to_write = n_bytes;
256 while (n_read == bufsize);
259 /* Split into pieces of exactly N_LINES lines.
260 Use buffer BUF, whose size is BUFSIZE. */
262 static void
263 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
265 size_t n_read;
266 char *bp, *bp_out, *eob;
267 int new_file_flag = 1;
268 uintmax_t n = 0;
272 n_read = full_read (input_desc, buf, bufsize);
273 if (n_read == SAFE_READ_ERROR)
274 error (EXIT_FAILURE, errno, "%s", infile);
275 bp = bp_out = buf;
276 eob = bp + n_read;
277 *eob = '\n';
278 for (;;)
280 bp = memchr (bp, '\n', eob - bp + 1);
281 if (bp == eob)
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);
287 new_file_flag = 0;
289 break;
292 ++bp;
293 if (++n >= n_lines)
295 cwrite (new_file_flag, bp_out, bp - bp_out);
296 bp_out = bp;
297 new_file_flag = 1;
298 n = 0;
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. */
311 static void
312 line_bytes_split (size_t n_bytes)
314 size_t n_read;
315 char *bp;
316 int eof = 0;
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)
330 eof = 1;
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')
337 bp--;
340 /* If chunk has no newlines, use all the chunk. */
341 if (bp == buf)
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;
351 if (n_buffered > 0)
352 memmove (buf, bp, n_buffered);
354 while (!eof);
355 free (buf);
358 #define FAIL_ONLY_ONE_WAY() \
359 do \
361 error (0, 0, _("cannot split in more than one way")); \
362 usage (EXIT_FAILURE); \
364 while (0)
367 main (int argc, char **argv)
369 struct stat stat_buf;
370 enum
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 */
376 uintmax_t n_units;
377 int c;
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. */
390 infile = "-";
391 outbase = "x";
393 while (1)
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);
399 if (c == -1)
400 break;
402 switch (c)
404 case 0:
405 break;
407 case 'a':
409 unsigned long tmp;
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);
416 suffix_length = tmp;
418 break;
420 case 'b':
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
425 || n_units == 0)
427 error (0, 0, _("%s: invalid number of bytes"), optarg);
428 usage (EXIT_FAILURE);
430 break;
432 case 'l':
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
437 || n_units == 0)
439 error (0, 0, _("%s: invalid number of lines"), optarg);
440 usage (EXIT_FAILURE);
442 break;
444 case 'C':
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);
454 break;
456 case '0':
457 case '1':
458 case '2':
459 case '3':
460 case '4':
461 case '5':
462 case '6':
463 case '7':
464 case '8':
465 case '9':
466 if (split_type == type_undef)
468 split_type = type_digits;
469 n_units = 0;
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';
485 break;
487 case 'd':
488 suffix_alphabet = "0123456789";
489 break;
491 case_GETOPT_HELP_CHAR;
493 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
495 default:
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;
512 n_units = 1000;
515 if (n_units == 0)
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. */
525 if (optind < argc)
526 infile = argv[optind++];
528 if (optind < argc)
529 outbase = argv[optind++];
531 if (optind < argc)
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;
540 else
542 input_desc = open (infile, O_RDONLY);
543 if (input_desc < 0)
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. */
550 output_desc = -1;
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);
560 switch (split_type)
562 case type_digits:
563 case type_lines:
564 lines_split (n_units, buf, in_blk_size);
565 break;
567 case type_bytes:
568 bytes_split (n_units, buf, in_blk_size);
569 break;
571 case type_byteslines:
572 line_bytes_split (n_units);
573 break;
575 default:
576 abort ();
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);
584 exit (EXIT_SUCCESS);