1

Off lately I am working with Berkeley DB. I have seen examples wherein people have used "string" as values to "key.data" while creating a database using Berkeley DB. I want to assign an integer value to it. How can I do that? Should I create a structure with int member in it or is there any other way possible?

DBT key, data;
memset(&key, 0, sizeof(key));
memset(&data, 0, sizeof(data));
key.data = "fruit";
key.size = sizeof("fruit");

So instead of "fruit" above I want to assign an integer value. Any kind of help would be appreciated.

1 Answer 1

2

DBT structures provide a void * field that you use to point to your data, and another field that identifies the data length. They can therefore be used to store anything from simple primitive data to complex structures so long as the information you want to store resides in a single contiguous block of memory.

See, http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/DBEntry.html

To store integers, you would assign a pointer to an int to key.data, e.g.:

int x = 42;
key.data = &x;
key.size = sizeof(x);
Sign up to request clarification or add additional context in comments.

4 Comments

Won't that cause problems if you read the database file on a system with different byte ordering?
@bromfiets: i used the method you showed above....but when I am trying to print it....it returns me a different value if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0) { printf("db: %d: key stored.\n", (char*)&key.data);}
@user537670 With &key.data you are taking the address of the pointer key.data. This is not necessary. key.data is already a pointer; cast it to be a pointer to an int and deference it, for example printf("key: %d\n", *(int *) key.data);
@Keith Yes it does. You would have to take care of byte ordering in the application, e.g. always read and write in a certain byte order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.