5

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);
}
Piglet
  • 59
  • 1
  • 1
  • 4

1 Answers1

1

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

Paul Praet
  • 1,367
  • 14
  • 25
  • Probably because [it is not a C Standard Library function](http://stackoverflow.com/questions/13112784/undefined-reference-to-getline-in-c). – Jongware Mar 26 '15 at 11:24