在 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);
}
最佳答案
为什么不使用 getline() 获取逐行缓冲区,然后在该缓冲区中执行 strstr() ?
关于c - 在文本文件中搜索匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048638/