From 5f09d05bbd75624cf9ba2d0f0f03f8e1c8563faf Mon Sep 17 00:00:00 2001 From: prozacx Date: Sun, 3 Apr 2005 05:46:18 +0000 Subject: [PATCH] Added MakeDir for creating dirs including parents git-svn-id: https://znc.svn.sourceforge.net/svnroot/znc/trunk@73 726aef4b-f618-498e-8847-2d620e286838 --- Utils.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ Utils.h | 1 + 2 files changed, 52 insertions(+) diff --git a/Utils.cpp b/Utils.cpp index 4e8fb5b4..9310f412 100644 --- a/Utils.cpp +++ b/Utils.cpp @@ -109,6 +109,57 @@ string CUtils::ChangeDir(const string& sPath, const string& sAdd, const string& return (sRet.empty()) ? "/" : sRet; } +int CUtils::MakeDir(const string& sPath, mode_t iMode) { + string sDir = sPath; + string::size_type iFind = sDir.find("/"); + + if (iFind == string::npos) { + return mkdir(sDir.c_str(), iMode); + } + + string sWorkDir = sDir.substr(0, iFind + 1); // include the trailing slash + string sNewDir = sDir.erase(0, iFind + 1); + + struct stat st; + + if (sWorkDir.length() > 1) { + sWorkDir = sWorkDir.erase( sWorkDir.length() - 1, 1 ); // trim off the trailing slash + } + + if (stat(sWorkDir.c_str(), &st) == 0) + { + int iChdir = chdir(sWorkDir.c_str()); + if (iChdir != 0) { + return iChdir; // could not change to dir + } + + // go ahead and call the next step + return MakeDir(sNewDir.c_str(), iMode); + } + + switch(errno) + { + case ENOENT: { + // ok, file doesn't exists, lets create it and cd into it + int iMkdir = mkdir(sWorkDir.c_str(), iMode); + if (iMkdir != 0) { + return iMkdir; // could not create dir + } + + int iChdir = chdir(sWorkDir.c_str()); + if (iChdir != 0) { + return iChdir; // could not change to dir + } + + return MakeDir(sNewDir.c_str(), iMode); + } + default: + break; + } + + return -1; +} + string CUtils::ToString(short i) { stringstream s; s << i; return s.str(); } string CUtils::ToString(unsigned short i) { stringstream s; s << i; return s.str(); } string CUtils::ToString(int i) { stringstream s; s << i; return s.str(); } diff --git a/Utils.h b/Utils.h index 59164c91..a0253075 100644 --- a/Utils.h +++ b/Utils.h @@ -28,6 +28,7 @@ public: static string GetIP(unsigned long addr); static unsigned long GetLongIP(const string& sIP); static string ChangeDir(const string& sPath, const string& sAdd, const string& sHomeDir); + static int MakeDir(const string& sPath, mode_t iMode = 0700); static string ToString(short i); static string ToString(unsigned short i);