Untabify.
[glibc.git] / sysdeps / unix / readdir.c
blob491469bcd1d3944d513fcd217fd54b028240cb1e
1 /* Copyright (C) 1991, 92, 93, 94, 95, 96 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA. */
19 #include <errno.h>
20 #include <limits.h>
21 #include <stddef.h>
22 #include <string.h>
23 #include <dirent.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <assert.h>
28 #include <dirstream.h>
31 /* Read a directory entry from DIRP. */
32 struct dirent *
33 __readdir (DIR *dirp)
35 struct dirent *dp;
37 if (dirp == NULL || dirp->data == NULL)
39 __set_errno (EINVAL);
40 return NULL;
43 __libc_lock_lock (dirp->lock);
47 size_t reclen;
49 if (dirp->offset >= dirp->size)
51 /* We've emptied out our buffer. Refill it. */
53 size_t maxread;
54 off_t base;
55 ssize_t bytes;
57 #ifndef _DIRENT_HAVE_D_RECLEN
58 /* Fixed-size struct; must read one at a time (see below). */
59 maxread = sizeof *dp;
60 #else
61 maxread = dirp->allocation;
62 #endif
64 base = dirp->filepos;
65 bytes = __getdirentries (dirp->fd, dirp->data, maxread, &base);
66 if (bytes <= 0)
68 dp = NULL;
69 break;
71 dirp->size = (size_t) bytes;
73 /* Reset the offset into the buffer. */
74 dirp->offset = 0;
77 dp = (struct dirent *) &dirp->data[dirp->offset];
79 #ifdef _DIRENT_HAVE_D_RECLEN
80 reclen = dp->d_reclen;
81 #else
82 /* The only version of `struct dirent' that lacks `d_reclen'
83 is fixed-size. */
84 assert (sizeof dp->d_name > 1);
85 reclen = sizeof *dp;
86 /* The name is not terminated if it is the largest possible size.
87 Clobber the following byte to ensure proper null termination. We
88 read jst one entry at a time above so we know that byte will not
89 be used later. */
90 dp->d_name[sizeof dp->d_name] = '\0';
91 #endif
93 dirp->offset += reclen;
95 #ifdef _DIRENT_HAVE_D_OFF
96 dirp->filepos = dp->d_off;
97 #else
98 dirp->filepos += reclen;
99 #endif
101 /* Skip deleted files. */
102 } while (dp->d_ino == 0);
104 __libc_lock_unlock (dirp->lock);
106 return dp;
108 weak_alias (__readdir, readdir)