MFC 文件I/O和串行化

1.枚举所有文件夹(递归)

void EnumerateFolders ()
{
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFile (_T ("*.*"), &fd);

    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                CString name = fd.cFileName;
                if (name != _T (".") && name != _T ("..")) {
                    TRACE (_T ("%s\n"), fd.cFileName);
                    ::SetCurrentDirectory (fd.cFileName);
                    EnumerateFolders ();
                    ::SetCurrentDirectory (_T (".."));
                }
            }
        } while (::FindNextFile (hFind, &fd));
        ::FindClose (hFind);
    }
}
//比如说枚举E:\svn文件夹,不过可能会导致栈溢出
::SetCurrentDirectory(_T("e:\\svn"));
EnumerateFolders();

 2.串行化类(版本控制http://www.vckbase.com/index.php/wv/1097

class MyLine:public CObject
{
    DECLARE_SERIAL(MyLine);
public:
    MyLine(){};
    MyLine(CPoint from,CPoint to){
        m_ptFrom=from;
        m_ptTo=to;
    }
    void Serialize(CArchive &ar);
protected:
    CPoint m_ptFrom;
    CPoint m_ptTo;
};

IMPLEMENT_SERIAL(MyLine,CObject,1);
void MyLine::Serialize(CArchive &ar){
    
    if(ar.IsLoading()){
        ar<<m_ptFrom<<m_ptTo;
    }else{
        ar>>m_ptFrom>>m_ptTo;
    }
}

 下面是串行化输入输出demo:

void CMainWindow::OnFileWrite()
{
    // TODO: 在此添加命令处理程序代码
    CFile file(_T("abc.txt"),CFile::modeCreate|CFile::modeWrite);
    CArchive ar(&file,CArchive::store);
    int i=10;
    float f=1.3f;
    char ch='c';
    CString str=_T("abc");
    ar<<i<<f<<ch<<str;
}


void CMainWindow::OnFileRead()
{
    // TODO: 在此添加命令处理程序代码
    CFile file(_T("abc.txt"),CFile::modeRead);
    CArchive ar(&file,CArchive::load);
    int i;
    float f;
    char ch;
    CString str;
    CString strResult;
    ar>>i>>f>>ch>>str;   //必须按顺序输出,也就是说存入的数据保持着原有的类型
    strResult.Format(_T("%d,%f,%c,%s"),i,f,ch,str);
    AfxMessageBox(strResult);
}

 

posted on 2014-06-13 16:53  上海—Michael  阅读(267)  评论(0编辑  收藏  举报