C++创建文件夹的四种方法

做一下笔记,方便以后找:

使用 system() 调用 dos 命令

#include <iostream>
using namespace std;

int main()
{
    string folderPath = "E:\\database\\testFolder"; 

    string command;
    command = "mkdir -p " + folderPath;  
    system(command.c_str());

    return 0;
}

使用头文件 direct.h 中的 access 和 mkdir 函数

#include <direct.h>
#include <iostream>
using namespace std;

int main()
{
    string folderPath = "E:\\database\\testFolder"; 

    if (0 != access(folderPath.c_str(), 0))
    {
        // if this folder not exist, create a new one.
        mkdir(folderPath.c_str());   // 返回 0 表示创建成功,-1 表示失败
        //换成 ::_mkdir  ::_access 可以创建多级目录,没测试
    }

    return 0;
}

调用 Windows API 函数

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
    string folderPath = "E:\\database\\testFolder"; 

    if (!GetFileAttributesA(folderPath.c_str()) & FILE_ATTRIBUTE_DIRECTORY) {
        bool flag = CreateDirectory(folderPath.c_str(), NULL);
        // flag 为 true 说明创建成功
    } else {
        cout<<"Directory already exists."<<endl;
    }

    return 0;
}

这个是别的博客看到的:

调用 MFC 封装好的接口函数

#include <iostream>
#include <shlwapi.h>
using namespace std;

int main()
{
    string folderPath = "E:\\database\\testFolder"; 

    if (!PathIsDirectory(folderPath.c_str()))  // 是否有重名文件夹
    {
        ::CreateDirectory(folderPath.c_str(), 0);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值