Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

760 ADatabase Library Chapter 20


138 hash[0]=0;
139 for (i = 0; i < NHASH_DEF + 1; i++)
140 strcat(hash, asciiptr);
141 strcat(hash, "\n");
142 i =strlen(hash);
143 if (write(db->idxfd, hash, i) != i)
144 err_dump("db_open: index file init write error");
145 }
146 if (un_lock(db->idxfd, 0, SEEK_SET, 0) < 0)
147 err_dump("db_open: un_lock error");
148 }
149 db_rewind(db);
150 return(db);
151 }
152 /*
153 * Allocate & initialize a DB structure and its buffers.
154 */
155 static DB *
156 _db_alloc(int namelen)
157 {
158 DB *db;
159 /*
160 * Use calloc, to initialize the structure to zero.
161 */
162 if ((db = calloc(1, sizeof(DB))) == NULL)
163 err_dump("_db_alloc: calloc error for DB");
164 db->idxfd=db->datfd = -1; /* descriptors */
165 /*
166 * Allocate room for the name.
167 * +5 for ".idx" or ".dat" plus null at end.
168 */
169 if ((db->name = malloc(namelen + 5)) == NULL)
170 err_dump("_db_alloc: malloc error for name");

[138 – 151] We continue to initialize the newly created database. We build the hash
table and write it to the index file. Then we unlock the index file, reset the
database file pointers, and return a pointer to theDBstructureasthe opaque
handle for the caller to use with the other database functions.
[152 – 164] The_db_allocfunction is called bydb_opento allocate storage for theDB
structure, an index buffer,and a data buffer.Weusecallocto allocate
memory to hold theDBstructureand ensurethat it is initialized to all zeros.
Since this has the side effect of setting the database file descriptors to zero,
we need to reset them to−1 to indicate that they arenot yet valid.
[165 – 170] We allocate space to hold the name of the database file.We use this buffer to
create both filenames by changing the suffix to refer to either the index file or
the data file, as we saw indb_open.
Free download pdf