xref: /csrg-svn/lib/libc/gen/opendir.c (revision 39957)
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.8 (Berkeley) 01/30/90";
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 long _rewinddir;
28 
29 /*
30  * open a directory.
31  */
32 DIR *
33 opendir(name)
34 	char *name;
35 {
36 	register DIR *dirp;
37 	register int fd;
38 	register int i;
39 
40 	if ((fd = open(name, 0)) == -1)
41 		return NULL;
42 	if (fcntl(fd, F_SETFD, 1) == -1 ||
43 	    (dirp = (DIR *)malloc(sizeof(DIR))) == NULL) {
44 		close (fd);
45 		return NULL;
46 	}
47 	/*
48 	 * If CLSIZE is an exact multiple of DIRBLKSIZ, use a CLSIZE
49 	 * buffer that it cluster boundary aligned.
50 	 * Hopefully this can be a big win someday by allowing page trades
51 	 * to user space to be done by getdirentries()
52 	 */
53 	if ((CLSIZE % DIRBLKSIZ) == 0) {
54 		dirp->dd_buf = malloc(CLSIZE);
55 		dirp->dd_len = CLSIZE;
56 	} else {
57 		dirp->dd_buf = malloc(DIRBLKSIZ);
58 		dirp->dd_len = DIRBLKSIZ;
59 	}
60 	if (dirp->dd_buf == NULL) {
61 		close (fd);
62 		return NULL;
63 	}
64 	dirp->dd_fd = fd;
65 	dirp->dd_loc = 0;
66 	dirp->dd_seek = 0;
67 	/*
68 	 * Set up seek point for rewinddir.
69 	 */
70 	_rewinddir = telldir(dirp);
71 	return dirp;
72 }
73