Here's another take on mkpath()
, using recursion, which is both small and readable. It makes use of strdupa()
to avoid altering the given dir
string argument directly and to avoid using malloc()
& free()
. Make sure to compile with -D_GNU_SOURCE
to activate strdupa()
... meaning this code only works on GLIBC, EGLIBC, uClibc, and other GLIBC compatible C libraries.
int mkpath(char *dir, mode_t mode)
{
if (!dir) {
errno = EINVAL;
return 1;
}
if (strlen(dir) == 1 && dir[0] == '/')
return 0;
mkpath(dirname(strdupa(dir)), mode);
return mkdir(dir, mode);
}
After input both here and from Valery Frolov, in the Inadyn project, the following revised version of mkpath()
has now been pushed to libite
int mkpath(char *dir, mode_t mode)
{
struct stat sb;
if (!dir) {
errno = EINVAL;
return 1;
}
if (!stat(dir, &sb))
return 0;
mkpath(dirname(strdupa(dir)), mode);
return mkdir(dir, mode);
}
It uses one more syscall, but otoh the code is more readable now.