/* Copyright (C) 1994, Klaus Preschern. */ /* All rights reserved. */ /* See the file COPYRIGHT.KP for a full description. */ /* * "m3mkdir X/Y/Z" will build directory X/Y/Z and * any missing intermediate directories. */ #include #include #define DEBUG 0 #define DIRS_LEN 4096 #define PATH_LEN 1024 static char * progname; static char dirs [DIRS_LEN] = ""; static char temp [DIRS_LEN] = ""; static char cur_dir [PATH_LEN] = ""; static char last_dir [PATH_LEN] = "@"; static int is_dir (char * name) { struct stat statbuf; #if DEBUG printf ("is_dir (%s)\n", name); #endif if (stat (name, &statbuf) < 0) { return 0; } return (statbuf.st_mode & __S_IFDIR); } static void dirname (char * name, char * path) { int i = strlen (path); name [0] = '\0'; while ((i > 0) && (path [i] != '/')) { i--; } if (path [i] == '/') { strncpy (name, path, i); name [i] = '\0'; } #if DEBUG printf ("dirname (%s, %s)\n", name, path); #endif } /* already done? */ /* if [ -d $1 ]; then exit 0; fi */ static int already_done (char * path) { struct stat statbuf; if (stat (path, &statbuf) < 0) { return 0; } if (statbuf.st_mode & __S_IFDIR) { return 1; } fprintf (stderr, "%s: %s exists and is not a directory\n", progname, path); exit (-1); } /* build a list of all the missing intermediate directories */ /* dirs="" * cur_dir=$1 * last_dir="@" * while [ $last_dir != $cur_dir -a ! -d $cur_dir ]; do * dirs="$cur_dir $dirs" * last_dir=$cur_dir * cur_dir=`dirname $cur_dir` * done */ static void build_dir_list (char * path) { strcpy (cur_dir, path); while ((strcmp (last_dir, cur_dir) != 0) && (! is_dir (cur_dir))) { strcpy (temp, dirs); strcpy (dirs, cur_dir); if (strlen (cur_dir) != 0) { strcat (dirs, " "); } strcat (dirs, temp); strcpy (last_dir, cur_dir); dirname (temp, cur_dir); strcpy (cur_dir, temp); } } /* finally, build the directories */ /* for f in $dirs ; do * echo mkdir $f * mkdir $f || exit 1 * done */ static void build_dirs (char * list) { int i = 0, j = 0, len = strlen (list); #if DEBUG printf ("build_dirs (%s)\n", list); #endif while (i < len) { while ((list [j] != '\0') && (list [j] != ' ')) { j++; } list [j] = '\0'; strcpy (temp, &list [i]); fprintf (stdout, "mkdir %s\n", temp); if (mkdir (temp, 0) < 0) { fprintf (stderr, "%s: cannot create %s\n", progname, temp); } i = j + 1; j = i; } } int main (int argc, char ** argv) { progname = argv [0]; if (argc != 2) { fprintf (stderr, "usage: %s directory_path\n", progname); exit (-1); } if (! already_done (argv [1])) { build_dir_list (argv [1]); build_dirs (dirs); } return 0; }