home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Simtel MSDOS 1992 June
/
SIMTEL_0692.cdr
/
msdos
/
txtutl
/
miscnix.arc
/
HEAD.C
next >
Wrap
Text File
|
1988-05-28
|
3KB
|
119 lines
#include <stdio.h>
#define ERROR 0
#define MAXINT 32767
#define LONGMAXINT 0x7fffffff
/** HEAD Print last several lines of a file.
Usage: head [-n[lbc]] [file ...]
where n is the number of lines (l), 512 byte blocks (b), or
characters (c) from the beginning of the file.
One or more files may be given; also, standard input will be
included in the list if it is a pipe or file. If more than one
file is given, the files will be separated by lines of the form:
==> file.nam <==
No copyright, dammit: this is PUBLIC DOMAIN!!!
*/
int nlines =MAXINT;
long numarg;
char unit ='l';
#define BUFLEN 512
char buf[BUFLEN];
char *bufpos,*bufend;
usage() {
puts("Usage: head [-#[lbc]] [file ...]");
puts("where # is the number of lines from the beginning of the file");
puts("and the file is standard input by default.");
exit(1);
}
processfile(f,s,b)
FILE *f;
char *s; /* file name */
int b; { /* >0 if we want to print it */
int lleft;
long cleft;
int len;
if (b>0) {fputs("==> ",stdout); fputs(s,stdout); puts(" <==");}
lleft=nlines;
cleft=numarg;
while (lleft && cleft) {
len=fread(buf, 1, cleft<BUFLEN ? (int) cleft : BUFLEN, f);
if (len==0) break;
cleft-=len;
if (unit!='c') {
bufpos= &buf;
bufend= &buf+len;
do {
bufpos=strnchr(bufpos,bufend-bufpos,'\n');
if (bufpos >= bufend) break;
++bufpos;
} while (--lleft);
len=bufpos-&buf;
}
fwrite(buf,1,len,stdout);
}
}
main(argc,argv)
int argc;
char **argv; {
int arg0 =1;
int arg;
FILE *f;
char c, *s;
/* parse numeric argument */
if (argc>1 && argv[1][0]=='-') {
s=argv[1]+1;
c=*s;
if (isdigit(c)) {
while (isdigit(c)) {
numarg=numarg*10+(c-'0');
c= *++s;
}
unit=c;
if (c=='b') {numarg<<=9; unit='c';}
else if (c!='c' && c!='l') --s;
++s;
}
if (*s) usage();
++arg0;
}
if (numarg==0) numarg=10;
if (unit!='c') {nlines=numarg; numarg=LONGMAXINT;}
arg=arg0;
--argc;
if (!isatty(0)) {
--arg0;
processfile(stdin,"Standard input",argc-arg0);
}
if (arg0>argc) usage();
for (; arg <= argc; ++arg) {
if (arg>arg0) putchar('\n');
/* Open file for input */
s=argv[arg];
f=fopen(s,"r");
if (f==ERROR) {
fputs("Cannot open ",stderr);
fputs(s,stderr);
fputs("\n",stderr);
exit(1);
}
processfile(f,s,argc-arg0);
}
}