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

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

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

/tmp/a/b/c 

但如果目录不在那里,我希望他们自动创build。 一个可行的例子将是完美的。

这是一个可以用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 */ 

macrosSTRDUP()FREE()是在emalloc.h (在emalloc.cestrdup.c实现free()声明的strdup()free()错误检查版本。 "sysstat.h"头文件处理<sys/stat.h>破解版本,可以在现代Unix系统上用<sys/stat.h>代替(但是在1990年有很多问题)。 和"jlss.h"声明mkpath()

v1.12(previous)和v1.13(above)之间的变化是do_mkdir()EEXIST的testing。 Switch有必要指出 – 谢谢,Switch。 testing代码已经升级,并在MacBook Pro(运行Mac OS X 10.7.4的2.3GHz Intel Core i7)上重现问题,并build议在修订中解决该问题(但testing只能显示出现问题,从来没有他们的缺席)。

(特此授权您使用此代码用于任何具有归属的目的。)

使用Boost.Filesystem: create_directories很容易

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

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

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

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

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

 #include <sys/types.h> #include <sys/stat.h> int status; ... status = mkdir("/tmp/a/b/c", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); 

从这里 。 您可能必须为/ tmp,/ tmp / a,/ tmp / a / b /然后是/ tmp / a / b / c分别执行mkdirs,因为在c api中没有相同的-p标志。 当你在做高层次的时候,确定并忽略EEXISTS errno。

这里是我的代码示例(它适用于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 

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

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

这与前面的类似,但通过string向前而不是recursion地向后。 留下最后一次失败的正确值errno。 如果有一个前导斜杠,循环中有一个额外的时间,可以通过循环外部的一个find_first_of()来避免,或者通过检测前导/和前置置1来实现。无论我们通过a第一个循环或预循环调用,并且在使用预循环调用时复杂度会(略高)。

 #include <iostream> #include <string> #include <sys/stat.h> int mkpath(std::string s,mode_t mode) { size_t pre=0,pos; 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('/',pre))!=std::string::npos){ dir=s.substr(0,pos++); pre=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'; } 
 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; } 

所以我今天需要mkdirp() ,发现这个页面上的解决scheme过于复杂。 因此,我写了一个相当短的代码片断,很容易被复制到其他谁偶然发现这个线程奇怪,为什么我们需要这么多的代码行。

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铸造和临时修改string,只需做一个strdup()free()之后。

由于这篇文章在谷歌的“创build目录树”排名高,我打算发布一个适用于Windows的答案 – 这将使用编译为UNICODE或MBCS的Win32 API。 这是从上面的Mark的代码移植过来的。

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

它将与:

 c:\foo\bar\hello\world 

 c:\foo\bar\hellp\world\ 

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

在说“只要在Windows中使用SHCreateDirectoryEx() ”之前,请注意, SHCreateDirectoryEx()已被弃用,并且可能随时从未来版本的Windows中删除。

 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; } 

我知道这是一个古老的问题,但它显示谷歌search结果高,这里提供的答案不是真的在C ++或有点太复杂。

请注意,在我的例子中,createDirTree()非常简单,因为所有繁重的工作(错误检查,pathvalidation)都需要由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编写它,所以我决定跳过它。

 mkdir -p /dir/to/the/file touch /dir/to/the/file/thefile.ending 

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

 boost::filesystem::create_directories(boost::filesystem::path(output_file).parent_path().string().c_str()); 

其他人给你正确的答案,但我想我会展示你可以做的另一个整洁的事情:

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

将创build以下path:

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

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