Search code examples
cfunctionfilesearchproject

how to search around a file for a matching string with a given one?


void merr_liber()
{
  FILE *fp_merr_liber;
  FILE *fp_librat;
  
  struct merr_liber input;
  struct librat liber;
  
  char isbn[13];
 
  int zgjedhja;
  
  fp_merr_liber = fopen("librat_e_marre.txt", "ab+");
  fp_librat = fopen("librat.txt", "r");
  

  if (fp_merr_liber == NULL)
  {
    printf("\nError merr_librat.txt nuk mund te hapet\n\n");
    exit(1);
  }
  if (fp_librat == NULL)
  {
    printf("\nError librat.txt nuk mund te hapet\n\n");
    exit(1);
  }
  while (!feof(fp_librat))
  {
     printf("\nISBN: ");
     scanf("%s", isbn);
     fscanf(fp_librat, "%s", liber.isbn);
     if (unike(isbn, 13) && valide(isbn, 13) && !strcmp(isbn, liber.isbn))
     {
        strcpy(input.isbn, isbn);
        fprintf(fp_merr_liber, "%s\n", input.isbn);
        break;
     }
     if (strcmp(isbn, liber.isbn) != 0)
     {
        printf("Nuk ekziston nje liber me kete isbn.\n");
        printf("Deshironi te vazhdoni ? (1- vazhdo 0- kthehu ne menune kryesore): ");
        scanf("%d", &zgjedhja);
        
        if (zgjedhja == 1)
        {
            continue;
        }
        else
        {
            menu();
        }
     }
     printf("Gabim ne formatin e isbn, isbn ka 13 karaktere, te cilat jane unike.");
  }

  
  fclose(fp_merr_liber);
  fclose(fp_librat);
}

I have a function that gets the string isbn from the user and then compares it to the member of the structure librat which is saved into a file. I am having difficulties since my while loop is only searching throw the first row and not the entire file. The inside functions are just for formatting and do not play any role in writing or reading the file. The labels are in my native language and I hope that beside this the code is still readable. I only need one instance since the string isbn is unique


Solution

  • You're trying to get a new string as an input in every iteration of the while loop which is probably not what you want.

    One thing you can do is create a different while loop and use fscanf() until the end of file is reached and compare each string gotten from the file with the string that you want to find, also don't forget to move the file position pointer to the beginning of the file after the end of file is reached.