c++serializationmfccarchive

Save application settings MFC CArchive way


I have several settings in app witch I want to be saved on changing it. there is check box:

void CL2HamsterDlg::OnBnClickedCheckAutoselect()
{
    CFile theFile( pFileName1,CFile::modeWrite );
    CArchive ar(&theFile, CArchive::store);
    if(c_Acheck.GetCheck()==BST_UNCHECKED)
        a = 0;
    else
        a = 1;
    ar << a;
    ar.Close();
    theFile.Close();
}

and combo box with save button (When pressing save saves combo content):

void CL2HamsterDlg::OnClickedButtonLoad()
{
    Value.GetWindowText(str);
    CFile theFile( pFileName1,CFile::modeWrite );
    CArchive ar(&theFile, CArchive::store);
    ar << Savename;
    ar.Close();
    theFile.Close();
}

on initialization app must load these settings and set it:

BOOL CL2HamsterDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    pFileName1 = "settings.dat";    
    theFile.Open( pFileName1,CFile::modeRead );
    CArchive ar(&theFile, CArchive::load);
    ar >> a;
    ar.Close();
    theFile.Close();
    if(a == 1)
        c_Acheck.SetCheck(BST_CHECKED);
    return TRUE;
}

but all the time when one or another setting changed the program overwrites file.

ps. I don't want use registry (because of cause portable)

my question is how I can write and read settings in serialization way?

what available alternatively ways to save program settings state? (please with example)


Solution

  • You need to write all settings to the archive every time, when something changed. Accordingly, load all settings from the archive file, when the program starts.