简体   繁体   中英

How to check if CArchive is valid

I use the MFC-Serialize function to read / store some values. If i catch the wrong filename, the Application crash.

I see that is usually because, it try to read beyound the end of the CArchive (file) and returns some unitialized values.

How can I check if CArchive is still valid after extraction? or the end of the CArchive is reached. Similiar with ifstrem if (is) is >> tmp.

std::vector<double> m_vecPoint;

void CTestDoc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {   // Store
        int AnzT = m_vecPoint.size();
        ar << AnzT;

        for (int i = 0; i < AnzT *&& *ar.isGood()*/; i++)
        {
            ar << m_vecPoint.at(i);
        }
    }

    else
    {   // Read
        int AnzT(0);
        ar >> AnzT;

        for (int i = 0; i < AnzT; i++)
        {
            double pt;
            ar >> pt;
            m_vecPoint.push_back(pt);  // crash occurs here (how to validate pt?)               }
    }
}

To avoid floating point exceptions while extracting from CArchive (the programm crashes, despite try, catch handler). I avoid this now by converting floats/doubles in CString and use ar.Write/ReadString(str) inside my >> and << operators.

inline Archive& operator<<(CArchive& ar, const CMyPoint& val)
{
    tostringstream os;
    const TCHAR kSep = _T(' ');

    os << val.m_fTemperatur1 << kSep;
    os << val.m_fTemperatur2 << kSep;

    ar.WriteString(os.str().c_str());
    return ar;
}

inline CArchive& operator >> (CArchive& ar, CMyPoint& val)
{
    CString str;
    ar.ReadString(str);

    tistringstream is((LPCTSTR)str);
    tstring sep;
    is >> val.m_fT1 >> sep;
    is >> val.m_fT2 >> sep;

    return ar;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM