Can someone tell my why won't this function work? I just can't get it...
void writeRegister(FILE *arq, Book *L){ //writes in actual file position
char c = '|';
int sizeRegWrite = reglen(L); //reglen() returns the size of Book
fwrite(&sizeRegWrite, sizeof(int), 1, arq);
fwrite(L->TITLE, sizeof(char), strlen(L->TITLE), arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->AUTHOR, sizeof(char), strlen(L->AUTHOR), arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->PUBLISHER, sizeof(char), strlen(L->PUBLISHER), arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->YEAR, sizeof(int), 1, arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->LANGUAGE, sizeof(char), strlen(L->LANGUAGE), arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->PAGES, sizeof(int), 1, arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
fwrite(L->PRICE, sizeof(float), 1, arq);
fwrite(&c, sizeof(char), 1, arq); //writing delimiter
return;
}
The struct Book is declared like this:
typedef struct {
char *TITLE;
char *AUTHOR;
char *PUBLISHER;
int YEAR;
char *LANGUAGE;
int PAGES;
float PRICE;
} Book;
Main
int main() {
FILE *arq = fopen("BD_books2.bin", "rb+");
if(arq == NULL)
printf("Error while opening file!!!");
Book L;
readData(&L); //Reads all fields from keyboard and places in Book. Working properly
writeRegister(arq, &L);
system("pause");
return 0;
}
I have to use those pointers inside the struct, so I can't remove them. By the way, my problem is only with those integers and the float.
This fuction is only working properly if I write all the integers and floats (YEAR, PAGES and PRICE) with fprintf(), but I'm writing it in a binary file, and of course I want to write it in binary, so I'm trying to use fwrite().
Another thing is: the compiler is pointing incompatible type for argument 1 of 'fwrite' at this line: fwrite(L->PRICE, sizeof(float), 1, arq);
Can someone explain me what is happening? My program crashes when it tries to write in the file...
readDataandreglenmay well play in to this. Any reason in particular you chose not to include them, if for no other reason than to finish the MCVE?fwrite(&sizeRegWrite, sizeof(int), 1, arq);, consider the modelfwrite(&var, sizeof var, 1, arq);fprintfto write each line andfscanfto read the file) or a more structured binary format (like length-prefixed strings)?