Saturday, March 10, 2012

mkdir Utility

How can we implement mkdir utility


Code:

int mkdirp(const char *dir, mode_t mode)
{
    const char *p = dir + 1;

    while(*p)
    {
        if(*p == '/')
        {
            *((char*)p) = '\0';

            if(mkdir(dir, mode) == -1 && errno != EEXIST)
                return -1;

            *((char*)p) = '/';
        }

        p++;
    }

    if(*(p-1) != '/')
        if(mkdir(dir, mode) == -1 && errno != EEXIST)
            return -1;
    
    return 0;
}

No comments:

Post a Comment