首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C++/Linux中创建目录树?

如何在C++/Linux中创建目录树?
EN

Stack Overflow用户
提问于 2009-03-23 20:10:26
回答 15查看 228.8K关注 0票数 129

我想要一种在C++/Linux中创建多个目录的简单方法。

例如,我想要在目录中保存一个文件lola.file:

/tmp/a/b/c

但是如果目录不在那里,我希望自动创建它们。一个工作的例子将是完美的。

EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2009-03-23 20:29:58

轻松使用Boost.Filesystem:create_directories

#include <boost/filesystem.hpp>
//...
boost::filesystem::create_directories("/tmp/a/b/c");

如果创建了新目录,则返回:true,否则返回false

票数 167
EN

Stack Overflow用户

发布于 2009-03-23 20:12:34

system("mkdir -p /tmp/a/b/c")

是我能想到的最短的方式(就代码长度而言,不一定是执行时间)。

它不是跨平台的,但可以在Linux下工作。

票数 44
EN

Stack Overflow用户

发布于 2015-04-24 00:08:06

下面是我的代码示例(它同时适用于Windows和Linux):

#include <iostream>
#include <string>
#include <sys/stat.h> // stat
#include <errno.h>    // errno, ENOENT, EEXIST
#if defined(_WIN32)
#include <direct.h>   // _mkdir
#endif

bool isDirExist(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    if (_stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & _S_IFDIR) != 0;
#else 
    struct stat info;
    if (stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & S_IFDIR) != 0;
#endif
}

bool makePath(const std::string& path)
{
#if defined(_WIN32)
    int ret = _mkdir(path.c_str());
#else
    mode_t mode = 0755;
    int ret = mkdir(path.c_str(), mode);
#endif
    if (ret == 0)
        return true;

    switch (errno)
    {
    case ENOENT:
        // parent didn't exist, try to create it
        {
            int pos = path.find_last_of('/');
            if (pos == std::string::npos)
#if defined(_WIN32)
                pos = path.find_last_of('\\');
            if (pos == std::string::npos)
#endif
                return false;
            if (!makePath( path.substr(0, pos) ))
                return false;
        }
        // now, try to create again
#if defined(_WIN32)
        return 0 == _mkdir(path.c_str());
#else 
        return 0 == mkdir(path.c_str(), mode);
#endif

    case EEXIST:
        // done!
        return isDirExist(path);

    default:
        return false;
    }
}

int main(int argc, char* ARGV[])
{
    for (int i=1; i<argc; i++)
    {
        std::cout << "creating " << ARGV[i] << " ... " << (makePath(ARGV[i]) ? "OK" : "failed") << std::endl;
    }
    return 0;
}

用法:

$ makePath 1/2 folderA/folderB/folderC
creating 1/2 ... OK
creating folderA/folderB/folderC ... OK
票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/675039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档