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