ptg10805159
766 ADatabase Library Chapter 20
317 /*
318 * Position index file and record the offset. db_nextrec
319 * calls us with offset==0, meaning read from current offset.
320 * We still need to call lseek to record the current offset.
321 */
322 if ((db->idxoff = lseek(db->idxfd, offset,
323 offset == 0? SEEK_CUR : SEEK_SET)) == -1)
324 err_dump("_db_readidx: lseek error");
325 /*
326 * Read the ascii chain ptr and the ascii length at
327 * the front of the index record. This tells us the
328 * remaining size of the index record.
329 */
330 iov[0].iov_base=asciiptr;
331 iov[0].iov_len =PTR_SZ;
332 iov[1].iov_base=asciilen;
333 iov[1].iov_len =IDXLEN_SZ;
334 if ((i = readv(db->idxfd, &iov[0], 2)) != PTR_SZ + IDXLEN_SZ) {
335 if (i == 0 && offset == 0)
336 return(-1); /* EOF for db_nextrec */
337 err_dump("_db_readidx: readv error of index record");
338 }
339 /*
340 * This is our return value; always >= 0.
341 */
342 asciiptr[PTR_SZ]=0;/*null terminate */
343 db->ptrval=atol(asciiptr); /* offset of next key in chain */
344 asciilen[IDXLEN_SZ]=0;/*null terminate */
345 if ((db->idxlen = atoi(asciilen)) < IDXLEN_MIN ||
346 db->idxlen>IDXLEN_MAX)
347 err_dump("_db_readidx: invalid length");
[317 – 324] We start by seeking to the index file offset provided by the caller.Werecord
the offset in theDBstructure, so even if the caller wants to read the recordat
the current file offset (by settingoffsetto 0), we still need to calllseekto
determine the current offset. Since an index recordwill never be stored at
offset 0 in the index file, we can safely overload the value of 0 to mean ‘‘read
from the current offset.’’
[325 – 338] We callreadvto read the two fixed-length fields at the beginning of the
index record: the chain pointer to the next index recordand the size of the
variable-length index recordthat follows.
[339 – 347] We convert the offset of the next record to an integer and store it in the
ptrvalfield (this will be used as the return value for this function). Then
we convert the length of the index recordinto an integer and save it in the
idxlenfield.