All pastes #458914 Raw Edit

Untitled

public text v1 · immutable
#458914 ·published 2007-04-26 05:19 UTC
rendered paste body
/*****************************
/*	grep.c file
/* ubios.c has the O_... in #define
/*****************************/

#include "ucode.c"

int putLineIntoBuffer(int fd, char* buffer, int bufSize)
{
	int spaceLeft = bufSize;
	int amtRead; 
	
	while(spaceLeft)
	{
		amtRead = read(fd,buffer,1);
		if(0 == amtRead || -1 == amtRead)
		{
			return -1;
		}/*end if read no more*/
		else if('\n' == *buffer)
		{
			/* *buffer='\0';*/
			*buffer=0;
			break;
		}/*end if pts to line break*/
		spaceLeft--;
		buffer++;
	}/*end while space is left*/
	return bufSize - spaceLeft;
}/*end int putLineIntoBuffer*/

int main(char* argLine)
{
	int fd;
	int i;
	int amtRead;
	
	char c;
	
	char inputLine[1024];
	char* linePlace;
	
	char* pattern;
	char* fileArg;

	/*get rid of carriage returns, enter, tab and spaces
	  grabs first arg out*/
	if(!strtok(argLine,"\r\n\t "))
	{
		return -1;
	}

   printf("^2 %s$\n\r", inputLine);

	/*grab second and third arg, tokenized same as first*/
	pattern = strtok(0, "\r\n\t ");

   printf("^3 %s$\n\r", inputLine);

	if(!pattern)
	{
		printf("grep: give me a pattern\n\r");
	}
	
	fileArg = strtok(0,"\r\n\t ");
	
	if(fileArg)
	{
		/*invariant: happens at least once, 
		  continues while there is more, 
		  tokenized same as the first*/
		do
		{
			fd=open(fileArg,O_RDONLY);
			if(-1 < fd)
			{
				/*get a line into the buffer*/
				while(-1 != putLineIntoBuffer(fd,inputLine,sizeof(inputLine)))
				{
					/*if exists inline, display*/
					if(strstr(inputLine,pattern))
					{
						printf("%s: %s\n\r",fileArg,inputLine);
					}/*end if exist, print the line*/
				}/*while has characters, put to screen*/
			}/*if have a valid fd*/
			else
			{
				printf("grep error! %s caused error.\n\t",fileArg);
			}
			close(fd);
		}while(fileArg = strtok(0,"\r\n\t "));
	}/*end if second arg exists*/
	else
	{
		/*no file exists...do on stdin?*/
				/*get & display*/
		while(read(0,&c,1))
		{
			putc(c);
			if('\n'==c)
			{
				putc('\r');
			}/*if newline, do hard return*/
		}/*while has characters, put to screen*/
	}/*end else: do from stdin*/
	
	
}/*end main*/