Hi all. I'm currently working on a small project which consists of reading struct from a file. The file contains info on separated lines and each bunch of 6 lines form a struct. I have some little problems and if anyone could help me I would really appreciate !
Currently I have 2 problems when compiling:
-"BOOK book;"
-"books[num_books] = book;"
I thought we could declare a new instance of a struct in the function but it gives me the "Undeclared identifier"...
The other error says "cannot convert from int to bookInfo", but I'm trying to assign a value from a struct book to the num_books value of the struct array, which is a struct...
Any help would be appreciate. Thanks
Currently I have 2 problems when compiling:
-"BOOK book;"
-"books[num_books] = book;"
I thought we could declare a new instance of a struct in the function but it gives me the "Undeclared identifier"...
The other error says "cannot convert from int to bookInfo", but I'm trying to assign a value from a struct book to the num_books value of the struct array, which is a struct...
Any help would be appreciate. Thanks
Code:
#include "stdafx.h"
#include "stdio.h"
#include <stdlib.h>
/* Struct containing the informations on a book */
struct book
{
char title[80];
char autor[40];
char editor[20];
char ISBN[10];
char subject[20];
int releaseDate;
};
typedef struct book bookInfo;
int main()
{
char c[50]; // Store line we read
FILE *file; // File containing the data
bookInfo *books; // Array of books, UNKNOWN size !
char *buff; // Buffer to read in the file
int num_books = 0; // Keep the count of number read in
int i, j;
/* First step we open the file and see if it's correct */
file = fopen("books.txt", "r");
if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
while(fgets(buff, sizeof(buff), file) != NULL) /* Loop until there's nothing to read
*/
{
BOOK book;
/*read a line and put it in the struct */
if(parseline(&book, buff) == 0)
{
books = realloc(books, (num_books + 1) * sizeof(BOOK));
if(!books)
{
/* out of memory, bale */
books[num_books] = book;
num_books++;
}
}
}
} // end else
fclose(file); /* close file */
for(i=0 ; i<num_books; i++)
{
printf("%s\t ", books[i].title);
//printf(every other fields of the struct....)
}
if(books!=NULL)
{
free(books); /* free any allocated memory */
}
return 0;
}
/* Function that reads the current line of the file and puts it in an array */
int parseline(BOOK *out, const char *str)
{
int i;
/* stop on tab, but also on end of string or overflow so we don't crash*/
for(i=0; str[i] != '\t' && str[i] != 0 && i < 63;i++)
out->title[i] = str[i];
out->title[i] = 0;
/* return -1 on parse error */
if(str[i] != '\t')
return -1;
/* for convenience, move the pointer along for the next field */
str += i +1;
/* now do the same thing for the other fields */
/* 0 to indicate OK */
return 0;
}