C++创建文件夹的方式

提前说明:从参数角度上看,其实都应该使用 char*,但是为了方便这里使用的都是 string。在 sof 上找到一个方式把 string 转成 char*,就是调用 string 的函数 c_str()。

文本都是在 E:\database 路径下创建一个叫做 testFolder 的文件夹。给出的文件夹路径的方式是基于我的需要,不是最简单的。

一、使用 system() 调用 dos 命令
#include <iostream>
using namespace std;

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

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

    return 0;
}

二、使用头文件 direct.h 中的 access 和 mkdir 函数
关于 direct.h 我觉得 维基百科 上介绍的不错

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

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

    if (0 != access(folderPath.c_str(), 0))
    {
        // if this folder not exist, create a new one.
        mkdir(folderPath.c_str());
        //换成 ::_mkdir  ::_access 也行,不知道什么意思
    }

    return 0;
}

三、调用 Windows API 函数
#include <iostream>
#include <windows.h>
using namespace std;

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

    bool flag = CreateDirectory(folderPath.c_str(), NULL);
    // flag 为 true 说明创建成功

    return 0;
}

四、调用 MFC 封装好的接口函数
不推荐此方法,出错的话会有点麻烦。

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

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

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

    return 0;
}

如果你出现了错误 undefined reference to imp__PathIsDirectory @ 4,可以参考 undefined reference to imp PathIsDirectory
下面的方法是基于你详细阅读完上述链接后的前提下给出的

说我在 CodeBlocks 下解决该问题的方法:
第一步:在项目上右击,选择 Build Options


第二步: 在 Linker Settings 里添加 libshlwapi.a 文件

--------------------- 

原文:https://blog.csdn.net/sinat_41104353/article/details/83149441 
 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值