Skip to content

Instantly share code, notes, and snippets.

@tangxinfa
Forked from JonathonReinhart/SConstruct
Last active July 11, 2022 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangxinfa/fd602be16b94ade7ab785dd48f2775d8 to your computer and use it in GitHub Desktop.
Save tangxinfa/fd602be16b94ade7ab785dd48f2775d8 to your computer and use it in GitHub Desktop.
mkdir -p implemented in C
#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