EOF not detected right when using strtok()?

30 Views Asked by At

So I have a load function that reads in this comma separatedtext data

9780136019701,An Introduction to Organic Chemistry,Timberlake Karen,10,3.54,12-2008
9781506304212,Mathematics for Social Scientists,Kropko Jonathan,7,4.73,12-2015
9781506304213,Discrete Mathematics,Jonathan,15,19.73,10-2013
9780136019702,Chemotherapy,Karen,1,2.54,1-2002
9781152304222,Advanced Mathematics Techniques,Antony Smith,5,5.21,2-2007 
9781506304215,Social Studies,Simon Minter,10,9.73,11-2013

I know there are 6 properties so I read in a line and keep calling strtok to get the next token and storing it in books which is an array of struct Book which has all these properties in it.

int load(Book *books, int* numberOfBooks){
  system("cls");
  // Implement
  int bookCounter = 0;
  char c;
  char line[STRING_LENGTH];

  FILE *file = fopen("books.txt", "r");
  if (file == NULL){
    printf("Error opening file");
    exit(1);
  }

  while (!feof(file))
  {
    fgets(line, STRING_LENGTH, file);
    line[strcspn(line, "\n")] = 0;
    printf("\n%s \n", line);
    
    char *bookToken = strtok(line, ",");

    strcpy(books[bookCounter].isbn, bookToken);

    bookToken = strtok(NULL, ",");

    strcpy(books[bookCounter].title, bookToken);

    bookToken = strtok(NULL, ",");
    strcpy(books[bookCounter].author, bookToken);

    bookToken = strtok(NULL, ",");
    int quantity = atoi(bookToken);
    books[bookCounter].quantity = quantity;

    bookToken = strtok(NULL, ",");
    double price = atof(bookToken);
    books[bookCounter].price = price;
    
    bookToken = strtok(NULL, ",");
    strcpy(books[bookCounter].date, bookToken);
    
  }
    bookCounter++;
    
  }
  fclose(file);
  printf("%d", bookCounter);

  return 0;


}

The problem is that when I call this, everything seems to be working fine (after checking with lots of print statements) however when it gets to the end of the file, it seems to get stuck on something. It doesnt just terminate when the file ends.

This is the print statement for every line

780136019701,An Introduction to Organic Chemistry,Timberlake Karen,10,3.54,12-2008

781506304212,Mathematics for Social Scientists,Kropko Jonathan,7,4.73,12-2015

781506304213,Discrete Mathematics,Jonathan,15,19.73,10-2013

780136019702,Chemotherapy,Karen,1,2.54,1-2002

781152304222,Advanced Mathematics Techniques,Antony Smith,5,5.21,2-2007

781506304215,Social Studies,Simon Minter,10,9.73,11-2013

781506304215

I didnt leave anything out, it gets stuck on this last isbn which isnt part of the file, its the last isbn printing again for some reason

0

There are 0 best solutions below