static char *sccsid
= "@(#)split.c 4.4 (Berkeley) %G%";
#define DEFLINE 1000 /* default num lines per file */
#define ERR -1 /* general error */
#define ERREXIT 0 /* error exit */
#define NO 0 /* no/false */
#define OK 0 /* okay exit */
#define YES 1 /* yes/true */
static long bytecnt
, /* byte count to split on */
numlines
; /* lines in each file */
static int ifd
= ERR
, /* input file descriptor */
ofd
= ERR
; /* output file descriptor */
static short file_open
; /* if a file open */
static char bfr
[MAXBSIZE
], /* I/O buffer */
fname
[MAXPATHLEN
]; /* file name */
register int cnt
; /* general counter */
for (cnt
= 1;cnt
< argc
;++cnt
) {
case 0: /* stdin by request */
case 'b': /* byte count split */
bytecnt
= atol(argv
[++cnt
]);
bytecnt
= atol(argv
[cnt
] + 2);
fputs("split: byte count must be greater than zero.\n",stderr
);
if (!isdigit(argv
[cnt
][1]) || bytecnt
)
if ((numlines
= atol(argv
[cnt
] + 1)) <= 0) {
fputs("split: line count must be greater than zero.\n",stderr
);
else if (ifd
== ERR
) { /* input file */
if ((ifd
= open(argv
[cnt
],O_RDONLY
,0)) < 0) {
else if (!*fname
) /* output file prefix */
if (ifd
== ERR
) /* stdin by default */
register long bcnt
; /* byte counter */
register int dist
, /* buffer offset */
register char *C
; /* tmp pointer into buffer */
switch(len
= read(ifd
,bfr
,MAXBSIZE
)) {
if (bcnt
+ len
>= bytecnt
) {
for (C
= bfr
+ dist
;len
>= bytecnt
;len
-= bytecnt
,C
+= bytecnt
) {
write(ofd
,C
,(int)bytecnt
);
register char *Ce
, /* start/end pointers */
register long lcnt
; /* line counter */
register int len
; /* read length */
switch(len
= read(ifd
,bfr
,MAXBSIZE
)) {
for (Cs
= Ce
= bfr
;len
--;Ce
++)
if (*Ce
== '\n' && ++lcnt
== numlines
) {
write(ofd
,Cs
,(int)(Ce
- Cs
) + 1);
write(ofd
,Cs
,(int)(Ce
- Cs
));
static long fnum
; /* file name counter */
static short defname
; /* using default name, "x" */
static char *fpnt
; /* output file name pointer */
fpnt
= fname
+ strlen(fname
);
* hack to increase max files; original code just wandered through
* magic characters. Maximum files is 3 * 26 * 26 == 2028
if (!defname
|| fname
[0] == 'z') {
fputs("split: too many files.\n",stderr
);
fpnt
[0] = fnum
/ 26 + 'a';
fpnt
[1] = fnum
% 26 + 'a';
if (!freopen(fname
,"w",stdout
)) {
fprintf(stderr
,"split: unable to write to %s.\n",fname
);
* print usage message and die
fputs("usage: split [-] [-#] [-b byte_count] [file [prefix]]\n",stderr
);