-
-
Save tangxinfa/fd602be16b94ade7ab785dd48f2775d8 to your computer and use it in GitHub Desktop.
mkdir -p implemented in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <libgen.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/stat.h> | |
int mkdir_p(char* path) { | |
int len = strlen(path); | |
if (len == 0) { | |
return -1; | |
} else if (len == 1 && (path[0] == '.' || path[0] == '/')) { | |
return 0; | |
} | |
int ret = 0; | |
for (int i = 0; i < 2; ++i) { | |
ret = mkdir(path, S_IRWXU); | |
if (ret == 0) { | |
return 0; | |
} else if (errno == EEXIST) { | |
struct stat st; | |
ret = stat(path, &st); | |
if (ret != 0) { | |
return ret; | |
} else if (S_ISDIR(st.st_mode)) { | |
return 0; | |
} else { | |
return -1; | |
} | |
} else if (errno != ENOENT) { | |
return -1; | |
} | |
char* copy = strdup(path); | |
ret = mkdir_p(dirname(copy)); | |
free(copy); | |
if (ret != 0) { | |
return ret; | |
} | |
} | |
return ret; | |
} | |
int main(int argc, char* argv[]) { | |
if (argc < 2) { | |
printf("usage: %s <path>\n", argv[0]); | |
return EXIT_FAILURE; | |
} | |
int ret = mkdir_p(argv[1]); | |
printf("mkdir: %s: %d\n", argv[1], ret); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment