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