遞歸建立、刪除目錄的幾個函數

遞歸建立目錄1:api

須要#include <shlwapi.h>,而且配置好shlwapi.ibapp

BOOL CreateDirTree( LPCTSTR lpPath )
{
    if( NULL == lpPath || _tcslen(lpPath)==0 )
    {
        return FALSE;
    }
 
    if( ::PathFileExists( lpPath) || ::PathIsRoot(lpPath) )
        return TRUE;
 
    TCHAR szParentpath[MAX_PATH] = _T("");
    ::lstrcpy( szParentpath, lpPath );
 
    ::PathRemoveBackslash( szParentpath );//去除路徑最後的反斜槓
    ::PathRemoveFileSpec( szParentpath );//將路徑末尾的文件名或文件夾和反斜槓去掉
 
    if(0 == _tcscmp(lpPath, szParentpath))
        return FALSE;
 
    assert(0 != _tcscmp(lpPath, szParentpath));
    if( CreateDirTree( szParentpath) )//遞歸建立直到上一層存在或是根目錄
    {
        return ::CreateDirectory(lpPath, NULL);
    }
    else
    {
        return FALSE;
    }
 
    return TRUE;
}

遞歸建立目錄2:函數

void __fastcall RecursiveDirectory(CString cstrDir) // 遞歸建立目錄
{
    if (cstrDir.GetLength() <= 3)//是根目錄,無需建立目錄
    {
        return;
    }
    if (cstrDir[cstrDir.GetLength()-1] == '\\')   // 將路徑改成目錄
    {
        cstrDir.Delete(cstrDir.GetLength()-1, 1);
    }
    // 修改文件屬性
    WIN32_FIND_DATA wfd;
    HANDLE hFind = FindFirstFile(cstrDir, &wfd); // 查找
    if (hFind != INVALID_HANDLE_VALUE)
    {
        FindClose(hFind);
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            return;
    }
    // 建立當前目錄的地目錄失敗
    if (CreateDirectory(cstrDir,NULL) == false)
    {// 退到上一級目錄
        CString wstrNewDir = cstrDir;
        int n = wstrNewDir.ReverseFind('\\');
        wstrNewDir = cstrDir.Left(n);
        
        // 遞歸進入
        RecursiveDirectory(wstrNewDir);  // 遞歸本函數,再建立目錄
        // 遞歸退出後建立以前失敗的目錄
        CreateDirectory(cstrDir,NULL);  // 遞歸返回,在存在的目錄上再建目錄
    }// 多級目錄建立成功
}

遞歸建立目錄3:ui

BOOL RecursiveDirectory(wstring wstrDir)
{
    if (wstrDir.length() <= 3)
    {
        return FALSE;
    }
    if (wstrDir[wstrDir.length() - 1] == '\\')
    {
        wstrDir.erase(wstrDir.end() - 1);
    }
 
    if (PathFileExists(wstrDir.c_str()))
        return TRUE;
 
    if (CreateDirectory(wstrDir.c_str(), NULL) == false)
    {
        wstring wstrNewDir = wstrDir;
        while (wstrNewDir[wstrNewDir.length() - 1] != '\\')
        {
            wstrNewDir.erase(wstrNewDir.length() - 1);
        }
        // delete '\\' 
        wstrNewDir.erase(wstrNewDir.length() - 1);
 
        RecursiveDirectory(wstrNewDir);
        CreateDirectory(wstrDir.c_str(), NULL);
    }
 
    if (!PathFileExists(wstrDir.c_str()))
        return FALSE;
    return TRUE;
}

 遞歸建立目錄4:spa

bool createDirectory(const char* pathName)
{
    char path[MAX_PATH];
    memset(path, 0x00, MAX_PATH);
    const char* pos = pathName;
    while ((pos = strchr(pos, '\\')) != NULL)
    {
        memcpy(path, pathName, pos - pathName + 1);
        pos++;
        if (_access(path, 0) == 0)
        {
            continue;
        }
        else
        {
            int ret = _mkdir(path);
            if (ret == -1)
            {
                return false;
            }
        }
    }
    return true;
}

 

 

遞歸刪除目錄1:命令行

system("rmdir /s /q dirname");  //dirname是要刪除的目錄名稱,這種方式,在使用MFC程序的時候出閃過一個CMD的窗口
/s是級聯刪除  /q 是不提示(在命令行下操做的話,若是不加這個開關,會有提示確認是否刪除目錄,而在程序中不容許停下)

遞歸刪除目錄2:code

 SHFILEOPSTRUCT FileOp;
 FileOp.fFlags = FOF_NOCONFIRMATION;
 FileOp.hNameMappings = NULL;
 FileOp.hwnd = NULL;
 FileOp.lpszProgressTitle = NULL;
 FileOp.pFrom = ".\\tempDir";
 FileOp.pTo = NULL;
 FileOp.wFunc = FO_DELETE;
 SHFileOperation(&FileOp);

此處有一個地方要留心一下,就是FileOp.pFrom這個參數,它使用的字符串必定是要'\0'結尾的,這個地方使用".\\tempDir",這個字符串默認的結束字符就是'\0',因此若是存在這個目錄或者文件的話,必定能夠將其刪除,若是像下面這樣寫的話就會出錯:blog

std::string delPath = ".\\tempDir";遞歸

FileOp.pFrom = delPath.c_str();  // 此時字符串沒有以'\0'結尾,因此刪除的時候會出錯rem

遞歸刪除目錄3:

bool deleteDirectory( char* pathName)
{
    struct _finddata_t fData;
    memset(&fData, 0, sizeof(fData));
 
    if (_chdir(pathName) != 0) //_chdir函數設置當前目錄
    {
        printf("chdir failed: %s\n",pathName);
        return false;
    }
 
    intptr_t hFile = _findfirst("*",&fData);  //參數1:char *類型,"*"表示通配符,能夠查找文件、文件夾
    if(hFile == -1)
    {
        printf("_findfirst error!\n");
        return false;
    }
 
    do
    {
        if(fData.name[0] == '.')
            continue;
        if(fData.attrib == _A_SUBDIR) //子文件夾
        {
 
            char dirPath[MAX_PATH];
            memset(dirPath,0,sizeof(pathName));
            strcpy_s(dirPath,pathName);
            strcat_s(dirPath,"\\");
            strcat_s(dirPath,fData.name);
 
            deleteDirectory(dirPath);  //recursion subdir
            printf("remove dir: %s\n",dirPath);
            _chdir("..");
             _rmdir(dirPath);
        }
        else
        {
            char filePath[MAX_PATH];
            memset(filePath,0,sizeof(filePath));
            strcpy_s(filePath,pathName);
            strcat_s(filePath,"\\");
            strcat_s(filePath,fData.name);
 
            remove(filePath);
            printf("remove file: %s\n",filePath);
        }
    }while(_findnext(hFile,&fData) == 0);
 
    _findclose(hFile);  //close
 
    return true;
}
相關文章
相關標籤/搜索