coreutils

custom mini coreutils
git clone git://git.evenfri.xyz/coreutils.git
Log | Files | Refs | README

mkdir.c (1458B)


      1 #include <libc.h>
      2 
      3 #define eexist 17
      4 
      5 int has_p = 0;
      6 
      7 size_t strspn(const char *s1, const char *s2) {
      8   const char *p = s1, *spanp;
      9   char c, sc;
     10 
     11 cont:
     12   c = *p++;
     13   for (spanp = s2; (sc = *spanp++) != 0;)
     14     if (sc == c)
     15       goto cont;
     16 
     17   return (p - 1 - s1);
     18 }
     19 
     20 size_t strcspn(const char *s1, const char *s2) {
     21   const char *p, *spanp;
     22   char c, sc;
     23 
     24   for (p = s1;;) {
     25     c = *p++;
     26     spanp = s2;
     27     do {
     28       if ((sc = *spanp++) == c)
     29         return (p - 1 - s1);
     30     } while (sc != 0);
     31   }
     32   return 0;
     33 }
     34 
     35 int main(int argc, char *argv[]) {
     36   if (argc < 2) {
     37     write(stderr, "using: mkdir [options] <path>\n", 30);
     38     return 1;
     39   }
     40 
     41 
     42   for (int i = 1; i < argc; i++) {
     43     if (strcmp(argv[i], "-p") == 0) {
     44       has_p = 1;
     45       continue;
     46     }
     47 
     48     char *path = argv[i];
     49 
     50     if (has_p) {
     51       char *slash = path;
     52 
     53       for (;;) {
     54         slash += strspn(slash, "/");
     55         slash += strcspn(slash, "/");
     56 
     57         if (*slash == '\0') {
     58           if (*path != '\0') {
     59             int r = mkdir(path, 0777);
     60             if (r < 0 && errno != eexist)
     61               return errno;
     62           }
     63           break;
     64         }
     65         *slash = '\0';
     66         if (*path != '\0') {
     67           int r = mkdir(path, 0777);
     68           if (r < 0 && errno != eexist)
     69             return errno;
     70         }
     71         *slash = '/';
     72         slash++;
     73       }
     74     } else  {
     75       int r = mkdir(path, 0777);
     76       if (r < 0)
     77         return errno;
     78     }
     79   }
     80 
     81   return 0;
     82 }