-
Notifications
You must be signed in to change notification settings - Fork 0
/
leveldb.cpp
65 lines (61 loc) · 1.48 KB
/
leveldb.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// leveldb
// https://github.com/google/leveldb/blob/master/doc/index.md
//
#include <iostream>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
//
int
main(int argc, char** argv)
{
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
// open
auto status = leveldb::DB::Open(options, ".testdb", &db);
if (!status.ok())
{
std::cerr << status.ToString() << std::endl;
return 1;
}
if (argc > 1)
{
leveldb::Slice key1 = argv[1];
std::string value;
auto s = db->Get(leveldb::ReadOptions(), key1, &value);
if (s.ok())
{
std::cout << key1.ToString() << ": " << value << std::endl;
}
else if (argc > 2)
{
value = argv[2];
auto s = db->Put(leveldb::WriteOptions(), key1, value);
if (!s.ok())
{
std::cerr << "key[" << key1.ToString() << "]: write failed." << std::endl;
return 1;
}
std::cout << "key[" << key1.ToString() << "]: write value<" << value << ">" << std::endl;
}
else
{
std::cerr << "key[" << key1.ToString() << "]: not found." << std::endl;
}
return 0;
}
// list
int ret = 0;
auto it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
std::cout << it->key().ToString() << ": " << it->value().ToString() << std::endl;
}
if (it->status().ok())
{
std::cerr << it->status().ToString() << std::endl;
ret = 1;
}
delete it;
return ret;
}