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