Update.
[glibc.git] / sysdeps / unix / readdir_r.c
blobd2f97357b454e9ffa5e91a8a36f0b2c2c301ab92
1 /* Copyright (C) 1991,92,93,94,95,96,97,98 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 not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, 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 int
33 __readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result)
35 struct dirent *dp;
36 size_t reclen;
38 __libc_lock_lock (dirp->lock);
42 if (dirp->offset >= dirp->size)
44 /* We've emptied out our buffer. Refill it. */
46 size_t maxread;
47 off_t base;
48 ssize_t bytes;
50 #ifndef _DIRENT_HAVE_D_RECLEN
51 /* Fixed-size struct; must read one at a time (see below). */
52 maxread = sizeof *dp;
53 #else
54 maxread = dirp->allocation;
55 #endif
57 base = dirp->filepos;
58 bytes = __getdirentries (dirp->fd, dirp->data, maxread, &base);
59 if (bytes <= 0)
61 dp = NULL;
62 /* Reclen != 0 signals that an error occurred. */
63 reclen = bytes != 0;
64 break;
66 dirp->size = (size_t) bytes;
68 /* Reset the offset into the buffer. */
69 dirp->offset = 0;
72 dp = (struct dirent *) &dirp->data[dirp->offset];
74 #ifdef _DIRENT_HAVE_D_RECLEN
75 reclen = dp->d_reclen;
76 #else
77 /* The only version of `struct dirent' that lacks `d_reclen'
78 is fixed-size. */
79 assert (sizeof dp->d_name > 1);
80 reclen = sizeof *dp;
81 /* The name is not terminated if it is the largest possible size.
82 Clobber the following byte to ensure proper null termination. We
83 read just one entry at a time above so we know that byte will not
84 be used later. */
85 dp->d_name[sizeof dp->d_name] = '\0';
86 #endif
88 dirp->offset += reclen;
90 #ifdef _DIRENT_HAVE_D_OFF
91 dirp->filepos = dp->d_off;
92 #else
93 dirp->filepos += reclen;
94 #endif
96 /* Skip deleted files. */
97 } while (dp->d_ino == 0);
99 if (dp != NULL)
100 *result = memcpy (entry, dp, reclen);
101 else
102 *result = NULL;
104 __libc_lock_unlock (dirp->lock);
106 return dp != NULL ? 0 : reclen ? errno : 0;
108 weak_alias (__readdir_r, readdir_r)