Created
March 25, 2011 05:07
-
-
Save athurg/886391 to your computer and use it in GitHub Desktop.
a example code for gdbm using
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* db_add.c: storing | |
written by rock <[email protected]>, 1999.11.29 | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <gdbm.h> | |
#define datum_set(um, buf) { um.dptr = buf; um.dsize = strlen(buf); } | |
int db_ls(char *dbname) { | |
GDBM_FILE dbf; | |
datum key, next, data; | |
int n = 1; | |
dbf = gdbm_open(dbname, 0, GDBM_READER, 0, NULL); | |
if(!dbf) { | |
printf("%s\n", gdbm_strerror(gdbm_errno)); | |
return 1; | |
} | |
key = gdbm_firstkey(dbf); | |
while( key.dptr ) { | |
data = gdbm_fetch(dbf, key); | |
printf("(%d) %s:\t%s\n", n++, key.dptr, data.dptr); | |
next = gdbm_nextkey(dbf, key); | |
free(key.dptr); | |
key = next; | |
} | |
gdbm_close(dbf); | |
return 0; | |
} | |
int db_rm(char *dbname) | |
{ | |
GDBM_FILE dbf; | |
char keyb[256]; | |
datum key; | |
dbf = gdbm_open(dbname, 0, GDBM_WRITER, 0, NULL); | |
if( !dbf ) { | |
printf("%s\n", gdbm_strerror(gdbm_errno)); | |
return 1; | |
} | |
puts("Input key: "); | |
gets(keyb); | |
key.dptr = keyb; key.dsize = strlen(keyb); | |
if(gdbm_delete(dbf, key)) { | |
printf("%s\n", gdbm_strerror(gdbm_errno)); | |
gdbm_close(dbf); | |
return 1; | |
} | |
puts("Removing record successed\n"); | |
gdbm_close(dbf); | |
return 0; | |
} | |
int db_add(char *dbname) { | |
char keyb[256], datab[256]; | |
GDBM_FILE dbf; | |
datum key, data; | |
if( !(dbf = gdbm_open(dbname, 0, GDBM_WRCREAT, 0644, NULL)) ) { | |
printf("%s\n", gdbm_strerror(gdbm_errno)); | |
return 1; | |
} | |
puts("Input key: "); | |
gets(keyb); | |
puts("Input data: "); | |
gets(datab); | |
datum_set(key, keyb); | |
datum_set(data, datab); | |
if( gdbm_store(dbf, key, data, GDBM_INSERT) ) { | |
printf("%s\nRecord may be exist.\n", gdbm_strerror(gdbm_errno)); | |
gdbm_close(dbf); | |
return 1; | |
} | |
puts("Storing record successed.\n"); | |
gdbm_close(dbf); | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
char keyb[256], datab[256], *dbname; | |
GDBM_FILE dbf; | |
datum key, data; | |
if( argc < 3) { | |
printf("Usage: %s add/ls/rm <dbname>\n", argv[0]); | |
return 1; | |
} | |
if (!strcmp(argv[1], "add")){ | |
db_add(argv[2]); | |
} else if (!strcmp(argv[1], "ls")){ | |
db_ls(argv[2]); | |
} else if (!strcmp(argv[1], "rm")){ | |
db_rm(argv[2]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment