int mkdir_p(char * path); /* create dir recursively like mkdir(1) -p */
/* return : 0 successful, -1 failed */
---------------------------------------------------------------------------
#include
#include
#include
#include
#include
/*
* do the action like "mkdir(1) -p"
*/
int
mkdir_p(char * path)
{
char * ptr = NULL;
int i, len, ret;
len = strlen(path);
if (NULL == (ptr = malloc(len + 2))) {
return (-1);
}
strcpy(ptr, path);
/*
* convert "a/b/c/d" to "a/b/c/d/"
*/
if (ptr[len - 1] != '/') {
ptr[len] = '/'; ptr[len + 1] = '\0';
}
/*
* create dir recursively
*/
for (i = 1; i < len + 1; i++) {
if (ptr[i] == '/') {
ptr[i] = '\0';
ret = mkdir(ptr, 0755);
if (ret < 0 && errno != EEXIST) {
free(ptr);
return (-1);
}
ptr[i] = '/';
}
}
free(ptr);
return (0);
}
阅读(2318) | 评论(0) | 转发(0) |