1 /* $NetBSD: csplit.c,v 1.4 2007/12/15 19:44:49 perry Exp $ */
2 /* $FreeBSD: src/usr.bin/csplit/csplit.c,v 1.9 2004/03/22 11:15:03 tjr Exp$ */
5 * Copyright (c) 2002 Tim J. Robbins.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
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/cdefs.h>
50 __RCSID("$NetBSD: csplit.c,v 1.4 2007/12/15 19:44:49 perry Exp $");
53 #include <sys/types.h>
69 static void cleanup(void);
70 static void do_lineno(const char *);
71 static void do_rexp(const char *);
72 static char *get_line(void);
73 static void handlesig(int);
74 static FILE *newfile(void);
75 static void toomuch(FILE *, long);
76 static void usage(void) __dead
;
79 * Command line options
81 const char *prefix
; /* File name prefix */
82 long sufflen
; /* Number of decimal digits for suffix */
83 int sflag
; /* Suppress output of file names */
84 int kflag
; /* Keep output if error occurs */
87 * Other miscellaneous globals (XXX too many)
89 long lineno
; /* Current line number in input file */
90 long reps
; /* Number of repetitions for this pattern */
91 long nfiles
; /* Number of files output so far */
92 long maxfiles
; /* Maximum number of files we can create */
93 char currfile
[PATH_MAX
]; /* Current output file */
94 const char *infn
; /* Name of the input file */
95 FILE *infile
; /* Input file handle */
96 FILE *overfile
; /* Overflow file for toomuch() */
97 off_t truncofs
; /* Offset this file should be truncated at */
98 int doclean
; /* Should cleanup() remove output? */
101 main(int argc
, char *argv
[])
110 (void)setlocale(LC_ALL
, "");
115 while ((ch
= getopt(argc
, argv
, "ksf:n:")) > 0) {
125 sufflen
= strtol(optarg
, &ep
, 10);
126 if (sufflen
<= 0 || *ep
!= '\0' || errno
!= 0)
127 errx(1, "%s: bad suffix length", optarg
);
138 if (sufflen
+ strlen(prefix
) >= PATH_MAX
)
139 errx(1, "name too long");
144 if ((infn
= *argv
++) == NULL
)
146 if (strcmp(infn
, "-") == 0) {
149 } else if ((infile
= fopen(infn
, "r")) == NULL
)
154 (void)atexit(cleanup
);
156 sa
.sa_handler
= handlesig
;
157 (void)sigemptyset(&sa
.sa_mask
);
158 (void)sigaddset(&sa
.sa_mask
, SIGHUP
);
159 (void)sigaddset(&sa
.sa_mask
, SIGINT
);
160 (void)sigaddset(&sa
.sa_mask
, SIGTERM
);
161 (void)sigaction(SIGHUP
, &sa
, NULL
);
162 (void)sigaction(SIGINT
, &sa
, NULL
);
163 (void)sigaction(SIGTERM
, &sa
, NULL
);
171 /* Ensure 10^sufflen < LONG_MAX. */
172 for (maxfiles
= 1, i
= 0; i
< sufflen
; i
++) {
173 if (maxfiles
> LONG_MAX
/ 10)
174 errx(1, "%ld: suffix too long (limit %ld)",
179 /* Create files based on supplied patterns. */
180 while (nfiles
< maxfiles
- 1 && (expr
= *argv
++) != NULL
) {
181 /* Look ahead & see if this pattern has any repetitions. */
182 if (*argv
!= NULL
&& **argv
== '{') {
184 reps
= strtol(*argv
+ 1, &ep
, 10);
185 if (reps
< 0 || *ep
!= '}' || errno
!= 0)
186 errx(1, "%s: bad repetition count", *argv
+ 1);
191 if (*expr
== '/' || *expr
== '%') {
194 while (reps
-- != 0 && nfiles
< maxfiles
- 1);
195 } else if (isdigit((unsigned char)*expr
))
198 errx(1, "%s: unrecognised pattern", expr
);
201 /* Copy the rest into a new file. */
204 while ((p
= get_line()) != NULL
&& fputs(p
, ofp
) == 0)
207 (void)printf("%jd\n", (intmax_t)ftello(ofp
));
208 if (fclose(ofp
) != 0)
209 err(1, "%s", currfile
);
222 (void)fprintf(stderr
,
223 "Usage: %s [-ks] [-f prefix] [-n number] file args ...\n", getprogname());
233 len
= snprintf(msg
, sizeof(msg
), "%s: Caught %s, cleaning up\n",
234 getprogname(), strsignal(sig
));
235 if (len
< sizeof(msg
))
236 (void)write(STDERR_FILENO
, msg
, len
);
238 (void)raise_default_signal(sig
);
242 /* Create a new output file. */
248 if ((size_t)snprintf(currfile
, sizeof(currfile
), "%s%0*ld", prefix
,
249 (int)sufflen
, nfiles
) >= sizeof(currfile
))
250 errx(1, "%s: %s", currfile
, strerror(ENAMETOOLONG
));
251 if ((fp
= fopen(currfile
, "w+")) == NULL
)
252 err(1, "%s", currfile
);
258 /* Remove partial output, called before exiting. */
262 char fnbuf
[PATH_MAX
];
269 * NOTE: One cannot portably assume to be able to call snprintf()
270 * from inside a signal handler. It does, however, appear to be safe
271 * to do on FreeBSD and NetBSD. The solution to this problem is worse
272 * than the problem itself.
275 for (i
= 0; i
< nfiles
; i
++) {
276 (void)snprintf(fnbuf
, sizeof(fnbuf
), "%s%0*ld", prefix
,
282 /* Read a line from the input into a static buffer. */
286 static char lbuf
[LINE_MAX
];
289 src
= overfile
!= NULL
? overfile
: infile
;
291 again
: if (fgets(lbuf
, sizeof(lbuf
), src
) == NULL
) {
292 if (src
== overfile
) {
305 /* Conceptually rewind the input (as obtained by get_line()) back `n' lines. */
307 toomuch(FILE *ofp
, long n
)
312 if (overfile
!= NULL
) {
314 * Truncate the previous file we overflowed into back to
315 * the correct length, close it.
317 if (fflush(overfile
) != 0)
319 if (ftruncate(fileno(overfile
), truncofs
) != 0)
321 if (fclose(overfile
) != 0)
327 /* Just tidying up */
333 * Wind the overflow file backwards to `n' lines before the
337 if (ftello(ofp
) < (off_t
)sizeof(buf
))
340 (void)fseeko(ofp
, -(off_t
)sizeof(buf
), SEEK_CUR
);
342 errx(1, "%s: can't seek", currfile
);
343 if ((nread
= fread(buf
, 1, sizeof(buf
), ofp
)) == 0)
344 errx(1, "can't read overflowed output");
345 if (fseeko(ofp
, -(off_t
)nread
, SEEK_CUR
) != 0)
346 err(1, "%s", currfile
);
347 for (i
= 1; i
<= nread
; i
++)
348 if (buf
[nread
- i
] == '\n' && n
-- == 0)
350 if (ftello(ofp
) == 0)
353 if (fseeko(ofp
, (off_t
)nread
- i
+ 1, SEEK_CUR
) != 0)
354 err(1, "%s", currfile
);
357 * get_line() will read from here. Next call will truncate to
358 * truncofs in this file.
361 truncofs
= ftello(overfile
);
364 /* Handle splits for /regexp/ and %regexp% patterns. */
366 do_rexp(const char *expr
)
372 char *ecopy
, *ep
, *p
, *pofs
, *re
;
375 if ((ecopy
= strdup(expr
)) == NULL
)
379 if ((pofs
= strrchr(ecopy
, *expr
)) == NULL
|| pofs
[-1] == '\\')
380 errx(1, "%s: missing trailing %c", expr
, *expr
);
385 ofs
= strtol(pofs
, &ep
, 10);
386 if (*ep
!= '\0' || errno
!= 0)
387 errx(1, "%s: bad offset", pofs
);
391 if (regcomp(&cre
, re
, REG_BASIC
|REG_NOSUB
) != 0)
392 errx(1, "%s: bad regular expression", re
);
395 /* /regexp/: Save results to a file. */
398 /* %regexp%: Make a temporary file for overflow. */
399 if ((ofp
= tmpfile()) == NULL
)
403 /* Read and output lines until we get a match. */
405 while ((p
= get_line()) != NULL
) {
406 if (fputs(p
, ofp
) != 0)
408 if (!first
&& regexec(&cre
, p
, 0, NULL
, 0) == 0)
414 errx(1, "%s: no match", re
);
418 * Negative (or zero) offset: throw back any lines we should
422 toomuch(ofp
, -ofs
+ 1);
423 nwritten
= (intmax_t)truncofs
;
425 nwritten
= (intmax_t)ftello(ofp
);
428 * Positive offset: copy the requested number of lines
431 while (--ofs
> 0 && (p
= get_line()) != NULL
)
432 if (fputs(p
, ofp
) != 0)
435 nwritten
= (intmax_t)ftello(ofp
);
436 if (fclose(ofp
) != 0)
437 err(1, "%s", currfile
);
440 if (!sflag
&& *expr
== '/')
441 (void)printf("%jd\n", nwritten
);
447 /* Handle splits based on line number. */
449 do_lineno(const char *expr
)
451 long lastline
, tgtline
;
456 tgtline
= strtol(expr
, &ep
, 10);
457 if (tgtline
<= 0 || errno
!= 0 || *ep
!= '\0')
458 errx(1, "%s: bad line number", expr
);
460 if (lastline
<= lineno
)
461 errx(1, "%s: can't go backwards", expr
);
463 while (nfiles
< maxfiles
- 1) {
465 while (lineno
+ 1 != lastline
) {
466 if ((p
= get_line()) == NULL
)
467 errx(1, "%ld: out of range", lastline
);
468 if (fputs(p
, ofp
) != 0)
472 (void)printf("%jd\n", (intmax_t)ftello(ofp
));
473 if (fclose(ofp
) != 0)
474 err(1, "%s", currfile
);