ocarina/tests/src/db_entry.cpp

109 lines
1.6 KiB
C++

/*
* Copyright 2014 (c) Anna Schumaker.
* Test a DatabaseEntry
*/
#include <database.h>
#include <file.h>
#include <print.h>
#include <string>
#include <stdlib.h>
#include <unistd.h>
enum action_t { PRIMARY_KEY, PRINT, READ, WRITE };
class IntEntry : public DatabaseEntry {
public:
unsigned int val;
std::string key;
IntEntry(unsigned int, const std::string &);
const std::string primary_key();
void write(File &);
void read(File &);
void print();
};
IntEntry :: IntEntry(unsigned int i, const std::string &s)
{
val = i;
key = s;
}
const std::string IntEntry :: primary_key()
{
return key;
}
void IntEntry :: write(File &f)
{
f << val << " " << key;
}
void IntEntry :: read(File &f)
{
f >> val >> key;
}
void IntEntry :: print()
{
:: print("Value: %u Key: %s Valid: %d\n", val, key.c_str(), valid);
}
int main(int argc, char **argv)
{
action_t action = PRINT;
char c;
while ((c = getopt(argc, argv, "prw")) != -1) {
switch (c) {
case 'p':
action = PRIMARY_KEY;
break;
case 'r':
action = READ;
break;
case 'w':
action = WRITE;
break;
}
}
if (optind >= argc) {
print("ERROR: Not enough arguments\n");
return 1;
}
unsigned int i = atoi(argv[optind++]);
std::string key = argv[optind];
File f("db_entry.txt", FILE_TYPE_DATA);
IntEntry ient(i, key);
switch (action) {
case PRIMARY_KEY:
print("Primary key: %s\n", ient.primary_key().c_str());
break;
case PRINT:
ient.print();
break;
case READ:
f.open(OPEN_READ);
ient.read(f);
ient.print();
f.close();
break;
case WRITE:
f.open(OPEN_WRITE);
ient.write(f);
f.close();
break;
}
return 0;
}