xref: /original-bsd/bin/mkdir/mkdir.c (revision 10020db5)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)mkdir.c	5.5 (Berkeley) 03/05/90";
26 #endif /* not lint */
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <strings.h>
33 
34 extern int errno;
35 
36 main(argc, argv)
37 	int argc;
38 	char **argv;
39 {
40 	extern int optind;
41 	int ch, exitval, pflag;
42 
43 	pflag = 0;
44 	while ((ch = getopt(argc, argv, "p")) != EOF)
45 		switch(ch) {
46 		case 'p':
47 			pflag = 1;
48 			break;
49 		case '?':
50 		default:
51 			usage();
52 		}
53 
54 	if (!*(argv += optind))
55 		usage();
56 
57 	for (exitval = 0; *argv; ++argv)
58 		if (pflag)
59 			exitval |= build(*argv);
60 		else if (mkdir(*argv, 0777) < 0) {
61 			(void)fprintf(stderr, "mkdir: %s: %s\n",
62 			    *argv, strerror(errno));
63 			exitval = 1;
64 		}
65 	exit(exitval);
66 }
67 
68 build(path)
69 	char *path;
70 {
71 	register char *p;
72 	struct stat sb;
73 	int create, ch;
74 
75 	for (create = 0, p = path;; ++p)
76 		if (!*p || *p  == '/') {
77 			ch = *p;
78 			*p = '\0';
79 			if (stat(path, &sb)) {
80 				if (errno != ENOENT || mkdir(path, 0777) < 0) {
81 					(void)fprintf(stderr, "mkdir: %s: %s\n",
82 					    path, strerror(errno));
83 					return(1);
84 				}
85 				create = 1;
86 			}
87 			if (!(*p = ch))
88 				break;
89 		}
90 	if (!create) {
91 		(void)fprintf(stderr, "mkdir: %s: %s\n", path,
92 		    strerror(EEXIST));
93 		return(1);
94 	}
95 	return(0);
96 }
97 
98 usage()
99 {
100 	(void)fprintf(stderr, "usage: mkdir [-p] dirname ...\n");
101 	exit(1);
102 }
103