2011-11-27 52 views
0

我不明白什麼是寫入文件file.write((char *) this, sizeof(BOOK)) ;。請解釋一下:)C++什麼fstream寫入函數寫入文件(coden在後)

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

您的代碼不夠完整,無法理解。請檢查它是否編譯並以某種方式運行後,請提供一個獨立的示例。 –

回答

2

大概你所引述的功能是class BOOK的成員函數,而write通話將簡單地傾倒在當前BOOK實例的整個二進制表示到文件中。 (this的類型爲BOOK*。)

這通常不是一個非常便攜或者明智的事情,因爲未來的序列化數據使用者無法知道實際的序列化格式。 (未來的消費者可能會在不同的機器上或不同的編譯器上。)如果你想認真對待它,查找適當的序列化策略。

+0

這個函數將所有char變量的數據寫入文件? 'file.write((char *)this,sizeof(BOOK));'。請解釋:) – Wizard

+0

解釋正是我所發佈的:*類的*二進制表示被寫出來。這樣做並不是一個好主意,因爲你很難控制實際發生的事情。 –

+0

謝謝隊友,你幫我;) – Wizard

0
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 
    }