2 * Copyright (c) 2002 Tim J. Robbins.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/usr.bin/csplit/csplit.c,v 1.9 2004/03/22 11:15:03 tjr Exp $
30 * csplit -- split files based on context
32 * This utility splits its input into numbered output files by line number
33 * or by a regular expression. Regular expression matches have an optional
34 * offset with them, allowing the split to occur a specified number of
35 * lines before or after the match.
37 * To handle negative offsets, we stop reading when the match occurs and
38 * store the offset that the file should have been split at, then use
39 * this output file as input until all the "overflowed" lines have been read.
40 * The file is then closed and truncated to the correct length.
42 * We assume that the output files can be seeked upon (ie. they cannot be
43 * symlinks to named pipes or character devices), but make no such
44 * assumption about the input.
47 #include <sys/types.h>
62 static void cleanup(void);
63 static void do_lineno(const char *);
64 static void do_rexp(const char *);
65 static char *get_line(void);
66 static void handlesig(int) __dead2
;
67 static FILE *newfile(void);
68 static void toomuch(FILE *, long);
69 static void usage(void) __dead2
;
72 * Command line options
74 static const char *prefix
; /* File name prefix */
75 static long sufflen
; /* Number of decimal digits for suffix */
76 static int sflag
; /* Suppress output of file names */
77 static int kflag
; /* Keep output if error occurs */
80 * Other miscellaneous globals (XXX too many)
82 static long lineno
; /* Current line number in input file */
83 static long reps
; /* Number of repetitions for this pattern */
84 static long nfiles
; /* Number of files output so far */
85 static long maxfiles
; /* Maximum number of files we can create */
86 static char currfile
[PATH_MAX
]; /* Current output file */
87 static const char *infn
; /* Name of the input file */
88 static FILE *infile
; /* Input file handle */
89 static FILE *overfile
; /* Overflow file for toomuch() */
90 static off_t truncofs
; /* Offset this file should be truncated at */
91 static int doclean
; /* Should cleanup() remove output? */
94 main(int argc
, char *argv
[])
103 setlocale(LC_ALL
, "");
108 while ((ch
= getopt(argc
, argv
, "ksf:n:")) > 0) {
118 sufflen
= strtol(optarg
, &ep
, 10);
119 if (sufflen
<= 0 || *ep
!= '\0' || errno
!= 0)
120 errx(1, "%s: bad suffix length", optarg
);
131 if (sufflen
+ strlen(prefix
) >= PATH_MAX
)
132 errx(1, "name too long");
137 if ((infn
= *argv
++) == NULL
)
139 if (strcmp(infn
, "-") == 0) {
142 } else if ((infile
= fopen(infn
, "r")) == NULL
)
149 sa
.sa_handler
= handlesig
;
150 sigemptyset(&sa
.sa_mask
);
151 sigaddset(&sa
.sa_mask
, SIGHUP
);
152 sigaddset(&sa
.sa_mask
, SIGINT
);
153 sigaddset(&sa
.sa_mask
, SIGTERM
);
154 sigaction(SIGHUP
, &sa
, NULL
);
155 sigaction(SIGINT
, &sa
, NULL
);
156 sigaction(SIGTERM
, &sa
, NULL
);
164 /* Ensure 10^sufflen < LONG_MAX. */
165 for (maxfiles
= 1, i
= 0; i
< sufflen
; i
++) {
166 if (maxfiles
> LONG_MAX
/ 10)
167 errx(1, "%ld: suffix too long (limit %ld)",
172 /* Create files based on supplied patterns. */
173 while (nfiles
< maxfiles
- 1 && (expr
= *argv
++) != NULL
) {
174 /* Look ahead & see if this pattern has any repetitions. */
175 if (*argv
!= NULL
&& **argv
== '{') {
177 reps
= strtol(*argv
+ 1, &ep
, 10);
178 if (reps
< 0 || *ep
!= '}' || errno
!= 0)
179 errx(1, "%s: bad repetition count", *argv
+ 1);
184 if (*expr
== '/' || *expr
== '%') {
187 while (reps
-- != 0 && nfiles
< maxfiles
- 1);
188 } else if (isdigit((unsigned char)*expr
))
191 errx(1, "%s: unrecognised pattern", expr
);
194 /* Copy the rest into a new file. */
197 while ((p
= get_line()) != NULL
&& fputs(p
, ofp
) == 0)
200 printf("%jd\n", (intmax_t)ftello(ofp
));
201 if (fclose(ofp
) != 0)
202 err(1, "%s", currfile
);
216 "usage: csplit [-ks] [-f prefix] [-n number] file args ...\n");
221 handlesig(int sig __unused
)
223 const char msg
[] = "csplit: caught signal, cleaning up\n";
225 write(STDERR_FILENO
, msg
, sizeof(msg
) - 1);
230 /* Create a new output file. */
236 if ((size_t)snprintf(currfile
, sizeof(currfile
), "%s%0*ld", prefix
,
237 (int)sufflen
, nfiles
) >= sizeof(currfile
))
238 errc(1, ENAMETOOLONG
, NULL
);
239 if ((fp
= fopen(currfile
, "w+")) == NULL
)
240 err(1, "%s", currfile
);
246 /* Remove partial output, called before exiting. */
250 char fnbuf
[PATH_MAX
];
257 * NOTE: One cannot portably assume to be able to call snprintf()
258 * from inside a signal handler. It does, however, appear to be safe
259 * to do on FreeBSD. The solution to this problem is worse than the
263 for (i
= 0; i
< nfiles
; i
++) {
264 snprintf(fnbuf
, sizeof(fnbuf
), "%s%0*ld", prefix
,
270 /* Read a line from the input into a static buffer. */
274 static char lbuf
[LINE_MAX
];
277 src
= overfile
!= NULL
? overfile
: infile
;
279 again
: if (fgets(lbuf
, sizeof(lbuf
), src
) == NULL
) {
280 if (src
== overfile
) {
293 /* Conceptually rewind the input (as obtained by get_line()) back `n' lines. */
295 toomuch(FILE *ofp
, long n
)
300 if (overfile
!= NULL
) {
302 * Truncate the previous file we overflowed into back to
303 * the correct length, close it.
305 if (fflush(overfile
) != 0)
307 if (ftruncate(fileno(overfile
), truncofs
) != 0)
309 if (fclose(overfile
) != 0)
315 /* Just tidying up */
321 * Wind the overflow file backwards to `n' lines before the
325 if (ftello(ofp
) < (off_t
)sizeof(buf
))
328 fseeko(ofp
, -(off_t
)sizeof(buf
), SEEK_CUR
);
330 errx(1, "%s: can't seek", currfile
);
331 if ((nread
= fread(buf
, 1, sizeof(buf
), ofp
)) == 0)
332 errx(1, "can't read overflowed output");
333 if (fseeko(ofp
, -(off_t
)nread
, SEEK_CUR
) != 0)
334 err(1, "%s", currfile
);
335 for (i
= 1; i
<= nread
; i
++)
336 if (buf
[nread
- i
] == '\n' && n
-- == 0)
338 if (ftello(ofp
) == 0)
341 if (fseeko(ofp
, nread
- i
+ 1, SEEK_CUR
) != 0)
342 err(1, "%s", currfile
);
345 * get_line() will read from here. Next call will truncate to
346 * truncofs in this file.
349 truncofs
= ftello(overfile
);
352 /* Handle splits for /regexp/ and %regexp% patterns. */
354 do_rexp(const char *expr
)
360 char *ecopy
, *ep
, *p
, *pofs
, *re
;
363 if ((ecopy
= strdup(expr
)) == NULL
)
367 if ((pofs
= strrchr(ecopy
, *expr
)) == NULL
|| pofs
[-1] == '\\')
368 errx(1, "%s: missing trailing %c", expr
, *expr
);
373 ofs
= strtol(pofs
, &ep
, 10);
374 if (*ep
!= '\0' || errno
!= 0)
375 errx(1, "%s: bad offset", pofs
);
379 if (regcomp(&cre
, re
, REG_BASIC
|REG_NOSUB
) != 0)
380 errx(1, "%s: bad regular expression", re
);
383 /* /regexp/: Save results to a file. */
386 /* %regexp%: Make a temporary file for overflow. */
387 if ((ofp
= tmpfile()) == NULL
)
391 /* Read and output lines until we get a match. */
393 while ((p
= get_line()) != NULL
) {
394 if (fputs(p
, ofp
) != 0)
396 if (!first
&& regexec(&cre
, p
, 0, NULL
, 0) == 0)
402 errx(1, "%s: no match", re
);
406 * Negative (or zero) offset: throw back any lines we should
410 toomuch(ofp
, -ofs
+ 1);
411 nwritten
= (intmax_t)truncofs
;
413 nwritten
= (intmax_t)ftello(ofp
);
416 * Positive offset: copy the requested number of lines
419 while (--ofs
> 0 && (p
= get_line()) != NULL
)
422 nwritten
= (intmax_t)ftello(ofp
);
423 if (fclose(ofp
) != 0)
424 err(1, "%s", currfile
);
427 if (!sflag
&& *expr
== '/')
428 printf("%jd\n", nwritten
);
434 /* Handle splits based on line number. */
436 do_lineno(const char *expr
)
438 long lastline
, tgtline
;
443 tgtline
= strtol(expr
, &ep
, 10);
444 if (tgtline
<= 0 || errno
!= 0 || *ep
!= '\0')
445 errx(1, "%s: bad line number", expr
);
447 if (lastline
<= lineno
)
448 errx(1, "%s: can't go backwards", expr
);
450 while (nfiles
< maxfiles
- 1) {
452 while (lineno
+ 1 != lastline
) {
453 if ((p
= get_line()) == NULL
)
454 errx(1, "%ld: out of range", lastline
);
455 if (fputs(p
, ofp
) != 0)
459 printf("%jd\n", (intmax_t)ftello(ofp
));
460 if (fclose(ofp
) != 0)
461 err(1, "%s", currfile
);