Serializing ASCII Data

Home
Serializing ASCII Data
Modeless child dialog
Modeless sibling dialog
The drag source
The MFC drop target
The TBTextTarget class
VC6 flat toolbar support

 

 

Serializing Data to / from an ASCII-file

The CArchive object has methods called ReadString and WriteString. ReadString reads a complete line stopping at, but not including the carriagereturn/linefeed pair. WriteString puts the specified string value into the archive, but without the CR/LF. ReadString detects eof by a returning zero which can be used as while-conditional.

This is from the sample application, step zero:

void CInterfaceDoc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        for (int i=0; i<m_String.GetUpperBound(); i++)
            ar.WriteString(m_Strings[i]+"\n");
    }
    else
    {
        m_Strings.RemoveAll();

        int idx=0;
        CString t;

        TRY
        {
            while(ar.ReadString(t))
            {
                m_Strings.SetAtGrow(idx, t);
                idx++;
            }
        }
        CATCH(CArchiveException, e)
        {
#ifdef _DEBUG
            TCHAR szCause[255];
            CString strFormatted;
            e->GetErrorMessage(szCause, 255);
            // in real life, it's probably more
            // appropriate to read this from
            // a string resource so it would be easy to
            // localize
            strFormatted = _T("CArciveException: ");
            strFormatted += szCause;
            AfxMessageBox(strFormatted); 
#endif //_DEBUG
        }
        END_CATCH;

        UpdateAllViews(NULL);
    }
}