Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

758 ADatabase Library Chapter 20


94 db->nhash =NHASH_DEF;/* hash table size */
95 db->hashoff =HASH_OFF; /* offset in index file of hash table */
96 strcpy(db->name, pathname);
97 strcat(db->name, ".idx");

98 if (oflag & O_CREAT) {
99 va_list ap;

100 va_start(ap, oflag);
101 mode=va_arg(ap, int);
102 va_end(ap);

103 /*
104 * Open index file and data file.
105 */
106 db->idxfd=open(db->name, oflag, mode);
107 strcpy(db->name+len, ".dat");
108 db->datfd=open(db->name, oflag, mode);
109 } else {
110 /*
111 * Open index file and data file.
112 */
113 db->idxfd=open(db->name, oflag);
114 strcpy(db->name+len, ".dat");
115 db->datfd=open(db->name, oflag);
116 }

117 if (db->idxfd < 0 || db->datfd < 0) {
118 _db_free(db);
119 return(NULL);
120 }

[94 – 97] We continue to initialize theDBstructure. The pathname passed in by the
caller specifies the prefix of the database filenames. We append the suffix
.idxto create the name for the database index file.
[98 – 108] If the caller wants to create the database files, we use the variable argument
functions from<stdarg.h>to find the optional thirdargument. Then we
useopento create and open the index file and data file. Note that the
filename of the data file starts with the same prefix as the index file but has
.datas a suffix instead.
[109 – 116] If the caller doesn’t specify theO_CREATflag, then we’reopening existing
database files. In this case, we simply callopenwith two arguments.
[117 – 120] If an error occurs while we areopening or creating either database file, we
call_db_freeto clean up theDBstructureand then returnNULLto the
caller.Ifoneopensucceeded and one failed,_db_freewill take careof
closing the open file descriptor, as we shall see shortly.
Free download pdf