问题描述
我正在尝试将包含空格的给定字符串拆分为多个字符串。 然后,我试图将这些字符串/令牌传递给strstr(),以从给定文件中搜索相似的字符串。输出应在输出屏幕中显示匹配的字符串。我可以将字符串拆分为多个字符串,但是我在strstr()中遇到问题。它不是在搜索并向我提供匹配的单词。这是代码:
#include<stdio.h>
#include<string.h>
#define MAXCHAR 20000
int main(){
FILE *fp,*fp2;
char str[MAXCHAR];
char str2[MAXCHAR];
char str3;
char delim[] = " ";
fp = fopen("blacklist.txt","r");
if (fp == NULL)
{
printf("Cannot open %s\n","blacklist.txt");
return 1;
}
fp2 = fopen("email.txt","r");
if (fp2 == NULL)
{
printf("Cannot open %s\n","email.txt");
return 1;
}
while (fgets(str2,MAXCHAR,fp2) != NULL){
char *ptr = strtok(str2,delim);
while(ptr != NULL){
printf("%s\n",ptr);
ptr = strtok(NULL,delim);
}
while (fgets(str,fp) != NULL){
rewind(fp2);
while (ptr != NULL){
char *p = strstr(str,ptr);
if (p != NULL && (p == str || p[-1] == '.'))
{
int n = strcspn(str,"\n");
int n2 = strcspn(ptr,"\n");
printf("domain matched on %.*s for %.*s\n",n2,ptr,n,str);
break;
}
}
}
}
fclose(fp);
fclose(fp2);
return 0;
}
解决方法
从不输入while
之后的rewind
循环,因为您确保ptr
为null
(退出包含{{1}的循环的唯一方法})。
您正在分割字符串并打印出来,但是程序无法访问分割的字符串。
我认为最好这样构造程序:
strtok