mkdir只能创建一层路径,比如,/home/xyz/abc/123,abc必须已经存在,否则mkdir会报错。于是我就写了一个简单的函数,能够创建多层路径,如上面的例子,xyz和abc可以都不存在。
bool create_dir(char* sz_path)
{
char sz_opath[256];
char *p;
size_t len;
int ret = -1;
bool rc = true;
strncpy(sz_opath, sz_path, sizeof(sz_opath));
len = strlen(sz_opath);
if(sz_opath[len - 1] == '/') {
sz_opath[len - 1] = '/0';
}
for(p = (char*)sz_opath+1; *p; p++) {
if(*p == '/') {
*p = '/0';
if(access(sz_opath, F_OK) != 0) {
ret = mkdir(sz_opath, S_IRWXU);
if (ret != 0) rc = false;
}
*p = '/';
}
}
if(access(sz_opath, F_OK) != 0) {
ret = mkdir(sz_opath, S_IRWXU);
if (ret != 0) rc = false;
}
return rc;
}
bool create_dir(char* sz_path)
{
char sz_opath[256];
char *p;
size_t len;
int ret = -1;
bool rc = true;
strncpy(sz_opath, sz_path, sizeof(sz_opath));
len = strlen(sz_opath);
if(sz_opath[len - 1] == '/') {
sz_opath[len - 1] = '/0';
}
for(p = (char*)sz_opath+1; *p; p++) {
if(*p == '/') {
*p = '/0';
if(access(sz_opath, F_OK) != 0) {
ret = mkdir(sz_opath, S_IRWXU);
if (ret != 0) rc = false;
}
*p = '/';
}
}
if(access(sz_opath, F_OK) != 0) {
ret = mkdir(sz_opath, S_IRWXU);
if (ret != 0) rc = false;
}
return rc;
}