C++: Read and write classes

C++: Read and write classes

本文关键字:write classes and Read C++      更新时间:2023-10-16
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class PERSON{
    string name, surname;
public:
    void set_name(string aname, string asurname){
        name = aname;
        surname = asurname;
    };
    void read(){
    }
    void output(){
     cout << name << " " << surname << "n";
    }
    void save(PERSON *x){
        ofstream file("test.bin", ios::out | ios::app | ios::binary);

        if(!file.is_open()){
                cout << "ERRORn";
        }else{
                file.write((char*)x, sizeof(*x));
                file.close();
        }
    }
};


/*
 * 
 * 
 * 
 */
int main(int argc, char** argv) {


    PERSON * person1 = new PERSON;
    PERSON * person2 = new PERSON;
    person1->set_name("Amon", "Raa");
    person1->save(oseba1);




    ifstream file2("test.bin", ios::in | ios::binary);
    if(!file2.is_open()){
        cout << "Errorn";
        return 0;
    }

    while(!file2.eof()){
        file2.read((char *)person2, sizeof(*person2));
        person2->output();
    }
    file2.close(); 

    return 0;

}

这是我的代码…我做错了什么?我想做的是每次保存一个类到二进制文件的末尾,然后读取所有条目…

但是每次我运行程序时,我只输出最后输入的名称

所以第一次运行它文件写入正确,输出正常然后我把名字改成别的东西,比如John Doe,我得到的输出是2乘以John Doe

请帮…我完全是初学者;(

例如,类的序列化包含在boost包中。

http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html

我不认为你真的想自己实现这些功能。

在c++中不能简单地写出类的二进制映像,特别是包含指针和非pod成员的类。一旦你在你的数据中有了间接,简单地写出一个内存映像是行不通的,因为仅仅写出类的内存映像不包括指向数据,而且为了让它工作,你必须把所有的数据,包括指向数据,加载到你保存它们时所在的内存位置。这可不容易(委婉点说)。

你有两个选择,一个是手动的,一个是使用第三方库:

1)你用一堆记帐信息分别写和读每个成员。这在你的情况下应该是可行的因为你真正需要加载和保存的只是两个字符串的内容和它们各自的长度

2)另一种选择—特别是当数据结构比您正在使用的数据结构更复杂时—是使用像boost::serialization这样的东西来为您完成繁重的工作。

必须使用PERSON类的指针数组。然后从二进制文件中读取并填充人员数组。

ifstream input("PERSON.std",ios::binary);
    input.seekg(0, ios::end);
    int count = input.tellg() / sizeof(PERSON);
    PERSON *persons = new PERSON[count];
    input.seekg(0, ios::beg);
    input.read((char*) persons, sizeof(PERSON)*count);
    cout << count << endl;
    for (int j = 0; j < count; j++)
    {
        cout << count << endl;
        cout <<persons[j].output() << "n";
    }
    cout << 'n';
    input.close();