Initial import from FreeBSD RELENG_4:
[dragonfly.git] / usr.bin / split / split.c
1 /*
2  * Copyright (c) 1987, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD: src/usr.bin/split/split.c,v 1.6.2.2 2002/07/25 12:46:36 tjr Exp $");
36
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1987, 1993, 1994\n\
40         The Regents of the University of California.  All rights reserved.\n";
41 #endif
42
43 #ifndef lint
44 static const char sccsid[] = "@(#)split.c       8.2 (Berkeley) 4/16/94";
45 #endif
46
47 #include <sys/param.h>
48
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <limits.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <regex.h>
59 #include <sysexits.h>
60
61 #define DEFLINE 1000                    /* Default num lines per file. */
62
63 off_t    bytecnt;                       /* Byte count to split on. */
64 long     numlines;                      /* Line count to split on. */
65 int      file_open;                     /* If a file open. */
66 int      ifd = -1, ofd = -1;            /* Input/output file descriptors. */
67 char     bfr[MAXBSIZE];                 /* I/O buffer. */
68 char     fname[MAXPATHLEN];             /* File name prefix. */
69 regex_t  rgx;
70 int      pflag;
71 long     sufflen = 2;                   /* File name suffix length. */
72
73 void newfile(void);
74 void split1(void);
75 void split2(void);
76 static void usage(void);
77
78 int
79 main(int argc, char **argv)
80 {
81         long long bytecnti;
82         long scale;
83         int ch;
84         char *ep, *p;
85
86         while ((ch = getopt(argc, argv, "-0123456789a:b:l:p:")) != -1)
87                 switch (ch) {
88                 case '0': case '1': case '2': case '3': case '4':
89                 case '5': case '6': case '7': case '8': case '9':
90                         /*
91                          * Undocumented kludge: split was originally designed
92                          * to take a number after a dash.
93                          */
94                         if (numlines == 0) {
95                                 p = argv[optind - 1];
96                                 if (p[0] == '-' && p[1] == ch && !p[2])
97                                         numlines = strtol(++p, &ep, 10);
98                                 else
99                                         numlines =
100                                             strtol(argv[optind] + 1, &ep, 10);
101                                 if (numlines <= 0 || *ep)
102                                         errx(EX_USAGE,
103                                             "%s: illegal line count", optarg);
104                         }
105                         break;
106                 case '-':               /* Undocumented: historic stdin flag. */
107                         if (ifd != -1)
108                                 usage();
109                         ifd = 0;
110                         break;
111                 case 'a':               /* Suffix length */
112                         if ((sufflen = strtol(optarg, &ep, 10)) <= 0 || *ep)
113                                 errx(EX_USAGE,
114                                     "%s: illegal suffix length", optarg);
115                         break;
116                 case 'b':               /* Byte count. */
117                         errno = 0;
118                         if ((bytecnti = strtoll(optarg, &ep, 10)) <= 0 ||
119                             (*ep != '\0' && *ep != 'k' && *ep != 'm') ||
120                             errno != 0)
121                                 errx(EX_USAGE,
122                                     "%s: illegal byte count", optarg);
123                         if (*ep == 'k')
124                                 scale = 1024;
125                         else if (*ep == 'm')
126                                 scale = 1024 * 1024;
127                         else
128                                 scale = 1;
129                         bytecnt = (off_t)(bytecnti * scale);
130                         break;
131                 case 'p' :      /* pattern matching. */
132                         if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
133                                 errx(EX_USAGE, "%s: illegal regexp", optarg);
134                         pflag = 1;
135                         break;
136                 case 'l':               /* Line count. */
137                         if (numlines != 0)
138                                 usage();
139                         if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
140                                 errx(EX_USAGE,
141                                     "%s: illegal line count", optarg);
142                         break;
143                 default:
144                         usage();
145                 }
146         argv += optind;
147         argc -= optind;
148
149         if (*argv != NULL)
150                 if (ifd == -1) {                /* Input file. */
151                         if (strcmp(*argv, "-") == 0)
152                                 ifd = STDIN_FILENO;
153                         else if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
154                                 err(EX_NOINPUT, "%s", *argv);
155                         ++argv;
156                 }
157         if (*argv != NULL)                      /* File name prefix. */
158                 if (strlcpy(fname, *argv++, sizeof(fname)) >= sizeof(fname))
159                         errx(EX_USAGE, "file name prefix is too long");
160         if (*argv != NULL)
161                 usage();
162
163         if (strlen(fname) + (unsigned long)sufflen >= sizeof(fname))
164                 errx(EX_USAGE, "suffix is too long");
165         if (pflag && (numlines != 0 || bytecnt != 0))
166                 usage();
167
168         if (numlines == 0)
169                 numlines = DEFLINE;
170         else if (bytecnt != 0)
171                 usage();
172
173         if (ifd == -1)                          /* Stdin by default. */
174                 ifd = 0;
175
176         if (bytecnt) {
177                 split1();
178                 exit (0);
179         }
180         split2();
181         if (pflag)
182                 regfree(&rgx);
183         exit(0);
184 }
185
186 /*
187  * split1 --
188  *      Split the input by bytes.
189  */
190 void
191 split1(void)
192 {
193         off_t bcnt;
194         char *C;
195         ssize_t dist, len;
196
197         for (bcnt = 0;;)
198                 switch ((len = read(ifd, bfr, MAXBSIZE))) {
199                 case 0:
200                         exit(0);
201                 case -1:
202                         err(EX_IOERR, "read");
203                         /* NOTREACHED */
204                 default:
205                         if (!file_open)
206                                 newfile();
207                         if (bcnt + len >= bytecnt) {
208                                 dist = bytecnt - bcnt;
209                                 if (write(ofd, bfr, dist) != dist)
210                                         err(EX_IOERR, "write");
211                                 len -= dist;
212                                 for (C = bfr + dist; len >= bytecnt;
213                                     len -= bytecnt, C += bytecnt) {
214                                         newfile();
215                                         if (write(ofd,
216                                             C, bytecnt) != bytecnt)
217                                                 err(EX_IOERR, "write");
218                                 }
219                                 if (len != 0) {
220                                         newfile();
221                                         if (write(ofd, C, len) != len)
222                                                 err(EX_IOERR, "write");
223                                 } else
224                                         file_open = 0;
225                                 bcnt = len;
226                         } else {
227                                 bcnt += len;
228                                 if (write(ofd, bfr, len) != len)
229                                         err(EX_IOERR, "write");
230                         }
231                 }
232 }
233
234 /*
235  * split2 --
236  *      Split the input by lines.
237  */
238 void
239 split2(void)
240 {
241         long lcnt = 0;
242         FILE *infp;
243
244         /* Stick a stream on top of input file descriptor */
245         if ((infp = fdopen(ifd, "r")) == NULL)
246                 err(EX_NOINPUT, "fdopen");
247
248         /* Process input one line at a time */
249         while (fgets(bfr, sizeof(bfr), infp) != NULL) {
250                 const int len = strlen(bfr);
251
252                 /* If line is too long to deal with, just write it out */
253                 if (bfr[len - 1] != '\n')
254                         goto writeit;
255
256                 /* Check if we need to start a new file */
257                 if (pflag) {
258                         regmatch_t pmatch;
259
260                         pmatch.rm_so = 0;
261                         pmatch.rm_eo = len - 1;
262                         if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
263                                 newfile();
264                 } else if (lcnt++ == numlines) {
265                         newfile();
266                         lcnt = 1;
267                 }
268
269 writeit:
270                 /* Open output file if needed */
271                 if (!file_open)
272                         newfile();
273
274                 /* Write out line */
275                 if (write(ofd, bfr, len) != len)
276                         err(EX_IOERR, "write");
277         }
278
279         /* EOF or error? */
280         if (ferror(infp))
281                 err(EX_IOERR, "read");
282         else
283                 exit(0);
284 }
285
286 /*
287  * newfile --
288  *      Open a new output file.
289  */
290 void
291 newfile(void)
292 {
293         long i, maxfiles, tfnum;
294         static long fnum;
295         static int defname;
296         static char *fpnt;
297
298         if (ofd == -1) {
299                 if (fname[0] == '\0') {
300                         fname[0] = 'x';
301                         fpnt = fname + 1;
302                         defname = 1;
303                 } else {
304                         fpnt = fname + strlen(fname);
305                         defname = 0;
306                 }
307                 ofd = fileno(stdout);
308         }
309
310         /* maxfiles = 26^sufflen, but don't use libm. */
311         for (maxfiles = 1, i = 0; i < sufflen; i++)
312                 if ((maxfiles *= 26) <= 0)
313                         errx(EX_USAGE, "suffix is too long (max %ld)", i);
314
315         /*
316          * Hack to increase max files; original code wandered through
317          * magic characters.
318          */
319         if (fnum == maxfiles) {
320                 if (!defname || fname[0] == 'z')
321                         errx(EX_DATAERR, "too many files");
322                 ++fname[0];
323                 fnum = 0;
324         }
325
326         /* Generate suffix of sufflen letters */
327         tfnum = fnum;
328         i = sufflen - 1;
329         do {
330                 fpnt[i] = tfnum % 26 + 'a';
331                 tfnum /= 26;
332         } while (i-- > 0);
333         fpnt[sufflen] = '\0';
334
335         ++fnum;
336         if (!freopen(fname, "w", stdout))
337                 err(EX_IOERR, "%s", fname);
338         file_open = 1;
339 }
340
341 static void
342 usage(void)
343 {
344         (void)fprintf(stderr,
345 "usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]\n");
346         (void)fprintf(stderr,
347 "             [file [prefix]]\n");
348         exit(EX_USAGE);
349 }