Windows 下创建目录,以及递归删除目录

Windows 下创建目录,以及删除目录,网上有很多不错的内容,但是有的有问题,记录下自己的实践。


创建目录利用_mkdir
,删除目录利用_rmdir
目录是否可以访问_access
设置当前的访问目录_chdir


利用_findfirst,_findnext进行遍历整个目录,遍历结束需要关闭句柄_findclose。


#include <io.h>
#include <windows.h>
#include <direct.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>

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;
}


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;
}

int main(void)
{
//    createDirectory("D:\\test\\txt");
    deleteDirectory("D:\\test");
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值