Advertisement
gocha

Create all directories in path (*nix)

Nov 19th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. /*
  2.  * Create all directories in path
  3.  * Original code by J Leffler (mkpath.c)
  4.  * http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
  5.  */
  6.  
  7. #include <errno.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <sys/stat.h>
  11. #include <sys/types.h>
  12.  
  13. static int do_mkdir(const char *path, mode_t mode)
  14. {
  15.     struct stat st;
  16.     int status = 0;
  17.  
  18.     if (stat(path, &st) != 0)
  19.     {
  20.         /* Directory does not exist. EEXIST for race condition */
  21.         if (mkdir(path, mode) != 0 && errno != EEXIST)
  22.         {
  23.             status = -1;
  24.         }
  25.     }
  26.     else if (!S_ISDIR(st.st_mode))
  27.     {
  28.         errno = ENOTDIR;
  29.         status = -1;
  30.     }
  31.  
  32.     return(status);
  33. }
  34.  
  35. /**
  36.  * mkpath - ensure all directories in path exist
  37.  * Algorithm takes the pessimistic view and works top-down to ensure
  38.  * each directory in path exists, rather than optimistically creating
  39.  * the last element and working backwards.
  40.  */
  41. int mkpath(const char *path, mode_t mode)
  42. {
  43.     char *pp;
  44.     char *sp;
  45.     int status;
  46.     char *copypath;
  47.  
  48.     copypath = strdup(path);
  49.     if (copypath == NULL)
  50.     {
  51.         return -1;
  52.     }
  53.  
  54.     status = 0;
  55.     pp = copypath;
  56.     while (status == 0 && (sp = strchr(pp, '/')) != NULL)
  57.     {
  58.         if (sp != pp)
  59.         {
  60.             /* Neither root nor double slash in path */
  61.             *sp = '\0';
  62.             status = do_mkdir(copypath, mode);
  63.             *sp = '/';
  64.         }
  65.         pp = sp + 1;
  66.     }
  67.     if (status == 0)
  68.     {
  69.         status = do_mkdir(path, mode);
  70.     }
  71.     free(copypath);
  72.     return status;
  73. }
  74.  
  75. #include <stdio.h>
  76.  
  77. int main(int argc, char **argv)
  78. {
  79.     int i;
  80.     int rc;
  81.  
  82.     if (argc != 2)
  83.     {
  84.         printf("Usage: %s <path>\n", argv[0]);
  85.         return EXIT_FAILURE;
  86.     }
  87.  
  88.     rc = mkpath(argv[1], 0777);
  89.     if (rc != 0)
  90.     {
  91.         fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
  92.             (int)getpid(), errno, strerror(errno), argv[1]);
  93.     }
  94.     return (rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement