Wizard
Wizard

Reputation: 11275

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)) ; }

Upvotes: 0

Views: 648

Answers (2)

LOLOLOL
LOLOLOL

Reputation: 125

    void add_new_book (BOOK &book){    // call the function as: add_new_book(book1);
        fstream file ;                 // where book1 is an object of class BOOK
        file.open("BOOK.DAT", ios::app) ;
        bookcode = book.bookcode ;
        strcpy(name,book.name) ;
        strcpy(author,book.author) ;
        price = book.price ;
        copies = book.copies ;
        avail = book.avail ;
        file.write((char *)this, sizeof(BOOK)) ;
        file.close() ;    //don't forget to close the file 
    }

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477150

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.

Upvotes: 2

Related Questions