Search code examples
c++fstream

c++ what fstream write function write to file (coden in post)


I'm don't understand what is written to a file file.write((char *) this, sizeof(BOOK)) ;. Please explain :)

void add_new_book(int tcode,char tname[33], char tauthor[26], float tprice, int tcopies, int tavail)
{
    fstream file ;
    file.open("BOOK.DAT", ios::app) ;
    bookcode = tcode ;
    strcpy(name,tname) ;
    strcpy(author,tauthor) ;
    price = tprice ;
    copies = tcopies ;
    avail = tavail ;
    file.write((char *) this, sizeof(BOOK)) ; }

Solution

  • Presumably the function you have quoted is a member function of a class BOOK, and the write call will simply dump the entire binary representation of the current BOOK instance into the file. (this is of type BOOK*.)

    This is usually not a very portable or sensible thing to do, since future consumers of the serialized data have no way of knowing the actual serialization format. (The future consumer may be yourself on a different machine or a different compiler.) Look up proper serialization strategies if you want to take this seriously.