16,466
社区成员
发帖
与我相关
我的任务
分享
CBook book1( "wo ca","wo ca", "hello" );
CBook book2( "world", "-------", "hello" );
int nCount = 2;
CFile FileStore( _T( "E:\\9876.dat" ), CFile::modeWrite|CFile::modeCreate );
CArchive arStore( &FileStore, CArchive::store );
CBook *PBookStore[2] = { &book1, &book2 };
arStore << nCount;
for( int i = 0; i < nCount; ++i )
{
arStore << PBookStore[i] ;
}
//FileStore.Close();
//这是main 如果这里不 Close 就没事 可以写入
//如果加上 FileStore.Close()就会down 而且是这句结束之后 在 main 后面反括号那里 down
//然后跳转到
void CFile::Write(const void* lpBuf, UINT nCount)
{
ASSERT_VALID(this);
ASSERT(m_hFile != INVALID_HANDLE_VALUE);//就是这里断言失败
//
Book.h
#include <afxwin.h>
class CBook : public CObject
{
DECLARE_SERIAL(CBook)
public:
CString m_strName;
CString m_strAuthor;
CString m_strPress;
public:
CBook()
{
// 要使CBook对象实现序列化,必须定义默认构造函数
}
CBook(CString strName, CString strAuthor, CString strPress)
{
m_strName = strName; // 书名
m_strAuthor = strAuthor; // 作者
m_strPress = strPress; // 出版社
}
void Serialize(CArchive &); // 重载基类的Serialize函数
};
Book.cpp
#include "Book.h"
IMPLEMENT_SERIAL(CBook, CObject, 1)
void CBook::Serialize(CArchive &ar)
{
CObject::Serialize(ar);
if(ar.IsStoring())
{
ar << m_strName << m_strAuthor << m_strPress;
}
else
{
ar >> m_strName >> m_strAuthor >> m_strPress;
}
}
主程序:
CBook book1("Programming Windows", "Charles Petzold", "Microsoft Press");
CBook book2("Programming Windows with MFC", "Jeff Prosise", "Microsoft Press");
int nCount = 2;
// 序列化
CFile fileStore(_T("mybooks.dat"), CFile::modeWrite | CFile::modeCreate);
CArchive arStore(&fileStore, CArchive::store);
CBook* PBooksStore[2] = { &book1, &book2 };
arStore << nCount;
for (int i=0; i<nCount; ++i)
{
arStore << pBooksStore[i];
}
fileStore.Close();
// 这就网上一个示例程序