在文本文件中搜索匹配的字符串

时间:2014-11-20 20:12:18

标签: c

对于C来说,我是一个完全的业余爱好者,我在尝试编写这段代码时遇到了一些麻烦。我希望它检查文本文件中是否有与给定字符串匹配的行。

例如,如果" stackoverflow"在文本文件中,我输入的字符串是" www.stackoverflow.com"它应该返回一个积极的匹配。

但是目前它正在搜索文本文件中的字符串,这与我想要的相反。我很感激任何提示/提示!

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);
}

1 个答案:

答案 0 :(得分:1)

为什么不使用getline()来获取逐行缓冲区,然后在该缓冲区中执行strstr()?

相关问题