2011-11-27 53 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 
    }