The reader and writer
#include<string> #include<fstream> #include<memory> class BinarySearchFile{ BinarySearchFile::BinarySearchFile(std::string file_name){ // concatenate extension to fileName file_name += ".dat"; // form complete table data filename data_file_name = file_name; // create or reopen table data file for reading and writing binary_search_file.open(data_file_name, std::ios::binary); // create file if(!binary_search_file.is_open()){ binary_search_file.clear(); binary_search_file.open(data_file_name, std::ios::out | std::ios::binary); binary_search_file.close(); binary_search_file.open(data_file_name), std::ios::out | std::ios::in | std::ios::binary | std::ios::ate; } std::fstream binary_search_file; void BinarySearchFile::writeT(std::string attribute){ if(binary_search_file){ binary_search_file.write(reinterpret_cast<char *>(&attribute), attribute.length() * 2); } } std::string BinarySearchFile::readT(long filePointerLocation, long sizeOfData) { if(binary_search_file){ std::string data; data.resize(sizeOfData); binary_search_file.seekp(filePointerLocation); binary_search_file.seekg(filePointerLocation); binary_search_file.read(&data[0], sizeOfData); return data; } }; The reader call
while (true){ std::unique_ptr<BinarySearchFile> data_file(new BinarySearchFile("classroom.dat")); std::string attribute_value = data_file->read_data(0, 20); } The writer call
data_file->write_data("packard "); The writer writes a total of 50 bytes
"packard 101 500 " The reader is to read the first 20 bytes and the result is "X packard X" where X represents some malformed bytes of data. Why is the data read back in x-number of bytes corrupt?
std::fstream::write()and subsequently read those 20 bytes usingstd::fstream::read().