# MFC浅析(8) CArchive 原理

908人阅读 评论(0)

MFC 提供CArchive类实现数据的缓冲区读写，同时定义了类对象的存储与读取方案。

CArchive使用了缓冲区，即一段内存空间作为临时数据存储地，对CArchive的读写都先依次排列到此缓冲区，当缓冲区满或用户要求时，将此段整理后的数据读写到指定的存储煤质。

2.内部数据

3.基本数据读写

 //操作符定义捕:

//插入操作
CArchive& operator<<(BYTE by);
CArchive& operator<<(WORD w);
CArchive& operator<<(LONG l);
CArchive& operator<<(DWORD dw);
CArchive& operator<<(float f);
CArchive& operator<<(double d);
CArchive& operator<<(int i);
CArchive& operator<<(short w);
CArchive& operator<<(char ch);
CArchive& operator<<(unsigned u);
//提取操作
CArchive& operator>>(BYTE& by);
CArchive& operator>>(WORD& w);
CArchive& operator>>(DWORD& dw);
CArchive& operator>>(LONG& l);
CArchive& operator>>(float& f);
CArchive& operator>>(double& d);
CArchive& operator>>(int& i);
CArchive& operator>>(short& w);
CArchive& operator>>(char& ch);
CArchive& operator>>(unsigned& u);


CArchive& CArchive::operator<<(DWORD dw)
{
if (m_lpBufCur + sizeof(DWORD) > m_lpBufMax) //缓冲区空间不够
Flush();  //缓冲区内容提交到实际存储煤质。
if (!(m_nMode & bNoByteSwap))
_AfxByteSwap(dw, m_lpBufCur);  //处理字节顺序
else
*(DWORD*)m_lpBufCur = dw;      //添入缓冲区
m_lpBufCur += sizeof(DWORD);     //移动当前指针
return *this;
}


CArchive& CArchive::operator>>(DWORD& dw)
{
if (m_lpBufCur + sizeof(DWORD) > m_lpBufMax) //缓冲区要读完了
FillBuffer(sizeof(DWORD) - (UINT)(m_lpBufMax - m_lpBufCur));  //重新读入内容到缓冲区
dw = *(DWORD*)m_lpBufCur;  //读取双字
m_lpBufCur += sizeof(DWORD); //移动当前位置指针
if (!(m_nMode & bNoByteSwap))
_AfxByteSwap(dw, (BYTE*)&dw);  //处理字节顺序
return *this;
}


4.缓冲区的更新

void CArchive::Flush()
{
ASSERT_VALID(m_pFile);
ASSERT(m_bDirectBuffer || m_lpBufStart != NULL);
ASSERT(m_bDirectBuffer || m_lpBufCur != NULL);
ASSERT(m_lpBufStart == NULL ||
ASSERT(m_lpBufCur == NULL ||
{
// unget the characters in the buffer, seek back unused amount
if (m_lpBufMax != m_lpBufCur)
m_pFile-> Seek(-(m_lpBufMax - m_lpBufCur), CFile::current);
m_lpBufCur = m_lpBufMax;    // 指向尾
}
else   //写模式
{
if (!m_bDirectBuffer)
{
// 内容写入到文件
if (m_lpBufCur != m_lpBufStart)
m_pFile-> Write(m_lpBufStart, m_lpBufCur - m_lpBufStart);
}
else
{
//如果是直接针对内存区域的的(例如CMemFile中) (只需移动相关指针，指向新的一块内存)
if (m_lpBufCur != m_lpBufStart)
m_pFile-> GetBufferPtr(CFile::bufferCommit, m_lpBufCur - m_lpBufStart);
// get next buffer
VERIFY(m_pFile-> GetBufferPtr(CFile::bufferWrite, m_nBufSize,
(void**)&m_lpBufStart, (void**)&m_lpBufMax) == (UINT)m_nBufSize);
ASSERT((UINT)m_nBufSize == (UINT)(m_lpBufMax - m_lpBufStart));
}
m_lpBufCur = m_lpBufStart; //指向缓冲区首
}
}


void CArchive::FillBuffer(UINT nBytesNeeded)
{
ASSERT_VALID(m_pFile);
ASSERT(m_bDirectBuffer || m_lpBufStart != NULL);
ASSERT(m_bDirectBuffer || m_lpBufCur != NULL);
ASSERT(nBytesNeeded > 0);
ASSERT(nBytesNeeded <= (UINT)m_nBufSize);
ASSERT(m_lpBufStart == NULL ||
ASSERT(m_lpBufCur == NULL ||
UINT nUnused = m_lpBufMax - m_lpBufCur;
ULONG nTotalNeeded = ((ULONG)nBytesNeeded) + nUnused;
// 从文件中读取
if (!m_bDirectBuffer)
{
ASSERT(m_lpBufCur != NULL);
ASSERT(m_lpBufStart != NULL);
ASSERT(m_lpBufMax != NULL);
if (m_lpBufCur > m_lpBufStart)
{
//保留剩余的尚未处理的部分，将它们移动到头
if ((int)nUnused > 0)
{
memmove(m_lpBufStart, m_lpBufCur, nUnused);
m_lpBufCur = m_lpBufStart;
m_lpBufMax = m_lpBufStart + nUnused;
}
// read to satisfy nBytesNeeded or nLeft if possible
UINT nLeft = m_nBufSize-nUnused;
UINT nBytes;
BYTE* lpTemp = m_lpBufStart + nUnused;
do
{
lpTemp = lpTemp + nBytes;
nLeft -= nBytes;
}
while (nBytes > 0 && nLeft > 0 && nRead < nBytesNeeded);
m_lpBufCur = m_lpBufStart;
}
}
else
{
// 如果是针对内存区域(CMemFile),移动相关指针，指向新的一块内存
if (nUnused != 0)
m_pFile-> Seek(-(LONG)nUnused, CFile::current);
UINT nActual = m_pFile-> GetBufferPtr(CFile::bufferRead, m_nBufSize,
(void**)&m_lpBufStart, (void**)&m_lpBufMax);
ASSERT(nActual == (UINT)(m_lpBufMax - m_lpBufStart));
m_lpBufCur = m_lpBufStart;
}
// not enough data to fill request?
if ((ULONG)(m_lpBufMax - m_lpBufCur) < nTotalNeeded)
AfxThrowArchiveException(CArchiveException::endOfFile);
}


5.指定长度数据段落的读写

UINT Read(void* lpBuf, UINT nMax); 读取长度为nMax的数据

void Write(const void* lpBuf, UINT nMax); 写入指定长度nMax的数据

(说明:缓冲区读写的主要目的是将零散的数据以缓冲区大小为尺度来处理。对于大型数据，其中间的部分，不是零散的数据，使用缓冲区已经没有意思，故直接读写)

①读取

UINT CArchive::Read(void* lpBuf, UINT nMax)
{
ASSERT_VALID(m_pFile);
if (nMax == 0)
return 0;
UINT nMaxTemp = nMax;  //还需要读入的长度，读入一部分，就减相应数值，直到此数值变为零

//处理当前缓冲区中剩余部分。
//如果要求读入字节小于缓冲区中剩余部分,则第一部分为要求读入的字节数，
//否则读入全部剩余部分
UINT nTemp = min(nMaxTemp, (UINT)(m_lpBufMax - m_lpBufCur));
memcpy(lpBuf, m_lpBufCur, nTemp);
m_lpBufCur += nTemp;
lpBuf = (BYTE*)lpBuf + nTemp; //移动读出内容所在区域的指针
nMaxTemp -= nTemp;
//当前缓冲区中剩余部分不够要求读入的长度。
//还有字节需要读，则需要根据需要执行若干次填充缓冲区，读出，直到读出指定字节。
if (nMaxTemp != 0)
{
//计算出去除尾数部分的字节大小(整数个缓冲区大小)
//对于这些部分，字节从文件对象中读出，放到输出缓冲区
nTemp = nMaxTemp - (nMaxTemp % m_nBufSize);
UINT nLeft = nTemp;
UINT nBytes;
do
{
nBytes = m_pFile-> Read(lpBuf, nLeft); //要求读入此整数缓冲区部分大小
lpBuf = (BYTE*)lpBuf + nBytes;
nLeft -= nBytes;
}
while ((nBytes > 0) && (nLeft > 0)); 知道读入了预定大小，或到达文件尾
if (nRead == nTemp) //读入的字节等于读入的整数倍部分  该读最后的余数部分了
{
// 建立装有此最后余数部分的内容的CArchive的工作缓冲区。
if (!m_bDirectBuffer)
{
UINT nLeft = max(nMaxTemp, (UINT)m_nBufSize);
UINT nBytes;
BYTE* lpTemp = m_lpBufStart;
do
{
nBytes = m_pFile-> Read(lpTemp, nLeft);  //从文件中读入到CArchive缓冲区
lpTemp = lpTemp + nBytes;
nLeft -= nBytes;
}
while ((nBytes > 0) && (nLeft > 0) && nRead < nMaxTemp);
m_lpBufCur = m_lpBufStart;
}
else
{
(void**)&m_lpBufStart, (void**)&m_lpBufMax);
m_lpBufCur = m_lpBufStart;
}
//读出此剩余部分到输出
nTemp = min(nMaxTemp, (UINT)(m_lpBufMax - m_lpBufCur));
memcpy(lpBuf, m_lpBufCur, nTemp);
m_lpBufCur += nTemp;
nMaxTemp -= nTemp;
}

}
return nMax - nMaxTemp;
}


②保存,写入

void CArchive::Write(const void* lpBuf, UINT nMax)
{
if (nMax == 0)
return;

//读入可能的部分到缓冲区当前的剩余部分
UINT nTemp = min(nMax, (UINT)(m_lpBufMax - m_lpBufCur));
memcpy(m_lpBufCur, lpBuf, nTemp);
m_lpBufCur += nTemp;
lpBuf = (BYTE*)lpBuf + nTemp;
nMax -= nTemp;
if (nMax > 0)  //还有未写入的部分
{
Flush();    //将当前缓冲区写入到存储煤质
//计算出整数倍缓冲区大小的字节数
nTemp = nMax - (nMax % m_nBufSize);
m_pFile-> Write(lpBuf, nTemp);  //直接写到文件
lpBuf = (BYTE*)lpBuf + nTemp;
nMax -= nTemp;

//剩余部分添加到缓冲区
if (m_bDirectBuffer)
{
// sync up direct mode buffer to new file position
VERIFY(m_pFile-> GetBufferPtr(CFile::bufferWrite, m_nBufSize,
(void**)&m_lpBufStart, (void**)&m_lpBufMax) == (UINT)m_nBufSize);
ASSERT((UINT)m_nBufSize == (UINT)(m_lpBufMax - m_lpBufStart));
m_lpBufCur = m_lpBufStart;
}
// copy remaining to active buffer
ASSERT(nMax < (UINT)m_nBufSize);
ASSERT(m_lpBufCur == m_lpBufStart);
memcpy(m_lpBufCur, lpBuf, nMax);
m_lpBufCur += nMax;
}
}


6.字符串的读写

void CArchive::WriteString(LPCTSTR lpsz)
{
ASSERT(AfxIsValidString(lpsz));
Write(lpsz, lstrlen(lpsz) * sizeof(TCHAR));  //调用Write，将字符串对应的一段数据写入
}


LPTSTR CArchive::ReadString(LPTSTR lpsz, UINT nMax)
{
// if nMax is negative (such a large number doesn't make sense given today's
// 2gb address space), then assume it to mean "keep the newline".
int nStop = (int)nMax < 0 ? -(int)nMax : (int)nMax;
_TUCHAR ch;
TRY
{
{
*this >> ch;  //读出一个字节
// stop and end-of-line (trailing '/n' is ignored)  遇换行—回车
if (ch == '/n' || ch == '/r')
{
if (ch == '/r')
*this >> ch;
// store the newline when called with negative nMax
if ((int)nMax != nStop)
break;
}
}
}
CATCH(CArchiveException, e)
{
if (e-> m_cause == CArchiveException::endOfFile)
{
DELETE_EXCEPTION(e);
return NULL;
}
else
{
THROW_LAST();
}
}
END_CATCH
return lpsz;
}

ReadString到CString对象,可以多行字符
{
rString = &afxChNil;    // empty string without deallocating
const int nMaxSize = 128;
LPTSTR lpsz = rString.GetBuffer(nMaxSize);
LPTSTR lpszResult;
int nLen;
for (;;)
{
lpszResult = ReadString(lpsz, (UINT)-nMaxSize); // store the newline
rString.ReleaseBuffer();
// if string is read completely or EOF
if (lpszResult == NULL ||
(nLen = lstrlen(lpsz)) < nMaxSize ||
lpsz[nLen-1] == '/n')
{
break;
}
nLen = rString.GetLength();
lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen;
}
// remove '/n' from end of string if present
lpsz = rString.GetBuffer(0);
nLen = rString.GetLength();
if (nLen != 0 && lpsz[nLen-1] == '/n')
rString.GetBufferSetLength(nLen-1);
return lpszResult != NULL;
}


②使用CString对象的"<<"与">>"符读写字符串

CString定义了输入输出符,可以象基本类型的数据一样使用CArchive

friend CArchive& AFXAPI operator<<(CArchive& ar, const CString& string);
friend CArchive& AFXAPI operator>>(CArchive& ar, CString& string);

// CString serialization code
// String format:
//      UNICODE strings are always prefixed by 0xff, 0xfffe
//      if < 0xff chars: len:BYTE, TCHAR chars
//      if >= 0xff characters: 0xff, len:WORD, TCHAR chars
//      if >= 0xfffe characters: 0xff, 0xffff, len:DWORD, TCHARs
CArchive& AFXAPI operator<<(CArchive& ar, const CString& string)
{
// special signature to recognize unicode strings
#ifdef _UNICODE
ar << (BYTE)0xff;
ar << (WORD)0xfffe;
#endif
if (string.GetData()-> nDataLength < 255)
{
ar << (BYTE)string.GetData()-> nDataLength;
}
else if (string.GetData()-> nDataLength < 0xfffe)
{
ar << (BYTE)0xff;
ar << (WORD)string.GetData()-> nDataLength;
}
else
{
ar << (BYTE)0xff;
ar << (WORD)0xffff;
ar << (DWORD)string.GetData()-> nDataLength;
}
ar.Write(string.m_pchData, string.GetData()-> nDataLength*sizeof(TCHAR));
return ar;
}
// return string length or -1 if UNICODE string is found in the archive
{
DWORD nNewLen;
// attempt BYTE length first
BYTE bLen;
ar >> bLen;
if (bLen < 0xff)
return bLen;
// attempt WORD length
WORD wLen;
ar >> wLen;
if (wLen == 0xfffe)
{
// UNICODE string prefix (length will follow)
return (UINT)-1;
}
else if (wLen == 0xffff)
{
ar >> nNewLen;
return (UINT)nNewLen;
}
else
return wLen;
}
CArchive& AFXAPI operator>>(CArchive& ar, CString& string)
{
#ifdef _UNICODE
int nConvert = 1;   // if we get ANSI, convert
#else
int nConvert = 0;   // if we get UNICODE, convert
#endif
if (nNewLen == (UINT)-1)
{
nConvert = 1 - nConvert;
ASSERT(nNewLen != -1);
}
// set length of string to new length
UINT nByteLen = nNewLen;
#ifdef _UNICODE
string.GetBufferSetLength((int)nNewLen);
nByteLen += nByteLen * (1 - nConvert);  // bytes to read
#else
nByteLen += nByteLen * nConvert;    // bytes to read
if (nNewLen == 0)
string.GetBufferSetLength(0);
else
string.GetBufferSetLength((int)nByteLen+nConvert);
#endif
if (nNewLen != 0)
{
ASSERT(nByteLen != 0);
AfxThrowArchiveException(CArchiveException::endOfFile);
// convert the data if as necessary
if (nConvert != 0)
{
#ifdef _UNICODE
CStringData* pOldData = string.GetData();
LPSTR lpsz = (LPSTR)string.m_pchData;
#else
CStringData* pOldData = string.GetData();
LPWSTR lpsz = (LPWSTR)string.m_pchData;
#endif
lpsz[nNewLen] = '/0';    // must be NUL terminated
string.Init();   // don't delete the old data
string = lpsz;   // convert with operator=(LPWCSTR)
CString::FreeData(pOldData);
}
}
return ar;
}


7.CObject派生对象的读写

MFC中多数类都从CObject类派生，CObject类与CArchive类有着良好的合作关系，能实现将对象序列化储存到文件或其他媒介中去，或者读取预先储存的对象，动态建立对象等功能。

①CObject定义了针对CArvhive的输入输出操作符,可以向其他基本数据类型一样使用"<<"、"<<"符号

CArchive& AFXAPI operator<<(CArchive& ar, const CObject* pOb)
{ ar.WriteObject(pOb); return ar; }
CArchive& AFXAPI operator>>(CArchive& ar, CObject*& pOb)
{ pOb = ar.ReadObject(NULL); return ar; }


//将对象写入到缓冲区
void CArchive::WriteObject(const CObject* pOb)
{
DWORD nObIndex;
// make sure m_pStoreMap is initialized
MapObject(NULL);
if (pOb == NULL)
{
// save out null tag to represent NULL pointer
*this << wNullTag;
}
else if ((nObIndex = (DWORD)(*m_pStoreMap)[(void*)pOb]) != 0)
// assumes initialized to 0 map
{
// save out index of already stored object
if (nObIndex < wBigObjectTag)
*this << (WORD)nObIndex;
else
{
*this << wBigObjectTag;
*this << nObIndex;
}
}
else
{
// write class of object first
CRuntimeClass* pClassRef = pOb-> GetRuntimeClass();
WriteClass(pClassRef);  //写入运行类信息
// enter in stored object table, checking for overflow
CheckCount();
(*m_pStoreMap)[(void*)pOb] = (void*)m_nMapCount++;
// 调用CObject的Serialize成员，按其中的代码写入类中数据。
((CObject*)pOb)-> Serialize(*this);
}
}


CObject* CArchive::ReadObject(const CRuntimeClass* pClassRefRequested)
{
// attempt to load next stream as CRuntimeClass
UINT nSchema;
DWORD obTag;
//先读入运行时类信息
CRuntimeClass* pClassRef = ReadClass(pClassRefRequested, &nSchema, &obTag);
CObject* pOb;
if (pClassRef == NULL)
{
{
// tag is too large for the number of objects read so far
m_strFileName);
}
if (pOb != NULL && pClassRefRequested != NULL &&
!pOb-> IsKindOf(pClassRefRequested))
{
// loaded an object but of the wrong class
m_strFileName);
}
}
else
{
// 建立对象
pOb = pClassRef-> CreateObject();
if (pOb == NULL)
AfxThrowMemoryException();
// Add to mapping array BEFORE de-serializing
CheckCount();
// Serialize the object with the schema number set in the archive
UINT nSchemaSave = m_nObjectSchema;
m_nObjectSchema = nSchema;
pOb-> Serialize(*this); //调用CObject的Serialize,按其中代码读入对象数据。
m_nObjectSchema = nSchemaSave;
ASSERT_VALID(pOb);
}
return pOb;
}


③运行时类信息的读写

void CArchive::WriteClass(const CRuntimeClass* pClassRef)
{
ASSERT(pClassRef != NULL);
ASSERT(IsStoring());    // proper direction
if (pClassRef-> m_wSchema == 0xFFFF)
{
TRACE1("Warning: Cannot call WriteClass/WriteObject for %hs./n",
pClassRef-> m_lpszClassName);
AfxThrowNotSupportedException();
}
// make sure m_pStoreMap is initialized
MapObject(NULL);
// write out class id of pOb, with high bit set to indicate
// new object follows
// ASSUME: initialized to 0 map
DWORD nClassIndex;
if ((nClassIndex = (DWORD)(*m_pStoreMap)[(void*)pClassRef]) != 0)
{
// previously seen class, write out the index tagged by high bit
if (nClassIndex < wBigObjectTag)
*this << (WORD)(wClassTag | nClassIndex);
else
{
*this << wBigObjectTag;
*this << (dwBigClassTag | nClassIndex);
}
}
else
{
// store new class
*this << wNewClassTag;
pClassRef-> Store(*this);
// store new class reference in map, checking for overflow
CheckCount();
(*m_pStoreMap)[(void*)pClassRef] = (void*)m_nMapCount++;
}
}


CRuntimeClass* CArchive::ReadClass(const CRuntimeClass* pClassRefRequested,
UINT* pSchema, DWORD* pObTag)
{
ASSERT(pClassRefRequested == NULL ||
if (pClassRefRequested != NULL && pClassRefRequested-> m_wSchema == 0xFFFF)
{
pClassRefRequested-> m_lpszClassName);
AfxThrowNotSupportedException();
}
// make sure m_pLoadArray is initialized
MapObject(NULL);
// read object tag - if prefixed by wBigObjectTag then DWORD tag follows
DWORD obTag;
WORD wTag;
*this >> wTag;
if (wTag == wBigObjectTag)
*this >> obTag;
else
obTag = ((wTag & wClassTag) << 16) | (wTag & ~wClassTag);
// check for object tag (throw exception if expecting class tag)
if (!(obTag & dwBigClassTag))
{
if (pObTag == NULL)
*pObTag = obTag;
return NULL;
}
CRuntimeClass* pClassRef;
UINT nSchema;
if (wTag == wNewClassTag)
{
// new object follows a new class id
if ((pClassRef = CRuntimeClass::Load(*this, &nSchema)) == NULL)
// check nSchema against the expected schema
if ((pClassRef-> m_wSchema & ~VERSIONABLE_SCHEMA) != nSchema)
{
if (!(pClassRef-> m_wSchema & VERSIONABLE_SCHEMA))
{
// schema doesn't match and not marked as VERSIONABLE_SCHEMA
m_strFileName);
}
else
{
// they differ -- store the schema for later retrieval
if (m_pSchemaMap == NULL)
m_pSchemaMap = new CMapPtrToPtr;
ASSERT_VALID(m_pSchemaMap);
m_pSchemaMap-> SetAt(pClassRef, (void*)nSchema);
}
}
CheckCount();
}
else
{
// existing class index in obTag followed by new object
DWORD nClassIndex = (obTag & ~dwBigClassTag);
if (nClassIndex == 0 || nClassIndex > (DWORD)m_pLoadArray-> GetUpperBound())
m_strFileName);
ASSERT(pClassRef != NULL);
// determine schema stored against objects of this type
void* pTemp;
BOOL bFound = FALSE;
nSchema = 0;
if (m_pSchemaMap != NULL)
{
bFound = m_pSchemaMap-> Lookup( pClassRef, pTemp );
if (bFound)
nSchema = (UINT)pTemp;
}
if (!bFound)
nSchema = pClassRef-> m_wSchema & ~VERSIONABLE_SCHEMA;
}
// check for correct derivation
if (pClassRefRequested != NULL &&
!pClassRef-> IsDerivedFrom(pClassRefRequested))
{
}
// store nSchema for later examination
if (pSchema != NULL)
*pSchema = nSchema;
else
m_nObjectSchema = nSchema;
// store obTag for later examination
if (pObTag != NULL)
*pObTag = obTag;
// return the resulting CRuntimeClass*
return pClassRef;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：189409次
• 积分：2911
• 等级：
• 排名：第12130名
• 原创：61篇
• 转载：80篇
• 译文：1篇
• 评论：21条
文章分类
评论排行
最新评论