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