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