利用FindFirstFile和CreateDirectory函数实现多层目录的检测和创建

来源:互联网 发布:急需网络兼职工作 编辑:程序博客网 时间:2024/05/20 12:24
 
//检测并创建多层目录//测试了 strPath = "C:\\Documents and Settings\\aa","11\\22\\33\\44","11\\22\\33\\44\\"情况。
BOOL MakeDirecory(CString strPath){//判断是不是以'\'或者'/'结尾,若是则去除int nLength = strPath.GetLength();while('\\' == strPath.GetAt(nLength-1) || '/' == strPath.GetAt(nLength-1)){strPath.Delete(nLength-1);//Delete的返回值是删除前的字符串长度。。nLength = strPath.GetLength();ASSERT(nLength == strPath.GetLength());}//如果有'\'全部转换成'/'if(-1 != strPath.Find('\\') ){strPath.Replace("\\","/");}CString strPathTemp = strPath;//找出当前已经存在的目录int nIndex = 0;while( INVALID_HANDLE_VALUE == FindFirstFile(strPathTemp,NULL) ){//除去该层目录nIndex = strPathTemp.ReverseFind('/');if(-1 != nIndex){strPathTemp.Delete(nIndex,nLength-nIndex);nLength = strPathTemp.GetLength();if( ':' == strPathTemp.GetAt(nIndex-1) )//已经到达盘符了break;}else//到达最根层目录了{strPathTemp.Empty();nLength = 0;break;}}ASSERT(nLength == strPathTemp.GetLength() );//从找到的这个已经存在的目录开始往后创建文件夹while(nLength != strPath.GetLength() ){strPathTemp.Empty();nIndex = strPath.Find("/",nLength+1);if(-1 == nIndex)//检查是否已经是最后一个目录了{strPathTemp = strPath;nLength = strPath.GetLength();}else{strPathTemp = strPath.Left(nIndex);nLength = strPathTemp.GetLength();}ASSERT(nLength == strPathTemp.GetLength());if(!CreateDirectory(strPathTemp,NULL)){CString strError = _T("");strError.Format(_T("创建目录%s失败。",strPathTemp));MessageBox(NULL,strError,_T("错误"),MB_OK | MB_ICONERROR );return FALSE;}}return TRUE;}

 
原创粉丝点击