home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Simtel MSDOS 1992 December
/
simtel1292_SIMTEL_1292_Walnut_Creek.iso
/
msdos
/
txtutl
/
miscnix.arc
/
SPLIT.C
< prev
next >
Wrap
Text File
|
1988-05-28
|
2KB
|
108 lines
#include <stdio.h>
/** SPLIT Print last several lines of a file.
Usage: split [-n] [ifile [ofile]]
where n is the number of lines per piece.
If ifile is given as "-", or if no files are given and standard
input is a pipe or file, then input will come from standard
input. Output file names are assigned sequentially: (ofile)aa,
(ofile)ab, etc. The default number of lines is 1000; the
default output file name is "x" (i.e., xaa, xab, etc.).
No copyright, dammit: this is PUBLIC DOMAIN!!!
*/
int nlines =1000;
int f1 =0; /* file descriptor for input */
int f2; /* file descriptor for output */
char f2name[128];
int f2count;
char *f2ptr; /* pointer to where to put the 'aa', etc. */
#define BUFLEN 31*1024
char buf[BUFLEN];
usage() {
puts("Usage: split [-n] [ifile [ofile]]");
puts(" where n is the number of lines per piece (default 1000).");
exit(1);
}
errquit(s1,s2)
char *s1,*s2; {
fputs(s1,stderr);
fputs(": ",stderr);
fputs(s2,stderr);
fputs("\n",stderr);
exit(2);
}
opennext() {
*f2ptr = 'a'+(f2count/26);
*(f2ptr+1) = 'a'+(f2count%26);
++f2count;
f2=creat(f2name);
if (f2==ERR) errquit(f2name,"cannot open output file.");
}
processfile(s)
char *s; { /* file name */
int lleft;
char *bufbgn,*bufpos,*bufend;
int len;
strcpy(f2name,s);
f2ptr= &f2name+strlen(f2name);
*(f2ptr+2)='\0';
opennext();
lleft=nlines;
for (;;) { /* loop over buffers read */
if ((len=read(f1,buf,BUFLEN))==0) break;
bufbgn=bufpos= &buf;
bufend= &buf+len;
for (;;) { /* loop over lines or fragments thereof */
bufpos=strnchr(bufpos,bufend-bufpos,'\n');
if (bufpos>=bufend) break;
++bufpos;
if ((--lleft) == 0) {
write(f2,bufbgn,bufpos-bufbgn);
close(f2);
bufbgn=bufpos;
opennext();
lleft=nlines;
}
}
write(f2,bufbgn,bufend-bufbgn);
}
close(f2);
}
main(argc,argv)
int argc;
char **argv; {
int arg =1;
/* parse numeric argument */
if (argc>1 && argv[1][0]=='-' && argv[1][1]) {
if ((nlines=atoi(&argv[1][1]))==0) usage();
++arg;
}
if (arg >= argc) {
if (isatty(0)) usage();
argv[--arg]="-";
}
if (arg<argc-2) usage();
/* f1=0; /* standard input */
if (strcmp(argv[arg],"-"))
if ((f1=open(argv[arg],0))==ERR)
errquit(argv[arg],"cannot open input file");
processfile(arg<argc-1? argv[arg+1]: "x");
}