界面上有两个button,点OnBnClickedButton11,运行OnBnClickedButton11()函数,写文件,但是总是抛出异常,
void CWindowsTestDlg::OnBnClickedButton11()
{
    CFile file;
    CFileException fe;
    //以读方式打开文件
    if(!file.Open(_T("f:\\123.dat"),CFile::modeCreate | CFile::modeWrite,&fe))
    {
            fe.ReportError();
            return;
    }
    
    //构建CArchive 对象
int i = 1234;
float dw = 4000.6789;
    CArchive ar(&file,CArchive::load);
    ar << i <<dw ;
    ar.Flush();
    //写完毕,关闭文件流
    ar.Close();
    file.Close();
}
点OnBnClickedButton12,运行OnBnClickedButton12()函数,希望序列化读取文件,也抛出异常。
void CWindowsTestDlg::OnBnClickedButton12()
{
 //示例代码2
    //定义文件对象和文件异常对象
    CFile file;
    CFileException fe;
    //以读方式打开文件
    if(!file.Open(_T("f:\\123.dat"),CFile::modeRead,&fe))
    {
        fe.ReportError();
        return;
    }
    //构建CArchive 对象
    CArchive ar(&file,CArchive::load);
int i = 0;
float dw = 0.0;
    ar >> i>> dw;
    ar.Flush();
    //读完毕,关闭文件流
    ar.Close();
    file.Close();
}请有经验的帮助验证一下上面的代码,问题在什么地方。

解决方案 »

  1.   

    发现一个问题:OnBnClickedButton11()函数为写文件,该函数中CArchive ar(&file,CArchive::load);不对,应该为CArchive ar(&file,CArchive::store);
    我用序列化读写文件没有用CFileException。我的方法如下,供参考:
    BOOL MyClass::SaveFile()
    {
       int i=10;
       float dw=10.234;
       CFile f;
       if(f.Open(_T("f:\\123.dat"),CFile::modeWrite|CFile::modeCreate))
       {
            CArchive ar(&f,CArchive::stroe);
            ar<<i<<dw;
            f.Flush();
        }
        else
            return FALSE;
        f.Close();
        return TRUE;
    }
    BOOL MyClass::LoadFile()
    {
       int i=0;
       float dw=0.0;
       CFile f;
       if(f.Open(_T("f:\\123.dat"),CFile::modeRead))
       {
            //文件中没有数据
            if(f.GetLength()==0)
               return FALSE;
            CArchive ar(&f,CArchive::load);
            ar>>i>>dw;
            
        }
        else
            return FALSE;
        f.Close();
        return TRUE;
    }
    我一直都是这样用的,没有什么问题。
      

  2.   

    你第一个函数明明是创建新文件,怎么会用CArchive ar(&file,CArchive::load); 呢?应该用CArchive::store啊。
      

  3.   

    而且ar < < i < <dw ; 是进行存储的操作。看来你是写错了。load改成store,第一个函数应该就OK了。
      

  4.   

    CArchive::load   Loads data from the archive. Requires only CFile read permission.
    CArchive::store   Saves data to the archive. Requires CFile write permission.
    CArchive::bNoFlushOnDelete   Prevents the archive from automatically calling Flush when the archive destructor is called. If you set this flag, you are responsible for explicitly calling Close before the destructor is called. If you do not, your data will be corrupted. 
      

  5.   

    改为CArchive::store,调试是OK的。