Metropoli BBS
VIEWER: mkpath.c MODE: TEXT (ASCII)
/************************************************************************/
/*                                                                      */
/*  Create all subdirectories of a given pathname                       */
/*                                                                      */
/*  Bug reports should be sent to                                       */
/*                                                                      */
/*  harald@os2point.ping.de                                             */
/*  harald@haport.sesam.com                                             */
/*  Fido: 2:2448/434                                                    */
/*                                                                      */
/************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <direct.h>
#include <errno.h>

#include <dbgheap.h>

#include <lprintf.h>
#include <chanlib.h>

/************************************************************************/
/*  makepath                                                            */
/*                                                                      */
/*  Creates a subdirectory and all its intermediate directories too.    */
/*  The 'pathname' parameter must contain backslashes, not slashes,     */
/*  including a trailing backslash.                                     */
/*                                                                      */
/*  An appended filename would do no harm.                              */
/*                                                                      */
/************************************************************************/
int makepath(char *pathname)
{
    int r;
    char *cp = strrchr(pathname, '\\');

    /*
     * Optimize common case, in which parent directory exists
     */
    if(cp)
        *cp = '\0';
    r = mkdir(pathname);
    if(cp)
        *cp = '\\';
    if(!r)
        return(0);

    /*
     * Set cp on first directory following a drive name
     */
    cp = pathname;
    if(pathname[1] == ':' || (pathname[0] == '\\' && pathname[1] == '\\'))
        cp += 3;

    /*
     * Now loop to create all subdirs
     */
    r = 0;
    while(!r && (cp = strchr(cp, '\\')) != NULL) {
        *cp = '\0';
        if(mkdir(pathname) && errno != EACCES) {
            r = -1;
            lperror(pathname);
        }
        *cp++ = '\\';
    }
    return(r);
}
[ RETURN TO DIRECTORY ]