* sysdeps/mach/hurd/dirstream.h: Define `struct __dirstream'
[glibc.git] / sysdeps / unix / bsd / telldir.c
blobdbab289a37fbe8fc440d67bdbe9092146535a55e
1 /* Copyright (C) 1994, 1995 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 <ansidecl.h>
20 #include <errno.h>
21 #include <stddef.h>
22 #include <dirent.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <stdlib.h>
26 #include "dirstream.h"
28 /* Internal data structure for telldir and seekdir. */
29 struct record
31 struct record *next; /* Link in chain. */
32 off_t cookie; /* Value returned by `telldir'. */
33 off_t pos;
34 size_t offset;
36 #define NBUCKETS 32
37 static struct record *records[32];
38 static off_t lastpos;
41 /* Return the current position of DIRP. */
42 off_t
43 DEFUN(telldir, (dirp), DIR *dirp)
45 struct record *new;
47 new = malloc (sizeof *new);
48 if (new == NULL)
49 return (off_t) -1;
51 new->pos = dirp->__pos;
52 new->offset = dirp->__offset;
53 new->cookie = ++lastpos;
54 new->next = records[new->cookie % NBUCKETS];
55 records[new->cookie % NBUCKETS] = new;
57 return new->cookie;
62 /* Seek to position POS in DIRP. */
63 void
64 DEFUN(seekdir, (dirp, pos), DIR *dirp AND __off_t pos)
66 struct record *r, **prevr;
68 for (prevr = &records[pos % NBUCKETS], r = *prevr;
69 r != NULL;
70 prevr = &r->next, r = r->next)
71 if (r->cookie == pos)
73 if (dirp->__pos != r->pos || dirp->__offset != r->offset)
75 dirp->__size = 0; /* Must read a fresh buffer. */
76 /* Move to the saved position. */
77 __lseek (dirp->__fd, r->pos, SEEK_SET);
78 dirp->__pos = r->pos;
79 dirp->__offset = 0;
80 /* Read entries until we reach the saved offset. */
81 while (dirp->__offset < r->offset)
82 if (readdir (dirp) == NULL)
83 break;
86 /* To prevent leaking memory, cookies returned from telldir
87 can only be used once. So free this one's record now. */
88 *prevr = r->next;
89 free (r);
90 return;
93 /* We lost, but have no way to indicate it. Oh well. */