I need to basically rewrite grep command:
method is suppose to take an exact string and an exact filename as the 2 arguments
grep<string><filename>
then it has to search through the file for the string and print out the "line" and the "line number" the string is in.
example #grep matt students
12 the student matt was late for class today
35 when class started matt was just walking in the door
Im using some code from a website.
This is what I have so far, but I've been working on asking the user for the filename to look at and I keep getting a seg fault. I feel like Im using the scanf() for the file improperly, also I believe I allocated enough memory for the file
#include <stdio.h>
const unsigned MAXLINE=9999;
char * skip_ws(char *line)
{
return line+strspn(line," \t");
}
char * findval(char *line,char const* prefix)
{
char *p;
int prelen;
prelen = malloc(strlen(prefix));
p=skip_ws(line);
if (strncmp(p,prefix,prelen)==0)
return p+prelen;
else
return NULL;
}
char *findval_slow(char *line,char const* prefix)
{
return findval(line,prefix);
}
int main() {
char line[MAXLINE];
char *p,*pend;
int findlen;
FILE *ifp;
char *string;
char filename[100];
long lsize;
char *buffer;
size_t result;
printf("what file do you want to look at\n");
scanf("%c", &filename);
ifp = fopen(&filename, "r");
if(ifp = NULL){
fprintf(stderr, "Cant open input file!\n");
exit(1);
}
//obtain file size
fseek(ifp, 0, SEEK_SET);
lsize = ftell(ifp);
printf("the file size is = %ld", lsize);
rewind(ifp);
//allocate memory to contain whole file
buffer = (char*) malloc (sizeof(char)*lsize);
if(buffer == NULL){
fputs ("memory error", stderr);
exit(2);
}
// copy the file into the buffer
result = fread(buffer, 1, lsize, ifp);
puts(buffer);
if(result != lsize){
fputs ("reading error", stderr);
exit(3);
}
printf("what string do you want to search for?\n");
scanf("%s", string);
findlen= strlen(string);
while (p=fgets(line,MAXLINE,ifp)) {
printf("Looking at %s\n",p);
if (p=findval(line,string)) {
pend=p+strlen(p)-1; /* check last char for newline terminator */
if (*pend=='\n') *pend=0;
printf("Found %s\n",p);
}
}
return 0;
}