-
Notifications
You must be signed in to change notification settings - Fork 0
/
BGM_FileManager.cpp
94 lines (84 loc) · 2.05 KB
/
BGM_FileManager.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "BGM_FileManager.h"
namespace BGM
{
FileManager::FileManager(const char* fileName)
{
if(!(file=fopen(fileName, "rb+")))
{
file = fopen(fileName, "wb+");
numberOfBlock = 0;
currentBlock = 0;
nextBlock = 1;
lastBlock = 0;
}
else
{
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
numberOfBlock = *((unsigned*)(buffer + NUMBEROFBLOCK_OFFSET));
currentBlock = *((unsigned*)(buffer + CURRENTBLOCK_OFFSET));
nextBlock = *((unsigned*)(buffer+NEXTBLOCK_OFFSET));
lastBlock = *((unsigned*)(buffer+LASTBLOCK_OFFSET));
loadBlock(currentBlock);
}
}
FileManager::~FileManager(void)
{
storeBlock(currentBlock);
fseek(file, 0, SEEK_SET);
fwrite(&numberOfBlock, 4, 1, file);
fwrite(¤tBlock, 4, 1, file);
fwrite(&nextBlock, 4, 1, file);
fwrite(&lastBlock, 4, 1, file);
fclose(file);
}
blockId_t FileManager::newBlock(void)
{
int result = nextBlock;
numberOfBlock++;
if(numberOfBlock > lastBlock)
{
lastBlock++;
nextBlock = lastBlock+1;
}
else
{
fseek(file, nextBlock*BLOCKSIZE, SEEK_SET);
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
nextBlock = *((blockId_t*)buffer);
}
return result;
}
void FileManager::loadBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fread_s(buffer, BLOCKSIZE, BLOCKSIZE, 1, file);
currentBlock = id;
}
void FileManager::loadBlock(blockId_t id, void *externalBuffer)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fread_s(externalBuffer, BLOCKSIZE, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(void)
{
fseek(file, currentBlock*BLOCKSIZE, SEEK_SET);
fwrite(buffer, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(buffer, BLOCKSIZE, 1, file);
}
void FileManager::storeBlock(blockId_t id, void *externalBuffer)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(externalBuffer, BLOCKSIZE, 1, file);
}
void FileManager::deleteBlock(blockId_t id)
{
fseek(file, id*BLOCKSIZE, SEEK_SET);
fwrite(&nextBlock, 4, 1, file);
nextBlock = id;
numberOfBlock--;
}
}