I am trying to read a text file line by line and tokenize them into elements of a struck using custom function. Yet I get an infinite loop trying to do so. My code is as follows:
typedef struct
{
char barcodeNumber[5];
char title[50]; char author[30];
char publisherCompany[30];
int publishingYear;
char isbn[13];
} Book;
Book booklist[100];
void readBooks()
{
int i = 0;
char line[255];
printf("asd");
FILE *libraryPtr;
libraryPtr = fopen("books.txt", "r");
if (libraryPtr == NULL)
printf("File not found.n");
else
{
while (fgets(line, sizeof(line), libraryPtr) != NULL)
{
booklist[i].barcodeNumber = strtok(line, ";");
booklist[i].title = strtok(NULL, ";");
booklist[i].author = strtok(NULL, ";");
booklist[i].publisherCompany = strtok(NULL, ";");
booklist[i].publishingYear = strtok(NULL, ";");
booklist[i].isbn = strtok(NULL, ";");
i++;
}
}
fclose(libraryPtr);
printf("%s", booklist[1].barcodeNumber);
}
My input file is (Books.txt):
A1234;Elements of Theory of Computation;Harry R. Lewis;Prentice Hall;1998;2132457198219
A1987;Knowledge Acquisiton;Karen L. McGraw;Prentice Hall;1989;1945868279220
M3158;Artificial Intelligence;Patrick H. Winston;Addison Wesley;1992;3243568791940
C8287;Linux Sistem Yonetimi;Tom Adelstein;O'Reilly;2007;1718295464178
E6097;CRYPTOGRAPHY AND NETWORK SECURITY PRINCIPLES;William Stallings;Prentice Hall;2007;9780136097044
2
Answers
Strings in C are not like in some high level language, you cannot somply assign strings with the
=
operator. A complete explanation is beyond the scope of this answer.You need this inside your while loop (minumum code, no error checking and/or bounds checking done here).
Id didn’t test the code, but it should at least give you an idea.
For
atol
you also need to include:EDIT:
should be
You need space for the terminating zero.
Try this code fragment replacing some of your function code. The errors were due trying to write the
strok
pointer to a string, instead of copying the string. Apart from being the wrong type, the string pointers became invalid once you moved on to the next line. I also tweaked the way you did the year integer field, and limited the string lengths and the array sizei
too.