Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Create all directories in path
- * Original code by J Leffler (mkpath.c)
- * http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
- */
- #include <errno.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- static int do_mkdir(const char *path, mode_t mode)
- {
- struct stat st;
- int status = 0;
- if (stat(path, &st) != 0)
- {
- /* Directory does not exist. EEXIST for race condition */
- if (mkdir(path, mode) != 0 && errno != EEXIST)
- {
- status = -1;
- }
- }
- else if (!S_ISDIR(st.st_mode))
- {
- errno = ENOTDIR;
- status = -1;
- }
- return(status);
- }
- /**
- * mkpath - ensure all directories in path exist
- * Algorithm takes the pessimistic view and works top-down to ensure
- * each directory in path exists, rather than optimistically creating
- * the last element and working backwards.
- */
- int mkpath(const char *path, mode_t mode)
- {
- char *pp;
- char *sp;
- int status;
- char *copypath;
- copypath = strdup(path);
- if (copypath == NULL)
- {
- return -1;
- }
- status = 0;
- pp = copypath;
- while (status == 0 && (sp = strchr(pp, '/')) != NULL)
- {
- if (sp != pp)
- {
- /* Neither root nor double slash in path */
- *sp = '\0';
- status = do_mkdir(copypath, mode);
- *sp = '/';
- }
- pp = sp + 1;
- }
- if (status == 0)
- {
- status = do_mkdir(path, mode);
- }
- free(copypath);
- return status;
- }
- #include <stdio.h>
- int main(int argc, char **argv)
- {
- int i;
- int rc;
- if (argc != 2)
- {
- printf("Usage: %s <path>\n", argv[0]);
- return EXIT_FAILURE;
- }
- rc = mkpath(argv[1], 0777);
- if (rc != 0)
- {
- fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
- (int)getpid(), errno, strerror(errno), argv[1]);
- }
- return (rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement