我是一個完整的業餘愛好者,當談到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);
}
你好,歡迎來到StackOverflow!你嘗試用'strstr(str,temp)'切換'strstr(temp,str)'嗎? – 2014-11-20 20:14:57
是的,但是當我試過時,即使我比較的字符串是相同的,我也不會得到任何結果。 – Piglet 2014-11-20 20:16:45
請記住'fgets'捕獲一個尾隨換行符('\ n');你可能需要自己去掉它。 – 2014-11-20 20:17:59