Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching text file for matching string

Tags:

c

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);
}
like image 690
Piglet Avatar asked Nov 09 '22 22:11

Piglet


1 Answers

Why not use getline() to get a line-by-line buffer and then do a strstr() in that buffer ?

like image 117
Paul Praet Avatar answered Nov 15 '22 13:11

Paul Praet