CSDN博客

img xierica

CMirrorFile - An undocumented MFC tale.

发表于2008/10/1 5:00:00  199人阅读

分类: MFC


Did you ever heard about CMirrorFile? No chance. Because its an undocumented MFC class. It’s also used for file operations. We can write, delete do anything to a file by using CMirrorFile. But if you wish you can rollback the changes at any point before committing. Seems interesting?


In CMirrorFile, you can open a file like CFile and you can do as may operations. All the changes will be committed only if you call CMirrorFile::Close(). If you want to rollback the changes, then call CMirrorFile::Abort(). See the code snippet. Its self explanatory.

#include "afxpriv.h"
...
CMirrorFile MirrorFile;
MirrorFile.Open( _T("C://Database.txt"),
CFile::modeCreate | CFile::modeReadWrite );

// Do as many operations as you want.
// Truncate current file.
MirrorFile.SetLength( 0 );

// Write the file content.
CString FileContent = _T("File modified by using CMirrorFile.");
MirrorFile.Write( (LPCTSTR)FileContent, FileContent.GetLength());

// Decide whether to abort or not.
bool bAbort = false;

if( bAbort )
{
// Abort the changes.
// The source file will be the same.
MirrorFile.Abort();
}
else
{
// Close and commit the changes.
MirrorFile.Close();
}


Actually when we open a file using CMirrorFile, Its really creating a temporary file. All the further changes that you apply is updated to the temporary file copy. When you call Close(), CMirrorFile, updates the temporary file copy, then replaces the master file with temporary file by using api - ReplaceFile(). When you call Abort(), CMirrorFile just deletes that temporary copy of file.

Cool! You can use CMirrorFile, if you want to do several operations without damaging the main file and can commit only if you need or else you are free to rollback at any point.


Targeted Audience - Intermediate.

阅读全文
0 0

相关文章推荐

img
取 消
img