Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
//**************************************
//
//INCLUDE files for :simplegrep
//**************************************
//
stdio.h, and string.h
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
Terms of Agreement:
By using this code, you agree to the following terms...
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for langauges that allow it) freely and with no charge.
2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
//
#include
#include
#define MAXDATASIZE 1024
void usage(void)
{
printf("usage:\t./simplegrep filename pattern\n");
printf("example:./simplegrep sipmlegrep.c int\n");
}
int main(int argc, char *argv[])
{
FILE *fp;
char fline[MAXDATASIZE]; /* string to use to store data from the file */
char *newline; /* pointer to get rid of pesky newlines that come from fgets */
int count = 0; /* line count (just nifty thingy) */
int occurences = 0; /* self explanitory */
/* time to check for all the correct args. */
if(argc != 3)
{
usage();
exit(1);
}
/* Ok, this is a funky way of opening the file and seeing if
fopen worked. bare with me here. */
if(!(fp = fopen(argv[1], "r")))
{
printf("simplegrep: Could not open file: %s\n", argv[1]);
exit(1);
}
/* Ok, time to read the file line by line and search for our keyword */
while(fgets(fline, MAXDATASIZE, fp) != NULL)
{
count++; /* might as well increment this every time that we get a new line =P */
/* fgets returns null on EOF and on error. So, we just keep
looping until we hit null, grabbing a new line every time */
/* check for a newline and get rid of it. */
if(newline = strchr(fline, '\n'))
*newline = '\0';
/* ok, time to check for our word. */
if(strstr(fline, argv[2]) != NULL)
{
/* we found our word! */
printf("%s:%d %s\n", argv[1], count, fline);
occurences++;
}
}
printf("simplegrep found: %d occurences of: ``%s''\n", occurences, argv[2]);
}