1 /* 2 * Copyright (c) 1983, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)telldir.c 8.1 (Berkeley) 06/04/93"; 10 #endif /* LIBC_SCCS and not lint */ 11 12 #include <sys/param.h> 13 #include <dirent.h> 14 #include <stdlib.h> 15 #include <unistd.h> 16 17 /* 18 * The option SINGLEUSE may be defined to say that a telldir 19 * cookie may be used only once before it is freed. This option 20 * is used to avoid having memory usage grow without bound. 21 */ 22 #define SINGLEUSE 23 24 /* 25 * One of these structures is malloced to describe the current directory 26 * position each time telldir is called. It records the current magic 27 * cookie returned by getdirentries and the offset within the buffer 28 * associated with that return value. 29 */ 30 struct ddloc { 31 struct ddloc *loc_next;/* next structure in list */ 32 long loc_index; /* key associated with structure */ 33 long loc_seek; /* magic cookie returned by getdirentries */ 34 long loc_loc; /* offset of entry in buffer */ 35 }; 36 37 #define NDIRHASH 32 /* Num of hash lists, must be a power of 2 */ 38 #define LOCHASH(i) ((i)&(NDIRHASH-1)) 39 40 static long dd_loccnt; /* Index of entry for sequential readdir's */ 41 static struct ddloc *dd_hash[NDIRHASH]; /* Hash list heads for ddlocs */ 42 43 /* 44 * return a pointer into a directory 45 */ 46 long telldir(dirp)47telldir(dirp) 48 const DIR *dirp; 49 { 50 register int index; 51 register struct ddloc *lp; 52 53 if ((lp = (struct ddloc *)malloc(sizeof(struct ddloc))) == NULL) 54 return (-1); 55 index = dd_loccnt++; 56 lp->loc_index = index; 57 lp->loc_seek = dirp->dd_seek; 58 lp->loc_loc = dirp->dd_loc; 59 lp->loc_next = dd_hash[LOCHASH(index)]; 60 dd_hash[LOCHASH(index)] = lp; 61 return (index); 62 } 63 64 /* 65 * seek to an entry in a directory. 66 * Only values returned by "telldir" should be passed to seekdir. 67 */ 68 void _seekdir(dirp,loc)69_seekdir(dirp, loc) 70 register DIR *dirp; 71 long loc; 72 { 73 register struct ddloc *lp; 74 register struct ddloc **prevlp; 75 struct dirent *dp; 76 77 prevlp = &dd_hash[LOCHASH(loc)]; 78 lp = *prevlp; 79 while (lp != NULL) { 80 if (lp->loc_index == loc) 81 break; 82 prevlp = &lp->loc_next; 83 lp = lp->loc_next; 84 } 85 if (lp == NULL) 86 return; 87 if (lp->loc_loc == dirp->dd_loc && lp->loc_seek == dirp->dd_seek) 88 goto found; 89 (void) lseek(dirp->dd_fd, (off_t)lp->loc_seek, SEEK_SET); 90 dirp->dd_seek = lp->loc_seek; 91 dirp->dd_loc = 0; 92 while (dirp->dd_loc < lp->loc_loc) { 93 dp = readdir(dirp); 94 if (dp == NULL) 95 break; 96 } 97 found: 98 #ifdef SINGLEUSE 99 *prevlp = lp->loc_next; 100 free((caddr_t)lp); 101 #endif 102 } 103