home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
OS/2 Shareware BBS: 11 Util
/
11-Util.zip
/
BOUNDUTI.ZIP
/
GREP.C
next >
Wrap
C/C++ Source or Header
|
1990-08-16
|
3KB
|
116 lines
/*
-----------------------------------------
grep.c - locate all lines with string
-----------------------------------------
written 8/15/90 by M. Mackey
*/
#define INCL_DOS
#include <os2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXLINE 256
#define TRUE 1
#define FALSE 0
#define ATTR 0x0021
#define NORMAL_FILE 0x0000
#define OPEN_FLAG 0x01
#define OPEN_MODE 0x0040
#define LENGTH sizeof(buff)
char pattern[MAXLINE],line[MAXLINE];
static int index(void);
static void error(char *fmt,char *arg);
char *signon="\ngrep - simple file pattern searcher\n";
char *signoff="grep - finished\n";
char *usage="\nsyntax: grep [-n(umber)] pattern filename\n";
void main(int argc,char *argv[])
{
char pathname[_MAX_PATH],buf[10];
unsigned long lineno;
unsigned number=0,nlines,handle=0xffff,count=1;
struct _FILEFINDBUF buff;
unsigned short fhandle,rc,i;
unsigned faction,nbytes;
fprintf(stderr,"%s",signon);
if(argv[1][0]=='-') {
if(tolower(argv[1][1])=='n') {
number=1;
argv++;
argc--;
} else {
if(tolower(argv[1][1])!='h')
fprintf(stderr,"GREP: illegal option %c\n",argv[1][1]);
error("%s",usage);
}
}
if(argc!=3)
error("%s",usage);
strcpy(pattern,argv[1]);
strcpy(pathname,argv[2]);
if(rc=DosFindFirst(pathname,&handle,ATTR,&buff,LENGTH,&count,0L))
if(rc==18)
error("grep: file %s not found\n",pathname);
else
error("grep: internal error %s\n",itoa((unsigned)rc,buf,10));
while(TRUE) {
if(DosOpen(buff.achName,&fhandle,&faction,0L,NORMAL_FILE,OPEN_FLAG,
OPEN_MODE,0L))
error("grep: cannot open input file %s",buff.achName);
printf("-------------------- %s\n",buff.achName);
lineno=0L;
nlines=0;
while(TRUE) {
i=0;
while(TRUE) {
DosRead(fhandle,&line[i],1,&nbytes);
if(!nbytes || line[i]==0x0a)
break;
i++;
}
if(!(nbytes+i))
break;
line[++i]='\0';
lineno++;
if((index() >= 0)) {
if(number)
printf("%ld: ",lineno);
printf("%s",line);
nlines++;
}
}
printf("%u Line(s) found\n",nlines);
DosClose(fhandle);
DosFindNext(handle,&buff,LENGTH,&count);
if(!count)
break;
}
DosFindClose(handle);
fprintf(stderr,"%s",signoff);
exit(0);
}
int index(void)
{
int i,j,k;
for(i=0;line[i] != '\0';i++) {
for(j=i,k=0;pattern[k]!='\0' && line[j]==pattern[k];j++,k++)
;
if(pattern[k]=='\0')
return(i);
}
return(-1);
}
void error(char *fmt,char *arg)
{
fprintf(stderr,fmt,arg);
exit(1);
}