xref: /original-bsd/lib/libc/gen/opendir.c (revision 33586e34)
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 #if defined(LIBC_SCCS) && !defined(lint)
19 static char sccsid[] = "@(#)opendir.c	5.7 (Berkeley) 08/17/89";
20 #endif /* LIBC_SCCS and not lint */
21 
22 #include <sys/param.h>
23 #include <dirent.h>
24 #include <fcntl.h>
25 
26 char *malloc();
27 
28 /*
29  * open a directory.
30  */
31 DIR *
32 opendir(name)
33 	char *name;
34 {
35 	register DIR *dirp;
36 	register int fd;
37 	register int i;
38 
39 	if ((fd = open(name, 0)) == -1)
40 		return NULL;
41 	if (fcntl(fd, F_SETFD, 1) == -1 ||
42 	    (dirp = (DIR *)malloc(sizeof(DIR))) == NULL) {
43 		close (fd);
44 		return NULL;
45 	}
46 	/*
47 	 * If CLSIZE is an exact multiple of DIRBLKSIZ, use a CLSIZE
48 	 * buffer that it cluster boundary aligned.
49 	 * Hopefully this can be a big win someday by allowing page trades
50 	 * to user space to be done by getdirentries()
51 	 */
52 	if ((CLSIZE % DIRBLKSIZ) == 0) {
53 		dirp->dd_buf = malloc(CLSIZE);
54 		dirp->dd_len = CLSIZE;
55 	} else {
56 		dirp->dd_buf = malloc(DIRBLKSIZ);
57 		dirp->dd_len = DIRBLKSIZ;
58 	}
59 	if (dirp->dd_buf == NULL) {
60 		close (fd);
61 		return NULL;
62 	}
63 	dirp->dd_fd = fd;
64 	dirp->dd_loc = 0;
65 	dirp->dd_seek = 0;
66 	return dirp;
67 }
68