T
The_Kingpin
Hi again guys,
I've decided to cut my project in section and I found it way easier like
this. I'm having a little problem reading struct in a file though. I think
after this I'll be able to handle it on my own.
Right now the file is opened correctly and I'm able to read each line and
print them in a new file. My problem is to insert each struct (which are
made of 6 consecutive lines) as an item in my array.
When reading a line in the file books.txt, this is how I currently assign
a value to a field of the struct infoBook. Then, when the struct is
completed (with the 6 fields having value), I need to add this struct to
the array books, which I'm not able right now I'm not sure my structure is
correct, but I tried regrouping all the info I learned so far...
Here's the part of the function where I treat the file info
I've decided to cut my project in section and I found it way easier like
this. I'm having a little problem reading struct in a file though. I think
after this I'll be able to handle it on my own.
Right now the file is opened correctly and I'm able to read each line and
print them in a new file. My problem is to insert each struct (which are
made of 6 consecutive lines) as an item in my array.
Code:
for(i=0, j=0; c[i]!='\t'; i++, j++) {
/* Loops until a tab character is reached */
books[num_books].title[j] = c[i];
}
/* add a null character to terminate string */
books[num_books].title[j] = '\0';
When reading a line in the file books.txt, this is how I currently assign
a value to a field of the struct infoBook. Then, when the struct is
completed (with the 6 fields having value), I need to add this struct to
the array books, which I'm not able right now I'm not sure my structure is
correct, but I tried regrouping all the info I learned so far...
Here's the part of the function where I treat the file info
Code:
file = fopen("books.txt", "r");
if(file==NULL) {
printf("Error: can't open file.\n");
return 1;
}
else {
while (!feof(file)){
if(num_books==0) {
books = calloc(1, sizeof(bookInfo));
}
else {
books = realloc(books, (num_books+1)*sizeof(bookInfo));
}
/* This is where I try to store info from the file in our struct field.
*/
//Title field
for(i=0, j=0; c[i]!='\t'; i++, j++) {
/* this keeps looping until a tab character is reached */
books[num_books].title[j] = c[i];
}
/* add a null character to terminate string */
books[num_books].title[j] = '\0';
/* Autor field */
for(i++, j=0; c[i]!='\t'; i++, j++) {
books[num_books].autor[j] = c[i];
}
books[num_books].autor = '\0';
/* Editor field */
for(i++, j=0; c[i]!='\0' && c[i]!='\n'; i++, j++) {
/* store the gender but ignore the last newline character */
books[num_books].editor[j] = c[i];
}
books[num_books].editor[j] = '\0';
num_books++; /* keep track of how many we stored */
}