I am playing with examples from book, I have modified one example and it does not provide correct result.
I am not sure why.
I am closing file after user provides data, file is saved (if i delete file is recreated and its size is 1KB)
When I try to read it and get the size of person object I am not getting correct value. I am getting 1.
int on its own should be 4KB plus size of string which I think for name such as tom is 12kb (not sure if this is correct)
#include <iostream>
#include <fstream> //for file stream
class Person
{
protected:
std::string name; // person name
int age; // person age
public:
void getData() // get person data
{
std::cout << "Enter name: ";
std::cin >> name;
std::cout << "Enter age: ";
std::cin >> age;
}
};
int main() {
Person person; // create person
person.getData(); // get data from user
std::ofstream outfile("Person.dat", std::ios::binary); // write it
outfile.write(reinterpret_cast<char*>(&person), sizeof(person));
outfile.close();
std::ifstream inFile("Person.dat",std::ios::in | std::ios::binary);
inFile.seekg(0, std::ios::end); // go to the end of the file
int endOfFile = inFile.tellg();
//std::cout << sizeof(person) << std::endl;
endOfFile /= sizeof(person);
std::cout << "each person have its size this one is.... " << endOfFile << "bytes" << std::endl;
std::cin.get();
return 0;
}
Line 25: You can't use write to output a struct/class that contains a std::string. std:string is a complex data type that contains a pointer to data maintained on the heap. When you write out a std::string, you're writing out that pointer, not the data it points to.
thank you for this, I think I have to get another book for this part (file streams) as one I am using I don't think deals with this very well (besides fact is ancient ;) )
from what my course tutor told me you can't send string string, instead you should you char and then you use pointer to char with reinterpreted_cast to read and write.
At the moment that sounds wired.
Maybe I need to read chapter properly in more then one book/tutorial :)