ack/lang/cem/libcc.ansi/misc/opendir.c

67 lines
1.4 KiB
C
Raw Normal View History

1989-12-18 14:40:54 +00:00
/*
opendir -- open a directory stream
last edit: 16-Jun-1987 D A Gwyn
*/
2018-06-21 20:33:47 +00:00
#include <errno.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
typedef void* pointer; /* (void *) if you have it */
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
extern int _open(const char* path, int flags, int mode);
extern int _close(int d);
2018-06-21 20:33:47 +00:00
extern int _fstat(int fd, struct stat* buf);
1989-12-18 14:40:54 +00:00
#ifndef NULL
2018-06-21 20:33:47 +00:00
#define NULL 0
1989-12-18 14:40:54 +00:00
#endif
#ifndef O_RDONLY
2018-06-21 20:33:47 +00:00
#define O_RDONLY 0
1989-12-18 14:40:54 +00:00
#endif
2018-06-21 20:33:47 +00:00
#ifndef S_ISDIR /* macro to test for directory file */
#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
1989-12-18 14:40:54 +00:00
#endif
2018-06-21 20:33:47 +00:00
DIR* opendir(const char* dirname) /* name of directory */
1989-12-18 14:40:54 +00:00
{
2018-06-21 20:33:47 +00:00
register DIR* dirp; /* -> malloc'ed storage */
register int fd; /* file descriptor for read */
struct stat sbuf; /* result of fstat() */
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
if ((fd = _open(dirname, O_RDONLY, 0)) < 0)
return NULL; /* errno set by open() */
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
if (_fstat(fd, &sbuf) != 0 || !S_ISDIR(sbuf.st_mode))
{
(void)_close(fd);
1989-12-18 14:40:54 +00:00
errno = ENOTDIR;
2018-06-21 20:33:47 +00:00
return NULL; /* not a directory */
}
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
if ((dirp = (DIR*)malloc(sizeof(DIR))) == NULL
|| (dirp->dd_buf = (char*)malloc((unsigned)DIRBUF)) == NULL)
{
register int serrno = errno;
/* errno set to ENOMEM by sbrk() */
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
if (dirp != NULL)
free((pointer)dirp);
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
(void)_close(fd);
1989-12-18 14:40:54 +00:00
errno = serrno;
2018-06-21 20:33:47 +00:00
return NULL; /* not enough memory */
}
1989-12-18 14:40:54 +00:00
dirp->dd_fd = fd;
2018-06-21 20:33:47 +00:00
dirp->dd_loc = dirp->dd_size = 0; /* refill needed */
1989-12-18 14:40:54 +00:00
return dirp;
}