在从文件中提取的字符串中查找输入子字符串

Finding input substring in string extracted from File

基本上,我想知道为什么这段代码不起作用。 strstr() 的值似乎总是 NULL,因为这段代码所做的所有事情都是 "word not found"

我已经试过了if (strstr(retezec,substring)!=NULL),但还是不行。

int main()
{

    FILE *files;
    files = fopen("Knihovna.txt","rb+");

    int i = 0;
    while(fgetc(files)!=EOF){
        i++;
    }
    //printf("%d",i);

    rewind(files);
    char *retezec;
    retezec = (char *)malloc(i);
    fread(retezec, i, 1, files);

    puts("zadejte hledane slovo");

    char *substring;
    substring = (char *)malloc(50);
    fflush(stdin);
    fgets(substring,49, stdin);

    char *found;
    found = strstr(retezec,substring);

    if(found){
        printf("word found!");
    }
    else{
        puts("word not found");
    }

}

这很可能是 fgets() 读取尾随换行符的结果。

fgets(substring,49, stdin);

如果 substring 有 space,这将读取结尾的换行符。所以如果你输入"name"。你实际上有 "name\n".

删除尾随的换行符:

char *p = strchr(substring, '\n');
if (p) *p = 0; // remove the newline, if present

你还有一个问题。 fread()NUL 不终止。它只是读取请求的字节。因此,您需要检查 fread() 是否读取了 i 字节或更少,并使用该数字(fread() 的 return 值)来查找实际读取的字节数。因为它可能比要求的少。然后,分配一个额外的字节,如果您想将其用作 C-string.

,则 NUL 终止它