xref: /csrg-svn/lib/libc/gen/opendir.c (revision 46597)
121350Sdist /*
221350Sdist  * Copyright (c) 1983 Regents of the University of California.
334790Sbostic  * All rights reserved.
434790Sbostic  *
542625Sbostic  * %sccs.include.redist.c%
621350Sdist  */
721350Sdist 
826573Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*46597Sdonn static char sccsid[] = "@(#)opendir.c	5.11 (Berkeley) 02/23/91";
1034790Sbostic #endif /* LIBC_SCCS and not lint */
115750Smckusick 
129142Smckusick #include <sys/param.h>
1336545Smckusick #include <dirent.h>
1438664Smckusick #include <fcntl.h>
15*46597Sdonn #include <stdlib.h>
16*46597Sdonn #include <unistd.h>
175750Smckusick 
1839957Smckusick long _rewinddir;
1938435Smckusick 
205750Smckusick /*
215750Smckusick  * open a directory.
225750Smckusick  */
235750Smckusick DIR *
245750Smckusick opendir(name)
25*46597Sdonn 	const char *name;
265750Smckusick {
276097Smckusic 	register DIR *dirp;
287659Smckusick 	register int fd;
295750Smckusick 
307659Smckusick 	if ((fd = open(name, 0)) == -1)
315750Smckusick 		return NULL;
3238664Smckusick 	if (fcntl(fd, F_SETFD, 1) == -1 ||
3338664Smckusick 	    (dirp = (DIR *)malloc(sizeof(DIR))) == NULL) {
347659Smckusick 		close (fd);
356097Smckusic 		return NULL;
366097Smckusic 	}
3738435Smckusick 	/*
3838435Smckusick 	 * If CLSIZE is an exact multiple of DIRBLKSIZ, use a CLSIZE
3938435Smckusick 	 * buffer that it cluster boundary aligned.
4038435Smckusick 	 * Hopefully this can be a big win someday by allowing page trades
4138435Smckusick 	 * to user space to be done by getdirentries()
4238435Smckusick 	 */
4338435Smckusick 	if ((CLSIZE % DIRBLKSIZ) == 0) {
4438435Smckusick 		dirp->dd_buf = malloc(CLSIZE);
4538435Smckusick 		dirp->dd_len = CLSIZE;
4638435Smckusick 	} else {
4738435Smckusick 		dirp->dd_buf = malloc(DIRBLKSIZ);
4838435Smckusick 		dirp->dd_len = DIRBLKSIZ;
4938435Smckusick 	}
5038435Smckusick 	if (dirp->dd_buf == NULL) {
5138435Smckusick 		close (fd);
5238435Smckusick 		return NULL;
5338435Smckusick 	}
547659Smckusick 	dirp->dd_fd = fd;
555750Smckusick 	dirp->dd_loc = 0;
5638435Smckusick 	dirp->dd_seek = 0;
5739957Smckusick 	/*
5839957Smckusick 	 * Set up seek point for rewinddir.
5939957Smckusick 	 */
6039957Smckusick 	_rewinddir = telldir(dirp);
615750Smckusick 	return dirp;
625750Smckusick }
63