(WRITTEN_BY): Rename from AUTHORS.
[platform/upstream/coreutils.git] / src / split.c
1 /* split.c -- split a file into pieces.
2    Copyright (C) 88, 91, 1995-2003 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17 \f
18 /* By tege@sics.se, with rms.
19
20    To do:
21    * Implement -t CHAR or -t REGEX to specify break characters other
22      than newline. */
23
24 #include <config.h>
25
26 #include <stdio.h>
27 #include <getopt.h>
28 #include <sys/types.h>
29
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"
39
40 /* The official name of this program (e.g., no `g' prefix).  */
41 #define PROGRAM_NAME "split"
42
43 #define WRITTEN_BY _("Written by Torbjorn Granlund and Richard M. Stallman.")
44
45 #define DEFAULT_SUFFIX_LENGTH 2
46
47 /* The name this program was run with. */
48 char *program_name;
49
50 /* Base name of output files.  */
51 static char const *outbase;
52
53 /* Name of output files.  */
54 static char *outfile;
55
56 /* Pointer to the end of the prefix in OUTFILE.
57    Suffixes are inserted here.  */
58 static char *outfile_mid;
59
60 /* Length of OUTFILE's suffix.  */
61 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
62
63 /* Alphabet of characters to use in suffix.  */
64 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
65
66 /* Name of input file.  May be "-".  */
67 static char *infile;
68
69 /* Descriptor on which input file is open.  */
70 static int input_desc;
71
72 /* Descriptor on which output file is open.  */
73 static int output_desc;
74
75 /* If nonzero, print a diagnostic on standard error just before each
76    output file is opened. */
77 static int verbose;
78
79 static struct option const longopts[] =
80 {
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}
90 };
91
92 void
93 usage (int status)
94 {
95   if (status != 0)
96     fprintf (stderr, _("Try `%s --help' for more information.\n"),
97              program_name);
98   else
99     {
100       printf (_("\
101 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
102 "),
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\
107 \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 (_("\
126 \n\
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);
130     }
131   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
132 }
133
134 /* Compute the next sequential output file name and store it into the
135    string `outfile'.  */
136
137 static void
138 next_file_name (void)
139 {
140   /* Index in suffix_alphabet of each character in the suffix.  */
141   static size_t *sufindex;
142
143   if (! outfile)
144     {
145       /* Allocate and initialize the first file name.  */
146
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 (size_t));
157
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.  */
163       {
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);
169       }
170 #endif
171     }
172   else
173     {
174       /* Increment the suffix in place, if possible.  */
175
176       size_t i = suffix_length;
177       while (i-- != 0)
178         {
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]];
185         }
186       error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
187     }
188 }
189
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.  */
193
194 static void
195 cwrite (int new_file_flag, const char *bp, size_t bytes)
196 {
197   if (new_file_flag)
198     {
199       if (output_desc >= 0 && close (output_desc) < 0)
200         error (EXIT_FAILURE, errno, "%s", outfile);
201
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);
209     }
210   if (full_write (output_desc, bp, bytes) != bytes)
211     error (EXIT_FAILURE, errno, "%s", outfile);
212 }
213
214 /* Split into pieces of exactly N_BYTES bytes.
215    Use buffer BUF, whose size is BUFSIZE.  */
216
217 static void
218 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
219 {
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;
225
226   do
227     {
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 (;;)
234         {
235           if (to_read < to_write)
236             {
237               if (to_read)      /* do not write 0 bytes! */
238                 {
239                   cwrite (new_file_flag, bp_out, to_read);
240                   to_write -= to_read;
241                   new_file_flag = 0;
242                 }
243               break;
244             }
245           else
246             {
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;
253             }
254         }
255     }
256   while (n_read == bufsize);
257 }
258
259 /* Split into pieces of exactly N_LINES lines.
260    Use buffer BUF, whose size is BUFSIZE.  */
261
262 static void
263 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
264 {
265   size_t n_read;
266   char *bp, *bp_out, *eob;
267   int new_file_flag = 1;
268   uintmax_t n = 0;
269
270   do
271     {
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 (;;)
279         {
280           bp = memchr (bp, '\n', eob - bp + 1);
281           if (bp == eob)
282             {
283               if (eob != bp_out) /* do not write 0 bytes! */
284                 {
285                   size_t len = eob - bp_out;
286                   cwrite (new_file_flag, bp_out, len);
287                   new_file_flag = 0;
288                 }
289               break;
290             }
291
292           ++bp;
293           if (++n >= n_lines)
294             {
295               cwrite (new_file_flag, bp_out, bp - bp_out);
296               bp_out = bp;
297               new_file_flag = 1;
298               n = 0;
299             }
300         }
301     }
302   while (n_read == bufsize);
303 }
304 \f
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.  */
310
311 static void
312 line_bytes_split (size_t n_bytes)
313 {
314   size_t n_read;
315   char *bp;
316   int eof = 0;
317   size_t n_buffered = 0;
318   char *buf = xmalloc (n_bytes);
319
320   do
321     {
322       /* Fill up the full buffer size from the input file.  */
323
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);
327
328       n_buffered += n_read;
329       if (n_buffered != n_bytes)
330         eof = 1;
331
332       /* Find where to end this chunk.  */
333       bp = buf + n_buffered;
334       if (n_buffered == n_bytes)
335         {
336           while (bp > buf && bp[-1] != '\n')
337             bp--;
338         }
339
340       /* If chunk has no newlines, use all the chunk.  */
341       if (bp == buf)
342         bp = buf + n_buffered;
343
344       /* Output the chars as one output file.  */
345       cwrite (1, buf, bp - buf);
346
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);
353     }
354   while (!eof);
355   free (buf);
356 }
357
358 #define FAIL_ONLY_ONE_WAY()                                     \
359   do                                                            \
360     {                                                           \
361       error (0, 0, _("cannot split in more than one way"));     \
362       usage (EXIT_FAILURE);                                     \
363     }                                                           \
364   while (0)
365
366 int
367 main (int argc, char **argv)
368 {
369   struct stat stat_buf;
370   enum
371     {
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;
379
380   initialize_main (&argc, &argv);
381   program_name = argv[0];
382   setlocale (LC_ALL, "");
383   bindtextdomain (PACKAGE, LOCALEDIR);
384   textdomain (PACKAGE);
385
386   atexit (close_stdout);
387
388   /* Parse command line options.  */
389
390   infile = "-";
391   outbase = "x";
392
393   while (1)
394     {
395       /* This is the argv-index of the option we will read next.  */
396       int this_optind = optind ? optind : 1;
397
398       c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
399       if (c == -1)
400         break;
401
402       switch (c)
403         {
404         case 0:
405           break;
406
407         case 'a':
408           {
409             unsigned long tmp;
410             if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
411                 || SIZE_MAX / sizeof (size_t) < tmp)
412               {
413                 error (0, 0, _("%s: invalid suffix length"), optarg);
414                 usage (EXIT_FAILURE);
415               }
416             suffix_length = tmp;
417           }
418           break;
419
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)
426             {
427               error (0, 0, _("%s: invalid number of bytes"), optarg);
428               usage (EXIT_FAILURE);
429             }
430           break;
431
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)
438             {
439               error (0, 0, _("%s: invalid number of lines"), optarg);
440               usage (EXIT_FAILURE);
441             }
442           break;
443
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)
450             {
451               error (0, 0, _("%s: invalid number of bytes"), optarg);
452               usage (EXIT_FAILURE);
453             }
454           break;
455
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)
467             {
468               split_type = type_digits;
469               n_units = 0;
470             }
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)
478             {
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);
483             }
484           n_units = n_units * 10 + c - '0';
485           break;
486
487         case 'd':
488           suffix_alphabet = "0123456789";
489           break;
490
491         case_GETOPT_HELP_CHAR;
492
493         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
494
495         default:
496           usage (EXIT_FAILURE);
497         }
498     }
499
500   if (digits_optind && 200112 <= posix2_version ())
501     {
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);
506     }
507
508   /* Handle default case.  */
509   if (split_type == type_undef)
510     {
511       split_type = type_lines;
512       n_units = 1000;
513     }
514
515   if (n_units == 0)
516     {
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);
521     }
522
523   /* Get out the filename arguments.  */
524
525   if (optind < argc)
526     infile = argv[optind++];
527
528   if (optind < argc)
529     outbase = argv[optind++];
530
531   if (optind < argc)
532     {
533       error (0, 0, _("too many arguments"));
534       usage (EXIT_FAILURE);
535     }
536
537   /* Open the input file.  */
538   if (STREQ (infile, "-"))
539     input_desc = STDIN_FILENO;
540   else
541     {
542       input_desc = open (infile, O_RDONLY);
543       if (input_desc < 0)
544         error (EXIT_FAILURE, errno, "%s", infile);
545     }
546   /* Binary I/O is safer when bytecounts are used.  */
547   SET_BINARY (input_desc);
548
549   /* No output file is open now.  */
550   output_desc = -1;
551
552   /* Get the optimal block size of input device and make a buffer.  */
553
554   if (fstat (input_desc, &stat_buf) < 0)
555     error (EXIT_FAILURE, errno, "%s", infile);
556   in_blk_size = ST_BLKSIZE (stat_buf);
557
558   buf = xmalloc (in_blk_size + 1);
559
560   switch (split_type)
561     {
562     case type_digits:
563     case type_lines:
564       lines_split (n_units, buf, in_blk_size);
565       break;
566
567     case type_bytes:
568       bytes_split (n_units, buf, in_blk_size);
569       break;
570
571     case type_byteslines:
572       line_bytes_split (n_units);
573       break;
574
575     default:
576       abort ();
577     }
578
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);
583
584   exit (EXIT_SUCCESS);
585 }