Ich bin verwirrt, wenn ich ein Objekt in C++ in eine Binärdatei geschrieben habe. Als ich schrieb einen String in einer Datei, wie folgt aus:schreibe ein Objekt in eine Binärdatei in C++
//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();
Aber es schrieb etwas anderes (vielleicht ein Zeiger) auf die Datei anstatt die Zeichenfolge selbst.
Wenn ich ein Objekt einer Klasse (die ein String-Mitglied hat) schrieb, funktionierte es.
// 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;
}
Es gibt die richtigen Informationen aus.
Warum? Vielen Dank.
Ja, ich habe es. Ich verstehe, warum es nicht empfohlen wird, ein Objekt direkt in eine Datei zu schreiben, besonders wenn Sie nicht sicher sind, ob die Klasse ein POD-Typ ist. Vielen Dank. – lifeisamoive