实现的小函数 mkdir rmdir

来源:互联网 发布:成都伊藤网络超市 编辑:程序博客网 时间:2024/06/11 04:32

int mkdirs(const char *path)
{
    char pathname[PATH_MAX];
    strcpy(pathname, path);
    int i;
    int len = strlen(pathname);
    if (pathname[len -1] != '/') {
        strcat(pathname, "/");
    }
    len = strlen(pathname);

    for (i=1; i<len; i++) {
        if (pathname[i] == '/') {
            pathname[i] = 0;
            if (access(pathname, F_OK) != 0) {
                if (mkdir(pathname, 0755) == -1) {
                     my_log_error("mkdir(%s) failed. Reason:%s.", pathname, strerror(errno));
                     return -1;
                }
            }
            pathname[i]='/';
        }
    }

    return 0;
}

 

 

int rmdirs(const char *name)
{
    int ret = 0;
    DIR *dir;
    struct dirent *read_dir;
    struct stat st;
    char buf[PATH_MAX];

    if (lstat(name, &st) < 0) {
         if (errno == ENOENT) {
             return ret;
         }
         my_log_error("lstat(%s) failed. Reason:%s.", name, strerror(errno));
         return -1;
    }

    if (S_ISDIR(st.st_mode)) {
        if ((dir = opendir(name)) == NULL) {
            my_log_error("opendir(%s) failed. Reason:%s.", name, strerror(errno));
            return -1;
        }

        while ((read_dir = readdir(dir)) != NULL) {
            if (strcmp(read_dir->d_name, ".") == 0 || strcmp(read_dir->d_name, "..") == 0) {
                continue;
            }
            sprintf(buf, "%s/%s", name, read_dir->d_name);
            ret = rmdirs(buf);
            if (0 != ret) {
                return -1;
            }
        }
        closedir(dir);
    }

    if (remove(name) != 0) {
        my_log_error("opendir(%s) failed. Reason:%s.", name, strerror(errno));
        return -1;
    }

    return ret;
}

 

原创粉丝点击