zoukankan      html  css  js  c++  java
  • 利用FindFirstFile和CreateDirectory函数实现多层目录的检测和创建

     
    //检测并创建多层目录
    //测试了 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;
    }


     

    友情提示: 写个博客对于我来说不容易,如果此文是我原创,烦请转载加个链接http://www.cnblogs.com/monotone/。谢谢。
  • 相关阅读:
    Python面向对象
    Python
    05、Win7上openSSH的安装与配置
    关于C++中的类型转换
    正确地使用智能指针
    为多态基类声明多态析构函数
    透视校正插值(Perspective-Correct Interpolation)
    保持const和non-const函数代码的一致
    第二章 信息的表示和处理
    《Linux内核分析》课程总结
  • 原文地址:https://www.cnblogs.com/monotone/p/2770603.html
Copyright © 2011-2022 走看看