Source

tailgrep / tg.c

Full commit
#include <stdio.h>
#include <stdlib.h>

#define CHUNK 1024

void
readPrint (FILE *ifp, size_t nread, char *readbuffer)
{
	if (ifp)
	{
		while ((nread = fread(readbuffer, 1, CHUNK, ifp)) > 0)
		{
			fwrite(readbuffer, 1, nread, stdout);
		}
		
		fclose(ifp);
	}
}

void
grepInclude ()
{

}

void
grepExclude ()
{

}

int
main (int argc, char *argv[])
{	

	char *filename = NULL;
	char *pattern = NULL;
	char *readbuffer = malloc(CHUNK);
	size_t nread;
    FILE *ifp;

	if (argc < 1 && stdin == NULL) 
	{
		fprintf(stderr, "Usage: %s <filename> <pattern>\n", argv[0]);
		return 1;
	} 


	if (argc > 1) 
    {
	    while (--argc > 0)
	    {
	    	filename = argv[1];
	    	pattern = argv[2];
	    }
	    ifp = fopen(filename, "r");
    }
    else
    {
        filename = "stdin";
	    ifp = stdin;
    }

	if (ifp == NULL)
	{
		fprintf(stderr, "File open error.\n");
		exit(1);
	}

	if (readbuffer == NULL)
	{
		fprintf(stderr, "Could not allocate read buffer.\n");
		exit(1);
	}

	printf ("File being concatenated: %s\n", filename);
	printf ("Pattern used for filter: %s\n\n", pattern);
    readPrint (ifp, nread, readbuffer);

	free (readbuffer);
	
	return 0;
}