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 $
27 * $DragonFly: src/usr.bin/csplit/csplit.c,v 1.1 2004/06/19 21:51:54 hmp Exp $
31 * csplit -- split files based on context
33 * This utility splits its input into numbered output files by line number
34 * or by a regular expression. Regular expression matches have an optional
35 * offset with them, allowing the split to occur a specified number of
36 * lines before or after the match.
38 * To handle negative offsets, we stop reading when the match occurs and
39 * store the offset that the file should have been split at, then use
40 * this output file as input until all the "overflowed" lines have been read.
41 * The file is then closed and truncated to the correct length.
43 * We assume that the output files can be seeked upon (ie. they cannot be
44 * symlinks to named pipes or character devices), but make no such
45 * assumption about the input.
48 #include <sys/types.h>
64 void do_lineno(const char *);
65 void do_rexp(const char *);
69 void toomuch(FILE *, long);
73 * Command line options
75 const char *prefix
; /* File name prefix */
76 long sufflen
; /* Number of decimal digits for suffix */
77 int sflag
; /* Suppress output of file names */
78 int kflag
; /* Keep output if error occurs */
81 * Other miscellaneous globals (XXX too many)
83 long lineno
; /* Current line number in input file */
84 long reps
; /* Number of repetitions for this pattern */
85 long nfiles
; /* Number of files output so far */
86 long maxfiles
; /* Maximum number of files we can create */
87 char currfile
[PATH_MAX
]; /* Current output file */
88 const char *infn
; /* Name of the input file */
89 FILE *infile
; /* Input file handle */
90 FILE *overfile
; /* Overflow file for toomuch() */
91 off_t truncofs
; /* Offset this file should be truncated at */
92 int doclean
; /* Should cleanup() remove output? */
95 main(int argc
, char *argv
[])
104 setlocale(LC_ALL
, "");
109 while ((ch
= getopt(argc
, argv
, "ksf:n:")) > 0) {
119 sufflen
= strtol(optarg
, &ep
, 10);
120 if (sufflen
<= 0 || *ep
!= '\0' || errno
!= 0)
121 errx(1, "%s: bad suffix length", optarg
);
132 if (sufflen
+ strlen(prefix
) >= PATH_MAX
)
133 errx(1, "name too long");
138 if ((infn
= *argv
++) == NULL
)
140 if (strcmp(infn
, "-") == 0) {
143 } else if ((infile
= fopen(infn
, "r")) == NULL
)
150 sa
.sa_handler
= handlesig
;
151 sigemptyset(&sa
.sa_mask
);
152 sigaddset(&sa
.sa_mask
, SIGHUP
);
153 sigaddset(&sa
.sa_mask
, SIGINT
);
154 sigaddset(&sa
.sa_mask
, SIGTERM
);
155 sigaction(SIGHUP
, &sa
, NULL
);
156 sigaction(SIGINT
, &sa
, NULL
);
157 sigaction(SIGTERM
, &sa
, NULL
);
165 /* Ensure 10^sufflen < LONG_MAX. */
166 for (maxfiles
= 1, i
= 0; i
< sufflen
; i
++) {
167 if (maxfiles
> LONG_MAX
/ 10)
168 errx(1, "%ld: suffix too long (limit %ld)",
173 /* Create files based on supplied patterns. */
174 while (nfiles
< maxfiles
- 1 && (expr
= *argv
++) != NULL
) {
175 /* Look ahead & see if this pattern has any repetitions. */
176 if (*argv
!= NULL
&& **argv
== '{') {
178 reps
= strtol(*argv
+ 1, &ep
, 10);
179 if (reps
< 0 || *ep
!= '}' || errno
!= 0)
180 errx(1, "%s: bad repetition count", *argv
+ 1);
185 if (*expr
== '/' || *expr
== '%') {
188 while (reps
-- != 0 && nfiles
< maxfiles
- 1);
189 } else if (isdigit((unsigned char)*expr
))
192 errx(1, "%s: unrecognised pattern", expr
);
195 /* Copy the rest into a new file. */
198 while ((p
= getline()) != NULL
&& fputs(p
, ofp
) == 0)
201 printf("%jd\n", (intmax_t)ftello(ofp
));
202 if (fclose(ofp
) != 0)
203 err(1, "%s", currfile
);
217 "usage: csplit [-ks] [-f prefix] [-n number] file args ...\n");
222 handlesig(int sig __unused
)
224 const char msg
[] = "csplit: caught signal, cleaning up\n";
226 write(STDERR_FILENO
, msg
, sizeof(msg
) - 1);
231 /* Create a new output file. */
237 if ((size_t)snprintf(currfile
, sizeof(currfile
), "%s%0*ld", prefix
,
238 (int)sufflen
, nfiles
) >= sizeof(currfile
))
239 errc(1, ENAMETOOLONG
, NULL
);
240 if ((fp
= fopen(currfile
, "w+")) == NULL
)
241 err(1, "%s", currfile
);
247 /* Remove partial output, called before exiting. */
251 char fnbuf
[PATH_MAX
];
258 * NOTE: One cannot portably assume to be able to call snprintf()
259 * from inside a signal handler. It does, however, appear to be safe
260 * to do on FreeBSD. The solution to this problem is worse than the
264 for (i
= 0; i
< nfiles
; i
++) {
265 snprintf(fnbuf
, sizeof(fnbuf
), "%s%0*ld", prefix
,
271 /* Read a line from the input into a static buffer. */
275 static char lbuf
[LINE_MAX
];
278 src
= overfile
!= NULL
? overfile
: infile
;
280 again
: if (fgets(lbuf
, sizeof(lbuf
), src
) == NULL
) {
281 if (src
== overfile
) {
294 /* Conceptually rewind the input (as obtained by getline()) back `n' lines. */
296 toomuch(FILE *ofp
, long n
)
301 if (overfile
!= NULL
) {
303 * Truncate the previous file we overflowed into back to
304 * the correct length, close it.
306 if (fflush(overfile
) != 0)
308 if (ftruncate(fileno(overfile
), truncofs
) != 0)
310 if (fclose(overfile
) != 0)
316 /* Just tidying up */
322 * Wind the overflow file backwards to `n' lines before the
326 if (ftello(ofp
) < (off_t
)sizeof(buf
))
329 fseeko(ofp
, -(off_t
)sizeof(buf
), SEEK_CUR
);
331 errx(1, "%s: can't seek", currfile
);
332 if ((nread
= fread(buf
, 1, sizeof(buf
), ofp
)) == 0)
333 errx(1, "can't read overflowed output");
334 if (fseeko(ofp
, -(off_t
)nread
, SEEK_CUR
) != 0)
335 err(1, "%s", currfile
);
336 for (i
= 1; i
<= nread
; i
++)
337 if (buf
[nread
- i
] == '\n' && n
-- == 0)
339 if (ftello(ofp
) == 0)
342 if (fseeko(ofp
, nread
- i
+ 1, SEEK_CUR
) != 0)
343 err(1, "%s", currfile
);
346 * getline() will read from here. Next call will truncate to
347 * truncofs in this file.
350 truncofs
= ftello(overfile
);
353 /* Handle splits for /regexp/ and %regexp% patterns. */
355 do_rexp(const char *expr
)
361 char *ecopy
, *ep
, *p
, *pofs
, *re
;
364 if ((ecopy
= strdup(expr
)) == NULL
)
368 if ((pofs
= strrchr(ecopy
, *expr
)) == NULL
|| pofs
[-1] == '\\')
369 errx(1, "%s: missing trailing %c", expr
, *expr
);
374 ofs
= strtol(pofs
, &ep
, 10);
375 if (*ep
!= '\0' || errno
!= 0)
376 errx(1, "%s: bad offset", pofs
);
380 if (regcomp(&cre
, re
, REG_BASIC
|REG_NOSUB
) != 0)
381 errx(1, "%s: bad regular expression", re
);
384 /* /regexp/: Save results to a file. */
387 /* %regexp%: Make a temporary file for overflow. */
388 if ((ofp
= tmpfile()) == NULL
)
392 /* Read and output lines until we get a match. */
394 while ((p
= getline()) != NULL
) {
395 if (fputs(p
, ofp
) != 0)
397 if (!first
&& regexec(&cre
, p
, 0, NULL
, 0) == 0)
403 errx(1, "%s: no match", re
);
407 * Negative (or zero) offset: throw back any lines we should
411 toomuch(ofp
, -ofs
+ 1);
412 nwritten
= (intmax_t)truncofs
;
414 nwritten
= (intmax_t)ftello(ofp
);
417 * Positive offset: copy the requested number of lines
420 while (--ofs
> 0 && (p
= getline()) != NULL
)
423 nwritten
= (intmax_t)ftello(ofp
);
424 if (fclose(ofp
) != 0)
425 err(1, "%s", currfile
);
428 if (!sflag
&& *expr
== '/')
429 printf("%jd\n", nwritten
);
435 /* Handle splits based on line number. */
437 do_lineno(const char *expr
)
439 long lastline
, tgtline
;
444 tgtline
= strtol(expr
, &ep
, 10);
445 if (tgtline
<= 0 || errno
!= 0 || *ep
!= '\0')
446 errx(1, "%s: bad line number", expr
);
448 if (lastline
<= lineno
)
449 errx(1, "%s: can't go backwards", expr
);
451 while (nfiles
< maxfiles
- 1) {
453 while (lineno
+ 1 != lastline
) {
454 if ((p
= getline()) == NULL
)
455 errx(1, "%ld: out of range", lastline
);
456 if (fputs(p
, ofp
) != 0)
460 printf("%jd\n", (intmax_t)ftello(ofp
));
461 if (fclose(ofp
) != 0)
462 err(1, "%s", currfile
);