ptg10805159
768 ADatabase Library Chapter 20
377 /*
378 * Read the current data record into the data buffer.
379 * Return a pointer to the null-terminated data buffer.
380 */
381 static char *
382 _db_readdat(DB *db)
383 {
384 if (lseek(db->datfd, db->datoff, SEEK_SET) == -1)
385 err_dump("_db_readdat: lseek error");
386 if (read(db->datfd, db->datbuf, db->datlen) != db->datlen)
387 err_dump("_db_readdat: read error");
388 if (db->datbuf[db->datlen-1] != NEWLINE) /* sanity check */
389 err_dump("_db_readdat: missing newline");
390 db->datbuf[db->datlen-1] = 0; /* replace newline with null */
391 return(db->datbuf); /* return pointer to data record */
392 }
393 /*
394 * Delete the specified record.
395 */
396 int
397 db_delete(DBHANDLE h, const char *key)
398 {
399 DB *db = h;
400 int rc=0;/*assume record will be found */
401 if (_db_find_and_lock(db, key, 1) == 0) {
402 _db_dodelete(db);
403 db->cnt_delok++;
404 } else {
405 rc=-1; /* not found */
406 db->cnt_delerr++;
407 }
408 if (un_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
409 err_dump("db_delete: un_lock error");
410 return(rc);
411 }
[377 – 392] The_db_readdatfunction populates thedatbuffield in theDBstructure
with the contents of the data record, expecting that thedatoffanddatlen
fields will have been properly initialized already.
[393 – 411] Thedb_deletefunction is used to delete a recordgiven its key.Weuse
_db_find_and_lock to determine whether the recordexists in the
database. If it does, we call_db_dodeleteto do the work needed to delete
the record. The thirdargument to_db_find_and_lockcontrols whether
the chain is read locked or write locked. Here we are requesting a write
lock, since we will potentially change the list. Since_db_find_and_lock
returns with the lock still held, we need to unlock it, regardless of whether
the recordwas found.