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