Reputation: 59
I'm a complete amateur when it comes to C and I was having some trouble trying to write this piece of code. I want it to check the text file for any line that matches the given string.
For example, if "stackoverflow" was in the text file and the string I was entered was "www.stackoverflow.com" it should return a positive match.
But currently it is searching for the string inside of the text file, which is the opposite of what I want. I would appreciate any hints/tips!
int Check(char *fname, char *str) {
FILE *file;
int i = 1;
int r = 0;
char temp[1000];
if((file = fopen(fname, "r")) == NULL) {
return(-1);
}
while(fgets(temp, 1000, file) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("Host name found on line: %d\n", i);
printf("\n%s\n", str);
r++;
}
i++;
}
if(r == 0) {
printf("\nHost name not blocked.\n");
}
if(file) {
fclose(file);
}
return(0);
}
Upvotes: 5
Views: 898
Reputation: 1387
Why not use getline() to get a line-by-line buffer and then do a strstr() in that buffer ?
Upvotes: 1