binaryfiles - C++ reading/writing objects with binary files -
binaryfiles - C++ reading/writing objects with binary files -
i have gone through hours of time trying prepare issue of binary file manipulation.
the task read , write bookstorebook objects to/from binary file
the bookstorebook class contains next fellow member variables:
string isbn; string title; author author; string publisher; date dateadded; int quantityonhand; double wholesalecost; double retailprice;
the code reading books shown:
fstream file("inventory.txt", ios::binary | ios::in | ios::out); vector<bookstorebook> books: bookstorebook *book = (bookstorebook *)new char[sizeof(bookstorebook)]; file.read((char*)book, sizeof(bookstorebook)); while (!file.eof()) { books.push_back(*book); file.read((char*)book, sizeof(bookstorebook)); }
the code writing books shown:
vector<bookstorebook> writebooks = library.getbooks(); //library contains books file.close(); file.open("inventory.txt", ios::out | ios::binary); for(int = 0; < writebooks.size(); i++) { bookstorebook *book = (bookstorebook *)new char[sizeof(bookstorebook)]; book = &writebooks[i]; file.write((char*)book, sizeof(bookstorebook)); file.clear(); } file.clear(); file.close();
i don't want convert string c_str(), prohibited in assignment requirements.
some notes:
right when run program, programme tries read books file, , when windows error window, later when debug, next message: unhandled exception @ 0x56b3caa4 (msvcr100d.dll) in finalproject.exe: 0xc0000005: access violation reading location 0x0084ef10
the funny thing is, programme runs fine, , crashes when first reads books file.
however, whenever programme has read contents, , dont modify books, , reopen program, programme keeps running perfectly.
nothing seems work. please help!
your problem here parts of bookstorebook
class contain pointers, though not visible. std::string
illustration has pointer memory location contents of string kept.
it virtually considered bad practice write info structures in c++ disk appear in memory. doing not business relationship different endianness of different machines, word width on different machines (int
or long
may differ in size on 32bit , 64bit machines), , run pointer trouble.
you should force each of fields of bookstorebook
output stream, along lines of
file << book.isbn << ' '; file << book.title << ' '; ...
note above bad practice, decoding gets horribly difficult. suggest utilize boost.serialization this, or write own methods can read/write key-value-pairs file, or might want jsoncpp or tinyxml2. whole topic can quite convoluted, sticking boost idea, if figure out how solve issue (assuming homework assignment).
c++ binaryfiles
Comments
Post a Comment