如何在MFC中使用相同的序列化方法将信息保存在两个文件中

时间:2019-02-27 08:54:58

标签: mfc

我试图单击下面所示的按钮后将信息保存在2个文件中,但是它正在创建大小为0KB的文件2.正在创建两个文件,但是file1有内容,但是file2没有内容它的大小为0kB。请让我知道我在做什么错误,也请让我知道是否有更好的过程使用MFC中的serialize方法将信息存储在两个文件中:

   void CMFCserializedemoDlg::OnBnClickedButton2()
    {
        // TODO: Add your control notification handler code here
        UpdateData(TRUE);
        CEmployee employee;
        CFile file;
        file.Open(L"EmployeeInfo.hse", CFile::modeCreate | CFile::modeWrite);
        CArchive ar(&file, CArchive::store);
        employee.empID = m_EmployeeId;
        employee.empName = m_EmployeeName;
        employee.age = m_EmployeeAge;
        employee.Serialize(ar);
        ar.Close();
        CFile file2;
        file2.Open(L"EmployeeInfo1.hse", CFile::modeCreate | CFile::modeWrite);
        CArchive ar1(&file, CArchive::store);
        employee.empID = m_EmployeeId;
        employee.empName = m_EmployeeName;
        employee.age = m_EmployeeAge;
        employee.Serialize(ar1);
        ar1.Close();
    }
    void CEmployee::Serialize(CArchive& ar) {
        CObject::Serialize(ar);

        if (ar.IsStoring())
            ar << empID << empName << age;
        else
            ar >> empID >> empName >> age;
    }
//
class CEmployee : public CObject
{
public:
    int empID;
    CString empName;
    int age;
    CEmployee(void);
    ~CEmployee(void);
private:

public:
    void Serialize(CArchive& ar);
    DECLARE_SERIAL(CEmployee);
};

1 个答案:

答案 0 :(得分:1)

您有:

CFile file2;
file2.Open(L"EmployeeInfo1.hse", CFile::modeCreate | CFile::modeWrite);
CArchive ar1(&file, CArchive::store);

请注意,您正在将file而不是file2的地址传递到ar1变量中。应该是:

CArchive ar1(&file2, CArchive::store);

那是原因。