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

时间:2009-03-23 20:10:26

标签: c++ linux directory

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

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

/tmp/a/b/c

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

18 个答案:

答案 0 :(得分:152)

使用Boost.Filesystem轻松:create_directories

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

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

答案 1 :(得分:57)

这是一个可以用C ++编译器编译的C函数。

/*
@(#)File:           $RCSfile: mkpath.c,v $
@(#)Version:        $Revision: 1.13 $
@(#)Last changed:   $Date: 2012/07/15 00:40:37 $
@(#)Purpose:        Create all directories in path
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1990-91,1997-98,2001,2005,2008,2012
*/

/*TABSTOP=4*/

#include "jlss.h"
#include "emalloc.h"

#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <string.h>
#include "sysstat.h"    /* Fix up for Windows - inc mode_t */

typedef struct stat Stat;

#ifndef lint
/* Prevent over-aggressive optimizers from eliminating ID string */
const char jlss_id_mkpath_c[] = "@(#)$Id: mkpath.c,v 1.13 2012/07/15 00:40:37 jleffler Exp $";
#endif /* lint */

static int do_mkdir(const char *path, mode_t mode)
{
    Stat            st;
    int             status = 0;

    if (stat(path, &st) != 0)
    {
        /* Directory does not exist. EEXIST for race condition */
        if (mkdir(path, mode) != 0 && errno != EEXIST)
            status = -1;
    }
    else if (!S_ISDIR(st.st_mode))
    {
        errno = ENOTDIR;
        status = -1;
    }

    return(status);
}

/**
** mkpath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
int mkpath(const char *path, mode_t mode)
{
    char           *pp;
    char           *sp;
    int             status;
    char           *copypath = STRDUP(path);

    status = 0;
    pp = copypath;
    while (status == 0 && (sp = strchr(pp, '/')) != 0)
    {
        if (sp != pp)
        {
            /* Neither root nor double slash in path */
            *sp = '\0';
            status = do_mkdir(copypath, mode);
            *sp = '/';
        }
        pp = sp + 1;
    }
    if (status == 0)
        status = do_mkdir(path, mode);
    FREE(copypath);
    return (status);
}

#ifdef TEST

#include <stdio.h>

/*
** Stress test with parallel running of mkpath() function.
** Before the EEXIST test, code would fail.
** With the EEXIST test, code does not fail.
**
** Test shell script
** PREFIX=mkpath.$$
** NAME=./$PREFIX/sa/32/ad/13/23/13/12/13/sd/ds/ww/qq/ss/dd/zz/xx/dd/rr/ff/ff/ss/ss/ss/ss/ss/ss/ss/ss
** : ${MKPATH:=mkpath}
** ./$MKPATH $NAME &
** [...repeat a dozen times or so...]
** ./$MKPATH $NAME &
** wait
** rm -fr ./$PREFIX/
*/

int main(int argc, char **argv)
{
    int             i;

    for (i = 1; i < argc; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            if (fork() == 0)
            {
                int rc = mkpath(argv[i], 0777);
                if (rc != 0)
                    fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
                            (int)getpid(), errno, strerror(errno), argv[i]);
                exit(rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
            }
        }
        int status;
        int fail = 0;
        while (wait(&status) != -1)
        {
            if (WEXITSTATUS(status) != 0)
                fail = 1;
        }
        if (fail == 0)
            printf("created: %s\n", argv[i]);
    }
    return(0);
}

#endif /* TEST */

STRDUP()FREE()strdup()free()的错误检查版本,在emalloc.h中声明(并在emalloc.c中实施和estrdup.c)。 "sysstat.h"标题处理<sys/stat.h>的破坏版本,可以在现代Unix系统上由<sys/stat.h>替换(但1990年有许多问题)。 "jlss.h"声明mkpath()

v1.12(上一个)和v1.13(上面)之间的变化是EEXISTdo_mkdir()的测试。 Switch有必要指出这一点 - 谢谢你,Switch。测试代码已经升级并在MacBook Pro(2.3GHz Intel Core i7,运行Mac OS X 10.7.4)上重现了这个问题,并建议在修订版中修复问题(但测试只能显示bug的存在) ,从不他们缺席。)

(特此授权您将此代码用于归因的任何目的。)

答案 2 :(得分:36)

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

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

它不是跨平台的,但可以在Linux下运行。

答案 3 :(得分:24)

#include <sys/types.h>
#include <sys/stat.h>

int status;
...
status = mkdir("/tmp/a/b/c", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

来自here。您可能必须为/ tmp,/ tmp / a,/ tmp / a / b /然后/ tmp / a / b / c单独执行mkdirs,因为在C api中没有等效的-p标志。当你做上层时,请确保并忽略EEXISTS错误。

答案 4 :(得分:23)

以下是我的代码示例(适用于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

答案 5 :(得分:9)

这与前一个类似,但是通过字符串向前工作而不是向后递归。为最后一次失败留下错误的正确值。如果有一个前导斜杠,那么循环中有一个额外的时间可以通过循环外的一个find_first_of()或通过检测前导/并将前置设置为1来避免。无论我们是否通过设置设置,效率都是相同的第一个循环或一个预循环调用,使用预循环调用时复杂度会略微提高。

#include <iostream>
#include <string>
#include <sys/stat.h>

int
mkpath(std::string s,mode_t mode)
{
    size_t pos=0;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        // force trailing / so we can handle everything in loop
        s+='/';
    }

    while((pos=s.find_first_of('/',pos))!=std::string::npos){
        dir=s.substr(0,pos++);
        if(dir.size()==0) continue; // if leading / first time is 0 length
        if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

int main()
{
    int mkdirretval;
    mkdirretval=mkpath("./foo/bar",0755);
    std::cout << mkdirretval << '\n';

}

答案 6 :(得分:7)

你说“C ++”但是这里的每个人似乎都在想“Bash shell。”

查看gnu mkdir的源代码;那么你可以看到如何在C ++中实现shell命令。

答案 7 :(得分:6)

应该注意,从C ++ 17文件系统接口开始是标准库的一部分。这意味着可以使用以下内容来创建目录:

#include <filesystem>

std::filesystem::create_directories("/a/b/c/d")

此处有更多信息:https://en.cppreference.com/w/cpp/filesystem/create_directory

另外,对于gcc,需要将“ -std = c ++ 17”发送给CFLAGS。和“ -lstdc ++ fs”到LDLIBS。将来可能不再需要后者。

答案 8 :(得分:3)

bool mkpath( std::string path )
{
    bool bSuccess = false;
    int nRC = ::mkdir( path.c_str(), 0775 );
    if( nRC == -1 )
    {
        switch( errno )
        {
            case ENOENT:
                //parent didn't exist, try to create it
                if( mkpath( path.substr(0, path.find_last_of('/')) ) )
                    //Now, try to create again.
                    bSuccess = 0 == ::mkdir( path.c_str(), 0775 );
                else
                    bSuccess = false;
                break;
            case EEXIST:
                //Done!
                bSuccess = true;
                break;
            default:
                bSuccess = false;
                break;
        }
    }
    else
        bSuccess = true;
    return bSuccess;
}

答案 9 :(得分:3)

所以今天我需要mkdirp(),并发现此页面上的解决方案过于复杂。 因此,我写了一个相当简短的片段,很容易被其他人复制 偶然发现这个线程,我们想知道为什么我们需要这么多行代码。

<强> mkdirp.h

#ifndef MKDIRP_H
#define MKDIRP_H

#include <sys/stat.h>

#define DEFAULT_MODE      S_IRWXU | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH

/** Utility function to create directory tree */
bool mkdirp(const char* path, mode_t mode = DEFAULT_MODE);

#endif // MKDIRP_H

<强> mkdirp.cpp

#include <errno.h>

bool mkdirp(const char* path, mode_t mode) {
  // const cast for hack
  char* p = const_cast<char*>(path);

  // Do mkdir for each slash until end of string or error
  while (*p != '\0') {
    // Skip first character
    p++;

    // Find first slash or end
    while(*p != '\0' && *p != '/') p++;

    // Remember value from p
    char v = *p;

    // Write end of string at p
    *p = '\0';

    // Create folder from path to '\0' inserted at p
    if(mkdir(path, mode) == -1 && errno != EEXIST) {
      *p = v;
      return false;
    }

    // Restore path to it's former glory
    *p = v;
  }

  return true;
}

如果您不喜欢const cast并暂时修改字符串,请稍后再执行strdup()free()

答案 10 :(得分:2)

由于这篇文章在谷歌的“创建目录树”中排名很高,我将发布一个适用于Windows的答案 - 这将使用为UNICODE或MBCS编译的Win32 API。这是从上面的马克代码移植而来的。

由于这是我们正在使用的Windows,目录分隔符是反斜杠,而不是正斜杠。如果您希望使用正斜杠,请将 '\\' 更改为 '/'

它适用于:

c:\foo\bar\hello\world

c:\foo\bar\hellp\world\

(即:不需要斜杠,所以你不必检查它。)

在说“在Windows中使用 SHCreateDirectoryEx()”之前,请注意 SHCreateDirectoryEx()已弃用,可以在以后的Windows版本中随时删除。< / p>

bool CreateDirectoryTree(LPCTSTR szPathTree, LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL){
    bool bSuccess = false;
    const BOOL bCD = CreateDirectory(szPathTree, lpSecurityAttributes);
    DWORD dwLastError = 0;
    if(!bCD){
        dwLastError = GetLastError();
    }else{
        return true;
    }
    switch(dwLastError){
        case ERROR_ALREADY_EXISTS:
            bSuccess = true;
            break;
        case ERROR_PATH_NOT_FOUND:
            {
                TCHAR szPrev[MAX_PATH] = {0};
                LPCTSTR szLast = _tcsrchr(szPathTree,'\\');
                _tcsnccpy(szPrev,szPathTree,(int)(szLast-szPathTree));
                if(CreateDirectoryTree(szPrev,lpSecurityAttributes)){
                    bSuccess = CreateDirectory(szPathTree,lpSecurityAttributes)!=0;
                    if(!bSuccess){
                        bSuccess = (GetLastError()==ERROR_ALREADY_EXISTS);
                    }
                }else{
                    bSuccess = false;
                }
            }
            break;
        default:
            bSuccess = false;
            break;
    }

    return bSuccess;
}

答案 11 :(得分:2)

我知道这是一个老问题,但它在谷歌搜索结果中显示得很高,这里提供的答案实际上并不是用C ++或者有点太复杂。

请注意,在我的示例中,createDirTree()非常简单,因为所有繁重的工作(错误检查,路径验证)都需要由createDir()完成。如果目录已经存在或者整个事情都不起作用,createDir()应该返回true。

以下是我在C ++中的表现方式:

#include <iostream>
#include <string>

bool createDir(const std::string dir)
{
    std::cout << "Make sure dir is a valid path, it does not exist and create it: "
              << dir << std::endl;
    return true;
}

bool createDirTree(const std::string full_path)
{
    size_t pos = 0;
    bool ret_val = true;

    while(ret_val == true && pos != std::string::npos)
    {
        pos = full_path.find('/', pos + 1);
        ret_val = createDir(full_path.substr(0, pos));
    }

    return ret_val;
}

int main()
{
    createDirTree("/tmp/a/b/c");
    return 0;
}

当然createDir()函数是系统特定的,在其他答案中已经有足够的例子如何为linux编写它,所以我决定跳过它。

答案 12 :(得分:1)

如果dir不存在,请创建它:

class PatchedClass
  using StringPatch
  def foo
    "test".foo #=> true
  end
end

class PatchedClass
  def bar
    "test".foo
  end
end

patched = PatchedClass.new
puts patched.foo  #=> true
puts patched.bar  #=> undefined method `foo' for "test":String (NoMethodError)

答案 13 :(得分:1)

这里描述了很多方法,但是大多数方法都需要对进入代码的路径进行硬编码。 有一个简单的解决方案,使用QD框架的两类QDir和QFileInfo。由于您已经在Linux环境中,因此使用Qt应该很容易。

QString qStringFileName("path/to/the/file/that/dont/exist.txt");
QDir dir = QFileInfo(qStringFileName).dir();
if(!dir.exists()) {
        dir.mkpath(dir.path());
}

确保您对该路径具有写权限。

答案 14 :(得分:0)

如果您还没有C ++ 17并寻找与平台无关的解决方案,请使用ghc::filesystem。标头符号代码与C ++ 17(实际上是一个反向端口)兼容,以后很容易移植。

答案 15 :(得分:0)

这是C / C ++递归函数,它使用dirname()遍历目录树的底部。找到现有祖先后,它将立即停止。

#include <libgen.h>
#include <string.h>

int create_dir_tree_recursive(const char *path, const mode_t mode)
{
    if (strcmp(path, "/") == 0) // No need of checking if we are at root.
        return 0;

    // Check whether this dir exists or not.
    struct stat st;
    if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode))
    {
        // Check and create parent dir tree first.
        char *path2 = strdup(path);
        char *parent_dir_path = dirname(path2);
        if (create_dir_tree_recursive(parent_dir_path, mode) == -1)
            return -1;

        // Create this dir.
        if (mkdir(path, mode) == -1)
            return -1;
    }

    return 0;
}

答案 16 :(得分:0)

mkdir -p /dir/to/the/file

touch /dir/to/the/file/thefile.ending

答案 17 :(得分:-2)

其他人给了你正确答案,但我想我会展示你能做的另一件好事:

mkdir -p /tmp/a/{b,c}/d

将创建以下路径:

/tmp/a/b/d
/tmp/a/c/d

大括号允许您在层次结构的同一级别上一次创建多个目录,而-p选项意味着“根据需要创建父目录”。

相关问题