xref: /original-bsd/bin/mkdir/mkdir.c (revision e59fb703)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)mkdir.c	5.7 (Berkeley) 05/31/90";
16 #endif /* not lint */
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 
24 extern int errno;
25 
26 main(argc, argv)
27 	int argc;
28 	char **argv;
29 {
30 	extern int optind;
31 	int ch, exitval, pflag;
32 
33 	pflag = 0;
34 	while ((ch = getopt(argc, argv, "p")) != EOF)
35 		switch(ch) {
36 		case 'p':
37 			pflag = 1;
38 			break;
39 		case '?':
40 		default:
41 			usage();
42 		}
43 
44 	if (!*(argv += optind))
45 		usage();
46 
47 	for (exitval = 0; *argv; ++argv)
48 		if (pflag)
49 			exitval |= build(*argv);
50 		else if (mkdir(*argv, 0777) < 0) {
51 			(void)fprintf(stderr, "mkdir: %s: %s\n",
52 			    *argv, strerror(errno));
53 			exitval = 1;
54 		}
55 	exit(exitval);
56 }
57 
58 build(path)
59 	char *path;
60 {
61 	register char *p;
62 	struct stat sb;
63 	int create, ch;
64 
65 	for (create = 0, p = path;; ++p)
66 		if (!*p || *p  == '/') {
67 			ch = *p;
68 			*p = '\0';
69 			if (stat(path, &sb)) {
70 				if (errno != ENOENT || mkdir(path, 0777) < 0) {
71 					(void)fprintf(stderr, "mkdir: %s: %s\n",
72 					    path, strerror(errno));
73 					return(1);
74 				}
75 				create = 1;
76 			}
77 			if (!(*p = ch))
78 				break;
79 		}
80 	if (!create) {
81 		(void)fprintf(stderr, "mkdir: %s: %s\n", path,
82 		    strerror(EEXIST));
83 		return(1);
84 	}
85 	return(0);
86 }
87 
88 usage()
89 {
90 	(void)fprintf(stderr, "usage: mkdir [-p] dirname ...\n");
91 	exit(1);
92 }
93