MFC递归复制文件夹

上一篇中使用CFileFind实现了递归删除文件夹。这一篇继续使用CFileFind类实现文件夹的复制。

文件title\name\path的区分

开始之前,先讲一下文件最常用的三个属性title、name、path的区分。比如如下代码

CFile file("C:/note/file.txt",CFile::modeRead);

CString szPath = file.GetFilePath();
CString szName = file.GetFileName();
CString szTitle = file.GetFileTitle();

AfxMessageBox("Path : "+szPath);
AfxMessageBox("Name: "+szName);
AfxMessageBox("Title: "+szTitle);

请问输出的结果是什么?

name和path很好理解,前者是文件名,后者是文件路径。那么name和title有何区别?
如果你文件夹选项中,设置的是显示文件后缀名,程序结果是

Path: C:/note/file.txtAfxMessageBox("Path : "+szPath);
Name: file.txt
Title: file.txt

如果你文件夹选项中,设置的是隐藏文件后缀名,程序结果是

Path: C:/note/file.txtAfxMessageBox("Path : "+szPath);
Name: file.txt
Title: file

可以看出区别了。Path是全路径+文件名,包括后缀名;name是文件名,包括后缀名;title是文件显示的名字,如果系统显示了后缀名,则其包括后缀名,否则不包括。

递归复制文件夹

MFC 中提供了一系列文件夹管理函数,却没有复制、移动文件夹这种基本操作函数

directory_manager

不过,按照上篇中递归的思想,仍旧可以实现复制文件夹,无论其非空与否。

实现代码

void myCopyDirectory(CString source, CString target)
{
    CreateDirectory(target,NULL); //创建目标文件夹
    //AfxMessageBox("创建文件夹"+target);
    CFileFind finder;
    CString path;
    path.Format("%s/*.*",source);
    AfxMessageBox(path);
    bool bWorking = finder.FindFile(path);
    while(bWorking){
        bWorking = finder.FindNextFile();
        AfxMessageBox(finder.GetFileName());
        if(finder.IsDirectory() && !finder.IsDots()){ //是文件夹 而且 名称不含 . 或 ..
            //递归创建文件夹+"/"+finder.GetFileName()
            myCopyDirectory(finder.GetFilePath(),target+"/"+finder.GetFileName());
        }
        else{ //是文件 则直接复制
            //AfxMessageBox("复制文件"+finder.GetFilePath());//+finder.GetFileName()
            CopyFile(finder.GetFilePath(),target+"/"+finder.GetFileName(),FALSE);
        }
    }
}

使用CFindFile对象,判断源文件夹的子项是文件还是文件夹,如果是文件,则直接copy过去,如果是文件夹则递归复制该子文件夹。

如果要实现递归移动,思路相同,区别在于复制过程中复制完一项就要删除源文件夹中相应的项。或者更简单

递归移动=递归复制+递归删除
——————————————————————–

该文2010-08-03 13:00首发于我的CSDN专栏。有改动。

作者:JarvisChu
原文链接:MFC递归复制文件夹
版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

发表评论