Search code examples
cfilestrstr

searching for EXACT string with spaces in . txt file from C program


struct Book {
        char *title;
        char *authors; 
        unsigned int year; 
        unsigned int copies; 
};


int existance_of_book(char title[])
{
    char string[30];
    ptr_to_library = fopen("library.txt", "r");

  if(ptr_to_library == NULL)
  {
    printf("\nERROR: cannot open file\n");
    return -1;
  }

    while (fgets(title, sizeof(title), ptr_to_library) != NULL)
  {
    if(strstr(string, title)!=0)
    {
      printf("book found\n");
      return 1;
    }
  }
    return 0;
}

I am Trying to search for a string in a file, but since the string I will be searching for has a space in it this function is unable to find the string. this function will also find a match if for example the string in the .txt file reads "hello", and the string entered in the function is "he". Is there a way to search for the exact string in a file even if there are spaces


Solution

  • Use strstr to find the sub-string.
    Check that the sub-string is either at the beginning of the line or is preceded by punctuation or whitespace.
    Also check that the sub-string is either at the end of the line or trailed by punctuation or whitespace.
    If fgets is used to obtain the sub-string to find, be sure to use strcspn to remove the trailing newline. In the line from the file, the trailing newline should not matter, but this code uses strcspn to remove it.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    #define SIZE 1024
    
    int main ( void) {
        char find[SIZE] = "he";
        char line[SIZE] = "";
        char const *filename = "library.txt";
        char *match = NULL;
        FILE *pf = NULL;
    
        if ( NULL == ( pf = fopen ( filename, "r"))) {
            perror ( filename);
            exit ( EXIT_FAILURE);
        }
    
        int length = strlen ( find);
    
        while ( fgets ( line, SIZE, pf)) {//read lines until end of file
            line[strcspn ( line, "\n")] = 0;//remove newline
            char *temp = line;
            while ( ( match = strstr ( temp, find))) {//look for matches
                if ( match == line //first of line
                || ispunct ( (unsigned char)*(match - 1))
                || isspace ( (unsigned char)*(match - 1))) {
                    if ( 0 == *(match + length)//end of line
                    || ispunct ( (unsigned char)*(match + length))
                    || isspace ( (unsigned char)*(match + length))) {
                        printf ( "found %s in %s\n", find, line);
                        break;//found a match
                    }
                }
                temp = match + 1;//advance temp and check again for matches.
            }
        }
    
        fclose ( pf);
    
        return 0;
    }