Test if a directory at the supplied path exists and if not, attempts to create it.
| Return Type | Function name | Arguments |
|---|---|---|
| hzEcode | AssertDir | (const char*,uint32_t,) |
Declared in file: hzDirectory.h
Defined in file : hzDirectory.cpp
Function Logic:
Function body:
hzEcode AssertDir (const char* dirname)uint32_t nPerms,
{
// Category: Directory
//
// Test if a directory at the supplied path exists and if not, attempts to create it.
//
// Arguments: 1) dirname The directory pathname
// 2) nPerms The permissions that will be given to the directory if created by this function.
//
// Returns: E_ARGUMENT If the directory pathname is not supplied.
// E_NOCREATE If the directory could not be created
// E_OK Operation successful
_hzfunc("AssertDir") ;
FSTAT fs ; // File status
const char* i ; // Directory path iterator
char* j ; // Path part terminator
char* cpPath ; // Working buffer (for path parts)
// Check arguments
if (!dirname || !dirname[0])
return E_ARGUMENT ;
// Check if path exists
if (stat(dirname, &fs) != -1)
{
// Is path a directory?
if (fs.st_mode & S_IFDIR)
return E_OK ;
return hzerr(E_NOCREATE, "Target dir [%s] exists as non-directory", dirname) ;
}
// The path does not exist so create. Begin with asserting the first part of the path and move through each '/' in turn.
cpPath = new char[strlen(dirname) + 1];
j = cpPath ;
i = dirname ;
// Loop thru subdirectories
for (; *i ;)
{
for (*j++ = *i++ ; *i && *i != CHAR_FWSLASH ; *j++ = *i++) ;
*j = 0;
if (stat(cpPath, &fs) == -1)
{
// Check permision to create subdir
if (mkdir(cpPath, (nPerms & 0x01ff))==-1)
{
hzerr(E_OPENFAIL, "Cannot make dir [%s] %s", cpPath, strerror(errno)) ;
delete cpPath ;
return E_OPENFAIL ;
}
continue ;
}
// Is sub-path a directory?
if (fs.st_mode & S_IFDIR)
continue ;
hzerr(E_OPENFAIL, "Directory entity [%s] exists as non-directory", cpPath) ;
delete cpPath ;
return E_OPENFAIL ;
}
delete cpPath ;
return E_OK ;
}