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
the following code:
1) eliminates the bad practice of typedef'ing a struct
2) removed the mis-leading all caps of the struct field names
3) contains the needed #includes
4) contains the needed prototypes for the external (in another file) functions
5) checks for the worst of the many possible runtime errors
6) replaces the mis-leading 'L' with a meaningful name
7) modifies the file pointer variable to a commonly known name
suggest compiling with all warnings enabled (and fix the warnings)
for gcc, at a minimum, use '-Wall -Wextra -pednatic'
#include
#include
#include
struct Book
{
char *title;
char *author;
char *publisher;
int year;
char *language;
int pages;
float price;
};
int reglen( struct Book * );
int readData( struct Book * );
void writeRegister(FILE *fp, struct Book *myBook)
{ //writes in actual file position
char c = '|';
int sizeRegWrite = reglen(myBook); //reglen() returns the size of Book
fwrite(&sizeRegWrite, sizeof(int), 1, fp);
fwrite(myBook->title, sizeof(char), strlen(myBook->title), fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(myBook->author, sizeof(char), strlen(myBook->author), fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(myBook->publisher, sizeof(char), strlen(myBook->publisher), fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(&(myBook->year), sizeof(int), 1, fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(myBook->language, sizeof(char), strlen(myBook->language), fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(&(myBook->pages), sizeof(int), 1, fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
fwrite(&(myBook->price), sizeof(float), 1, fp);
fwrite(&c, sizeof(char), 1, fp); //writing delimiter
return;
} // end function: writeRegister
int main( void )
{
FILE *fp = fopen("BD_books2.bin", "rb");
if(fp == NULL)
{
perror( "fopen for BD_books2.bin failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
struct Book myBook;
int goodRead = readData(&myBook); //Reads all fields from keyboard and places in Book. Working properly
if( goodRead )
{
writeRegister(fp, &myBook);
}
system("pause");
return 0;
} // end function: main