I get confused when I wrote an object to a binary file in C++. When I wrote a string to a file, like this:
//write a string to a binary file
ofstream ofs("Test.txt", ofstream::binary | ofstream::app);
string foo = "This is a long .... string."
ofs.write((char*)&foo, sizeof(foo));
ofs.close();
But it wrote something else(maybe a pointer) to the file rather than the string itself.
When I wrote an object of a class(which has a string member), it worked.
// a simple class
class Person {
public:
Person() = default;
Person(std::string name, int old) : fullName(name), age(old) {}
std::string getName() const { return this->fullName; }
int getAge() const { return this->ID; }
private:
string fullName;
int age;
};
int main()
{
std::ofstream ofs("Test.txt", std::ofstream::binary | std::ofstream::app);
Person p1("lifeisamoive", 1234);
ofs.write((char*)&p1, sizeof(Person));
ofs.close();
Person *p2 = new Person();
std::ifstream ifs("Test.txt", std::ifstream::binary);
//output the right information
while(ifs.read((char*)p2, sizeof(Person)))
std::cout << p2->getName() << " " << p2->getAge() << std::endl;
else
std::cout << "Fail" << std::endl;
ifs.close();
return 0;
}
It output the right information.
Why? Thanks.