1

Basically, I would like to know why this code doesn´t work. It appears that the value of strstr() is always NULL, as all this code ever does is "word not found".

I have already tried if (strstr(retezec,substring)!=NULL), but it doesn't work either.

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

}
P.P
  • 117,907
  • 20
  • 175
  • 238

1 Answers1

3

It's most likely the result of fgets() reading the trailing newline.

fgets(substring,49, stdin);

This would read the trailing newline if substring has space. So if you input "name". You actually have "name\n".

Remove the trailing newline with:

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

You have another problem. fread()doesn't NUL terminate. It simply reads the requested bytes. So you would need to check if fread() read i bytes or less and use that number (return value of fread()) to find the actual bytes read. Because it may be less than requested. And then, allocate one extra byte and NUL terminate it if you want to use it as a C-string.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • it does seem to read as it should. Checked that with printing out the entire file (if that is what you mean. I am really NEW to programming and C in particular. – Vojta Martinec Jan 03 '16 at 11:10
  • 1
    @VojtaMartinec It usually does. In case of failure, it may have read less `i` bytes. It's always best to check the return value of library functions/system calls than assuming success. You must NULL terminate it though. – P.P Jan 03 '16 at 11:12
  • Thank you very much. Finally solved. – Vojta Martinec Jan 03 '16 at 13:09