-
Notifications
You must be signed in to change notification settings - Fork 1
/
const_recorder.h
75 lines (64 loc) · 1.89 KB
/
const_recorder.h
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
66
67
68
69
70
71
72
73
74
75
#ifndef NEWDATABASE_CONST_RECORDER_H
#define NEWDATABASE_CONST_RECORDER_H
#include <cstdio>
#include <cstring>
#include "constant.h"
#include "constant.h"
namespace sjtu {
class const_recorder {
private:
FILE *fp;
char filename[20];
public:
int append_id;
private:
/**
* create pile file, assume file non-exist.
* write in initial tail_offset as PILE_HEAD_OFFSET. */
void create_file() {
fp = fopen(filename, "w");
append_id = START_USER_ID;
fwrite(&append_id, sizeof(int), 1, fp);
fclose(fp);
}
public:
/** fp and tail_offset's initial values are to show storer is closed. */
const_recorder() {
fp = nullptr;
append_id = -1;
}
~const_recorder() {
if (fp != nullptr)
close_file();
}
void set_filename(const char *name) {
strcpy(filename, name);
}
void increment() {
++append_id;
fseek(fp, 0, SEEK_SET);
fwrite(&append_id, sizeof(int), 1, fp);
}
void open_file() {
fp = fopen(filename, "r+");
// file doesn't exist, then create one.
if (fp == nullptr) {
create_file();
fp = fopen(filename, "r+");
}
fread(&append_id, sizeof(int), 1, fp);
}
/**
* everything is concurrently stored into file without delay
* because this program may be shut down from time to time.
* but I store tail_offset again when closing for carefulness. */
void close_file() {
fseek(fp, 0, SEEK_SET);
fwrite(&append_id, sizeof(int), 1, fp);
fclose(fp);
fp = nullptr;
append_id = -1;
}
};
};
#endif //NEWDATABASE_CONST_RECORDER_H