ptg10805159
762 ADatabase Library Chapter 20
200 if (db->idxbuf != NULL)
201 free(db->idxbuf);
202 if (db->datbuf != NULL)
203 free(db->datbuf);
204 if (db->name != NULL)
205 free(db->name);
206 free(db);
207 }
208 /*
209 * Fetch a record. Return a pointer to the null-terminated data.
210 */
211 char *
212 db_fetch(DBHANDLE h, const char *key)
213 {
214 DB *db = h;
215 char *ptr;
216 if (_db_find_and_lock(db, key, 0) < 0) {
217 ptr=NULL; /* error, record not found */
218 db->cnt_fetcherr++;
219 } else {
220 ptr=_db_readdat(db); /* return pointer to data */
221 db->cnt_fetchok++;
222 }
223 /*
224 * Unlock the hash chain that _db_find_and_lock locked.
225 */
226 if (un_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
227 err_dump("db_fetch: un_lock error");
228 return(ptr);
229 }
[200 – 207] Next, we free any dynamically allocated buffers. Wecan safely pass a null
pointer tofree, so we don’t need to check the value of each buffer pointer
beforehand, but we do so anyway because we consider it better style to free
only those objects that we allocated. (Not all deallocator functions areas
forgiving asfree.) Finally, we freethe memory backing theDBstructure.
[208 – 218] Thedb_fetchfunction is used to read a recordgiven its key.Wefirst try to
find the record by calling_db_find_and_lock.Ifthe recordcan’t be
found, we set the return value (ptr)toNULLand increment the count of
unsuccessful recordsearches. Because_db_find_and_lockreturns with
the database index file locked, we can’t return until we unlock it.
[219 – 229] If the record is found, we call_db_readdatto read the corresponding data
recordand increment the count of the successful recordsearches. Before
returning, we unlock the index file by callingun_lock.Then we return a
pointer to the recordfound (orNULLif the recordwasn’t found).