(cwrite, bytes_split, lines_split, line_bytes_split):
[platform/upstream/coreutils.git] / src / split.c
1 /* split.c -- split a file into pieces.
2    Copyright (C) 88, 91, 1995-2004 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 "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"
41
42 /* The official name of this program (e.g., no `g' prefix).  */
43 #define PROGRAM_NAME "split"
44
45 #define AUTHORS "Torbjorn Granlund", "Richard M. Stallman"
46
47 #define DEFAULT_SUFFIX_LENGTH 2
48
49 /* The name this program was run with. */
50 char *program_name;
51
52 /* Base name of output files.  */
53 static char const *outbase;
54
55 /* Name of output files.  */
56 static char *outfile;
57
58 /* Pointer to the end of the prefix in OUTFILE.
59    Suffixes are inserted here.  */
60 static char *outfile_mid;
61
62 /* Length of OUTFILE's suffix.  */
63 static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
64
65 /* Alphabet of characters to use in suffix.  */
66 static char const *suffix_alphabet = "abcdefghijklmnopqrstuvwxyz";
67
68 /* Name of input file.  May be "-".  */
69 static char *infile;
70
71 /* Descriptor on which input file is open.  */
72 static int input_desc;
73
74 /* Descriptor on which output file is open.  */
75 static int output_desc;
76
77 /* If nonzero, print a diagnostic on standard error just before each
78    output file is opened. */
79 static int verbose;
80
81 static struct option const longopts[] =
82 {
83   {"bytes", required_argument, NULL, 'b'},
84   {"lines", required_argument, NULL, 'l'},
85   {"line-bytes", required_argument, NULL, 'C'},
86   {"suffix-length", required_argument, NULL, 'a'},
87   {"numeric-suffixes", no_argument, NULL, 'd'},
88   {"verbose", no_argument, &verbose, 1},
89   {GETOPT_HELP_OPTION_DECL},
90   {GETOPT_VERSION_OPTION_DECL},
91   {NULL, 0, NULL, 0}
92 };
93
94 void
95 usage (int status)
96 {
97   if (status != EXIT_SUCCESS)
98     fprintf (stderr, _("Try `%s --help' for more information.\n"),
99              program_name);
100   else
101     {
102       printf (_("\
103 Usage: %s [OPTION] [INPUT [PREFIX]]\n\
104 "),
105               program_name);
106     fputs (_("\
107 Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
108 PREFIX is `x'.  With no INPUT, or when INPUT is -, read standard input.\n\
109 \n\
110 "), stdout);
111       fputs (_("\
112 Mandatory arguments to long options are mandatory for short options too.\n\
113 "), stdout);
114       fprintf (stdout, _("\
115   -a, --suffix-length=N   use suffixes of length N (default %d)\n\
116   -b, --bytes=SIZE        put SIZE bytes per output file\n\
117   -C, --line-bytes=SIZE   put at most SIZE bytes of lines per output file\n\
118   -d, --numeric-suffixes  use numeric suffixes instead of alphabetic\n\
119   -l, --lines=NUMBER      put NUMBER lines per output file\n\
120 "), DEFAULT_SUFFIX_LENGTH);
121       fputs (_("\
122       --verbose           print a diagnostic to standard error just\n\
123                             before each output file is opened\n\
124 "), stdout);
125       fputs (HELP_OPTION_DESCRIPTION, stdout);
126       fputs (VERSION_OPTION_DESCRIPTION, stdout);
127       fputs (_("\
128 \n\
129 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
130 "), stdout);
131       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
132     }
133   exit (status);
134 }
135
136 /* Compute the next sequential output file name and store it into the
137    string `outfile'.  */
138
139 static void
140 next_file_name (void)
141 {
142   /* Index in suffix_alphabet of each character in the suffix.  */
143   static size_t *sufindex;
144
145   if (! outfile)
146     {
147       /* Allocate and initialize the first file name.  */
148
149       size_t outbase_length = strlen (outbase);
150       size_t outfile_length = outbase_length + suffix_length;
151       if (outfile_length + 1 < outbase_length)
152         xalloc_die ();
153       outfile = xmalloc (outfile_length + 1);
154       outfile_mid = outfile + outbase_length;
155       memcpy (outfile, outbase, outbase_length);
156       memset (outfile_mid, suffix_alphabet[0], suffix_length);
157       outfile[outfile_length] = 0;
158       sufindex = xcalloc (suffix_length, sizeof *sufindex);
159
160 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
161       /* POSIX requires that if the output file name is too long for
162          its directory, `split' must fail without creating any files.
163          This must be checked for explicitly on operating systems that
164          silently truncate file names.  */
165       {
166         char *dir = dir_name (outfile);
167         long name_max = pathconf (dir, _PC_NAME_MAX);
168         if (0 <= name_max && name_max < base_len (base_name (outfile)))
169           error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
170         free (dir);
171       }
172 #endif
173     }
174   else
175     {
176       /* Increment the suffix in place, if possible.  */
177
178       size_t i = suffix_length;
179       while (i-- != 0)
180         {
181           sufindex[i]++;
182           outfile_mid[i] = suffix_alphabet[sufindex[i]];
183           if (outfile_mid[i])
184             return;
185           sufindex[i] = 0;
186           outfile_mid[i] = suffix_alphabet[sufindex[i]];
187         }
188       error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
189     }
190 }
191
192 /* Write BYTES bytes at BP to an output file.
193    If NEW_FILE_FLAG is true, open the next output file.
194    Otherwise add to the same output file already in use.  */
195
196 static void
197 cwrite (bool new_file_flag, const char *bp, size_t bytes)
198 {
199   if (new_file_flag)
200     {
201       if (output_desc >= 0 && close (output_desc) < 0)
202         error (EXIT_FAILURE, errno, "%s", outfile);
203
204       next_file_name ();
205       if (verbose)
206         fprintf (stderr, _("creating file `%s'\n"), outfile);
207       output_desc = open (outfile,
208                           O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
209       if (output_desc < 0)
210         error (EXIT_FAILURE, errno, "%s", outfile);
211     }
212   if (full_write (output_desc, bp, bytes) != bytes)
213     error (EXIT_FAILURE, errno, "%s", outfile);
214 }
215
216 /* Split into pieces of exactly N_BYTES bytes.
217    Use buffer BUF, whose size is BUFSIZE.  */
218
219 static void
220 bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize)
221 {
222   size_t n_read;
223   bool new_file_flag = true;
224   size_t to_read;
225   uintmax_t to_write = n_bytes;
226   char *bp_out;
227
228   do
229     {
230       n_read = full_read (input_desc, buf, bufsize);
231       if (n_read == SAFE_READ_ERROR)
232         error (EXIT_FAILURE, errno, "%s", infile);
233       bp_out = buf;
234       to_read = n_read;
235       for (;;)
236         {
237           if (to_read < to_write)
238             {
239               if (to_read)      /* do not write 0 bytes! */
240                 {
241                   cwrite (new_file_flag, bp_out, to_read);
242                   to_write -= to_read;
243                   new_file_flag = false;
244                 }
245               break;
246             }
247           else
248             {
249               size_t w = to_write;
250               cwrite (new_file_flag, bp_out, w);
251               bp_out += w;
252               to_read -= w;
253               new_file_flag = true;
254               to_write = n_bytes;
255             }
256         }
257     }
258   while (n_read == bufsize);
259 }
260
261 /* Split into pieces of exactly N_LINES lines.
262    Use buffer BUF, whose size is BUFSIZE.  */
263
264 static void
265 lines_split (uintmax_t n_lines, char *buf, size_t bufsize)
266 {
267   size_t n_read;
268   char *bp, *bp_out, *eob;
269   bool new_file_flag = true;
270   uintmax_t n = 0;
271
272   do
273     {
274       n_read = full_read (input_desc, buf, bufsize);
275       if (n_read == SAFE_READ_ERROR)
276         error (EXIT_FAILURE, errno, "%s", infile);
277       bp = bp_out = buf;
278       eob = bp + n_read;
279       *eob = '\n';
280       for (;;)
281         {
282           bp = memchr (bp, '\n', eob - bp + 1);
283           if (bp == eob)
284             {
285               if (eob != bp_out) /* do not write 0 bytes! */
286                 {
287                   size_t len = eob - bp_out;
288                   cwrite (new_file_flag, bp_out, len);
289                   new_file_flag = false;
290                 }
291               break;
292             }
293
294           ++bp;
295           if (++n >= n_lines)
296             {
297               cwrite (new_file_flag, bp_out, bp - bp_out);
298               bp_out = bp;
299               new_file_flag = true;
300               n = 0;
301             }
302         }
303     }
304   while (n_read == bufsize);
305 }
306 \f
307 /* Split into pieces that are as large as possible while still not more
308    than N_BYTES bytes, and are split on line boundaries except
309    where lines longer than N_BYTES bytes occur.
310    FIXME: Allow N_BYTES to be any uintmax_t value, and don't require a
311    buffer of size N_BYTES, in case N_BYTES is very large.  */
312
313 static void
314 line_bytes_split (size_t n_bytes)
315 {
316   size_t n_read;
317   char *bp;
318   bool eof = false;
319   size_t n_buffered = 0;
320   char *buf = xmalloc (n_bytes);
321
322   do
323     {
324       /* Fill up the full buffer size from the input file.  */
325
326       n_read = full_read (input_desc, buf + n_buffered, n_bytes - n_buffered);
327       if (n_read == SAFE_READ_ERROR)
328         error (EXIT_FAILURE, errno, "%s", infile);
329
330       n_buffered += n_read;
331       if (n_buffered != n_bytes)
332         eof = true;
333
334       /* Find where to end this chunk.  */
335       bp = buf + n_buffered;
336       if (n_buffered == n_bytes)
337         {
338           while (bp > buf && bp[-1] != '\n')
339             bp--;
340         }
341
342       /* If chunk has no newlines, use all the chunk.  */
343       if (bp == buf)
344         bp = buf + n_buffered;
345
346       /* Output the chars as one output file.  */
347       cwrite (true, buf, bp - buf);
348
349       /* Discard the chars we just output; move rest of chunk
350          down to be the start of the next chunk.  Source and
351          destination probably overlap.  */
352       n_buffered -= bp - buf;
353       if (n_buffered > 0)
354         memmove (buf, bp, n_buffered);
355     }
356   while (!eof);
357   free (buf);
358 }
359
360 #define FAIL_ONLY_ONE_WAY()                                     \
361   do                                                            \
362     {                                                           \
363       error (0, 0, _("cannot split in more than one way"));     \
364       usage (EXIT_FAILURE);                                     \
365     }                                                           \
366   while (0)
367
368 int
369 main (int argc, char **argv)
370 {
371   struct stat stat_buf;
372   enum
373     {
374       type_undef, type_bytes, type_byteslines, type_lines, type_digits
375     } split_type = type_undef;
376   size_t in_blk_size;           /* optimal block size of input file device */
377   char *buf;                    /* file i/o buffer */
378   size_t page_size = getpagesize ();
379   uintmax_t n_units;
380   int c;
381   int digits_optind = 0;
382
383   initialize_main (&argc, &argv);
384   program_name = argv[0];
385   setlocale (LC_ALL, "");
386   bindtextdomain (PACKAGE, LOCALEDIR);
387   textdomain (PACKAGE);
388
389   atexit (close_stdout);
390
391   /* Parse command line options.  */
392
393   infile = "-";
394   outbase = "x";
395
396   while (1)
397     {
398       /* This is the argv-index of the option we will read next.  */
399       int this_optind = optind ? optind : 1;
400
401       c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL);
402       if (c == -1)
403         break;
404
405       switch (c)
406         {
407         case 0:
408           break;
409
410         case 'a':
411           {
412             unsigned long tmp;
413             if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
414                 || SIZE_MAX / sizeof (size_t) < tmp)
415               {
416                 error (0, 0, _("%s: invalid suffix length"), optarg);
417                 usage (EXIT_FAILURE);
418               }
419             suffix_length = tmp;
420           }
421           break;
422
423         case 'b':
424           if (split_type != type_undef)
425             FAIL_ONLY_ONE_WAY ();
426           split_type = type_bytes;
427           if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
428               || n_units == 0)
429             {
430               error (0, 0, _("%s: invalid number of bytes"), optarg);
431               usage (EXIT_FAILURE);
432             }
433           break;
434
435         case 'l':
436           if (split_type != type_undef)
437             FAIL_ONLY_ONE_WAY ();
438           split_type = type_lines;
439           if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK
440               || n_units == 0)
441             {
442               error (0, 0, _("%s: invalid number of lines"), optarg);
443               usage (EXIT_FAILURE);
444             }
445           break;
446
447         case 'C':
448           if (split_type != type_undef)
449             FAIL_ONLY_ONE_WAY ();
450           split_type = type_byteslines;
451           if (xstrtoumax (optarg, NULL, 10, &n_units, "bkm") != LONGINT_OK
452               || n_units == 0 || SIZE_MAX < n_units)
453             {
454               error (0, 0, _("%s: invalid number of bytes"), optarg);
455               usage (EXIT_FAILURE);
456             }
457           break;
458
459         case '0':
460         case '1':
461         case '2':
462         case '3':
463         case '4':
464         case '5':
465         case '6':
466         case '7':
467         case '8':
468         case '9':
469           if (split_type == type_undef)
470             {
471               split_type = type_digits;
472               n_units = 0;
473             }
474           if (split_type != type_undef && split_type != type_digits)
475             FAIL_ONLY_ONE_WAY ();
476           if (digits_optind != 0 && digits_optind != this_optind)
477             n_units = 0;        /* More than one number given; ignore other. */
478           digits_optind = this_optind;
479           if (UINTMAX_MAX / 10 < n_units
480               || n_units * 10 + c - '0' < n_units * 10)
481             {
482               char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
483               error (EXIT_FAILURE, 0,
484                      _("line count option -%s%c... is too large"),
485                      umaxtostr (n_units, buffer), c);
486             }
487           n_units = n_units * 10 + c - '0';
488           break;
489
490         case 'd':
491           suffix_alphabet = "0123456789";
492           break;
493
494         case_GETOPT_HELP_CHAR;
495
496         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
497
498         default:
499           usage (EXIT_FAILURE);
500         }
501     }
502
503   if (digits_optind && 200112 <= posix2_version ())
504     {
505       char buffer[INT_BUFSIZE_BOUND (uintmax_t)];
506       char const *a = umaxtostr (n_units, buffer);
507       error (0, 0, _("`-%s' option is obsolete; use `-l %s'"), a, a);
508       usage (EXIT_FAILURE);
509     }
510
511   /* Handle default case.  */
512   if (split_type == type_undef)
513     {
514       split_type = type_lines;
515       n_units = 1000;
516     }
517
518   if (n_units == 0)
519     {
520       /* FIXME: be sure to remove this block when removing
521          support for obsolete options like `-10'.  */
522       error (0, 0, _("invalid number of lines: 0"));
523       usage (EXIT_FAILURE);
524     }
525
526   /* Get out the filename arguments.  */
527
528   if (optind < argc)
529     infile = argv[optind++];
530
531   if (optind < argc)
532     outbase = argv[optind++];
533
534   if (optind < argc)
535     {
536       error (0, 0, _("extra operand %s"), quote (argv[optind]));
537       usage (EXIT_FAILURE);
538     }
539
540   /* Open the input file.  */
541   if (STREQ (infile, "-"))
542     input_desc = STDIN_FILENO;
543   else
544     {
545       input_desc = open (infile, O_RDONLY);
546       if (input_desc < 0)
547         error (EXIT_FAILURE, errno, "%s", infile);
548     }
549   /* Binary I/O is safer when bytecounts are used.  */
550   SET_BINARY (input_desc);
551
552   /* No output file is open now.  */
553   output_desc = -1;
554
555   /* Get the optimal block size of input device and make a buffer.  */
556
557   if (fstat (input_desc, &stat_buf) < 0)
558     error (EXIT_FAILURE, errno, "%s", infile);
559   in_blk_size = ST_BLKSIZE (stat_buf);
560
561   buf = ptr_align (xmalloc (in_blk_size + 1 + page_size - 1), page_size);
562
563   switch (split_type)
564     {
565     case type_digits:
566     case type_lines:
567       lines_split (n_units, buf, in_blk_size);
568       break;
569
570     case type_bytes:
571       bytes_split (n_units, buf, in_blk_size);
572       break;
573
574     case type_byteslines:
575       line_bytes_split (n_units);
576       break;
577
578     default:
579       abort ();
580     }
581
582   if (close (input_desc) < 0)
583     error (EXIT_FAILURE, errno, "%s", infile);
584   if (output_desc >= 0 && close (output_desc) < 0)
585     error (EXIT_FAILURE, errno, "%s", outfile);
586
587   exit (EXIT_SUCCESS);
588 }