how to write/read vector of A Class safely with fstream in C++? -


recently got annoying bug read data vector of class.i have written simple program test fstream in main function , worked without problem. while coding book class in book.h , implement class in book.cpp,then attempted write vector of book file ofstream,no bug occurred.

 //write data ofstream output("book.bat",ios::binary);         if( !output ){             exit(-1);         }         output.write(reinterpret_cast<char*>(&books[0]),sizeof(book)*books.size());           output.close();   //read data ifstream input("book.bat",ios::binary);         if( !input ){             exit(-1);         }         book tmp;         while( input.read(reinterpret_cast<char*>(&tmp),sizeof(book)) ) {             books.push_back(tmp);          }          input.close(); 

unfortunately when program run step of readding file vector,the bug occurred.having searched hours, got nothing deal bug. help.

for point of view of class type encapsulates internal representation, read/write using direction of memory , size of type error. work pod types, if book type data pointers dynamic memory, code not work.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -