Serialize: Appending to a file

I need to save the contents of my document on a file which already has data, this means I must append the data to a file.
How ever, on the document::Serialize function, I use something like this:

void CMyDoc::Serialize(CArchive& ar)
{
// Assume is storing here
    CFile *pFile= ar.GetFile();
    pFile->SeekToEnd();
    ...
    pEditView->SerializeRaw(ar);
}

But it doesn't work, the file is always overwritten... What's wrong???
LVL 2
trilloAsked:
Who is Participating?
 
RONSLOWConnect With a Mentor Commented:
The file is already deleted and recreated by the time you get to the serialize.
0
 
RONSLOWCommented:
Also, appending to a file saved with serialize (via CArchive) will not work (that easily), as you will end up writing the file header twice.
0
 
RONSLOWCommented:
What you could do is create a temporary CMyDoc object, serialize in from the file you wish to append to, apppend the info from the real CMyDoc object and then serialize out the combined file.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
trilloAuthor Commented:
Oh!... And can avoid using the Serialize function.... What if I used CFile directly... will it be the same?
0
 
RONSLOWCommented:
Actually, if you override the CMyDoc::GetFile so that, if opening for read, it also opens for append, then you should be ok.

eg.

CFile* CMyDoc::GetFile(LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError) {
  bool bWriting = CFile::modeCreate == (nOpenFlags & CFile::modeCreate)
  if (bWriting) {
    nOpenFlags |= CFile::modeNoTruncate;
  }
  CFile* pFile = CDocument::GetFile(lpszFileName,nOpenFlags,pError);
  if (bWriting && pFile) {
    pFile->SeekToEnd();
  }
  return pFile;
}

This should ensure that you are appending to the existing file all the time.
0
 
RONSLOWCommented:
oops that should have read

....if opening for WRITE, it also opens for append, then...
0
 
trilloAuthor Commented:
Thanks... Very Helpful
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.