files created with "makedbm" can not used with "dbm_fetch"

files created with "makedbm" can not used with "dbm_fetch"

Post by Michael Wa » Tue, 18 May 1999 04:00:00



I created a dbm file:

[julie:/export/home/root/C]echo a b | makedbm - db

I then wrote a C program to read it:

[julie:/export/home/root/C]more query_dbm.c
#include <ndbm.h>
#include <stdio.h>
#include <fcntl.h>

#define NAME    "a"
#define DB_NAME "db"

main()
{
DBM *db;
datum name = {NAME, sizeof (NAME)};
datum val;

db = dbm_open(DB_NAME, O_RDONLY, 0600);
val = dbm_fetch(db, name);
(void) printf("Name: %s, Value: %s\n", name.dptr, val.dptr);
dbm_close(db);
return (0);

Quote:}

But it cannot:

[julie:/export/home/root/C]gcc query_dbm.c
[julie:/export/home/root/C]./a.out                
Segmentation Fault(coredump)

What is the deal? Thanks.
--
Michael Wang
http://www.mindspring.com/~mwang

 
 
 

files created with "makedbm" can not used with "dbm_fetch"

Post by Casper H.S. Dik - Network Security Engine » Tue, 18 May 1999 04:00:00


[[ PLEASE DON'T SEND ME EMAIL COPIES OF POSTINGS ]]


>I created a dbm file:
>[julie:/export/home/root/C]echo a b | makedbm - db
>I then wrote a C program to read it:
>[julie:/export/home/root/C]more query_dbm.c
>val = dbm_fetch(db, name);

This returns NUL.  You're looking for an item w/ key "a\0"
and a dsize of 2; makedbm stores it as "a", dsize = 1.

Makedbm does not 0 terminate its items, use the following:

#include <ndbm.h>
#include <stdio.h>
#include <fcntl.h>

#define NAME    "a"
#define DB_NAME "db"

main()
{
    DBM *db;
    datum name = {NAME, sizeof(NAME)-1};  /* Actually, strlen(NAME) */
    datum val;

    db = dbm_open(DB_NAME, O_RDONLY, 0600);
    val = dbm_fetch(db, name);
    /* Print with length of field limited to "dsize" */
    (void) printf("Name: %.*s, Value: %.*s\n", name.dsize, name.dptr,
            val.dsize, val.dptr);
    dbm_close(db);
    return (0);

Quote:}

--
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.