windows下,linux下c++生成文件夹

windows下方法

方法1:使用system()函数调用 mkdir 命令

代码如下

#include <string>
using namespace std;

int main()
{
    string folderPath = "testFolder";
    string command = "mkdir " + folderPath;
    system(command.c_str());
}

效果:在当前目录下生成一个testFolder的文件夹,如下图

////////////////////////////////////////////// 分割线 /////////////////////////////////////////////

linux下方法

代码如下

#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <iostream>
using namespace std;

bool createDirs(const string& dirName)
{
    // 全路径名
    string fullPath = "";

    uint32_t beginCmpPath = 0; // fullPath开始的下标
    uint32_t endCmpPath   = 0; // fullPath结尾的下标

    if('/' != dirName[0]) // 不是'/'开头说明是相对路径
    {
        // 使用getcwd()函数获取当前工作目录的绝对路径
        fullPath = getcwd(NULL, 0);
        beginCmpPath = fullPath.size();

        // 得到全路径名
        fullPath = fullPath + "/" + dirName;
    }
    else // 绝对路径
    {
        fullPath = dirName;
        beginCmpPath = 1;
    }


    // 结尾不是 '/' 结尾,则加上 '/'
    if (fullPath[fullPath.size() - 1] != '/')
    {
        fullPath += "/";
    }

    endCmpPath = fullPath.size();


    // 从前往后遍历
    for(uint32_t i = beginCmpPath; i < endCmpPath ; i++ )
    {
        // 以 '/' 为分隔符
        if('/' == fullPath[i])
        {
            string curPath = fullPath.substr(0, i);
            // 若该目录不存在
            if(access(curPath.c_str(), F_OK) != 0)
            {
                // 新建该目录(S_IRUSR:用户读权限; S_IRGRP:用户组读权限; S_IROTH:其他组都权限; S_IWUSR:用户写权限; S_IWGRP:用户组写权限; S_IWOTH:其他组写权限)
                if(mkdir(curPath.c_str(), S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH) == -1)
                {
                    return false;
                }
            }
        }
    }

    return true;
}

int main()
{
        createDirs("go/log");
        return 0;
}

效果图(可以看到我们编译出可执行程序test后,执行得到目录 go/log)

扫描二维码关注公众号,回复: 9746843 查看本文章
发布了108 篇原创文章 · 获赞 62 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/yzf279533105/article/details/104760307