Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 20.3 The Library 745


#include "apue_db.h"
DBHANDLE db_open(const char *pathname,intoflag,... /* intmode*/);
Returns: database handle if OK,NULLon error
void db_close(DBHANDLEdb);
Ifdb_openis successful, two files arecreated: pathname.idxis the index file, and
pathname.datis the data file. Theoflagargument is used as the second argument toopen
(Section 3.3) to specify how the files are to be opened (e.g., read-only,read–write, create
file if it doesn’t exist). Themodeargument is used as the thirdargument toopen(the
file access permissions) if the database files arecreated.
When we’redone with a database, we calldb_close.Itcloses the index file and
the data file and releases any memory that it allocated for internal buffers.
When we storeanew record in the database, we have to specify the key for the
recordand the data associated with the key.Ifthe database contained personnel
records, the key could be the employee ID, and the data could be the employee’s name,
address, telephone number,date of hire, and the like. Our implementation requires that
the key for each record be unique. (Wecan’t have two employee records with the same
employee ID, for example.)
#include "apue_db.h"
int db_store(DBHANDLEdb,const char *key,const char *data,
intflag);
Returns: 0 if OK, nonzero on error (see following)
Thekeyanddataarguments arenull-terminated character strings. The only restriction
on these two strings is that neither can contain null bytes. They may,for example,
contain newlines.
Theflagargument can beDB_INSERT(to insert a new record),DB_REPLACE(to
replace an existing record), orDB_STORE(to either insert or replace a record, whichever
is appropriate). These three constants aredefined in theapue_db.hheader.Ifwe
specify eitherDB_INSERTorDB_STOREand the recorddoes not exist, a new recordis
inserted. If we specify eitherDB_REPLACEorDB_STOREand the recordalready exists,
the existing record is replaced with the new record. If we specifyDB_REPLACEand the
recorddoesn’t exist, we seterrnotoENOENTand return−1without adding the new
record. If we specifyDB_INSERTand the recordalready exists, no record is inserted. In
this case, the return value is 1 to distinguish it from a normal error return(− 1 ).
We can fetch any recordfromthe database by specifying itskey.
#include "apue_db.h"
char *db_fetch(DBHANDLEdb,const char *key);
Returns: pointer to data if OK,NULLif recordnot found
The return value is a pointer to the data that was stored with thekey, if the recordis
found. Wecan also delete a recordfromthe database by specifying itskey.
Free download pdf