forked from EmK530/ConMIDI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBufferFile.c
109 lines (107 loc) · 2.27 KB
/
BufferFile.c
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <windows.h>
FILE *midi;
char *buffer;
size_t bufRange = 0;
unsigned long int bufSize = 0;
long long bufPos = 0;
long long filePos = 0;
long long curSeek = 0;
char *pathSave;
BOOL fileEnded = FALSE;
void BufferInit(char path[], unsigned long seek, unsigned int bufSizee)
{
bufSize = bufSizee;
pathSave = path;
midi = fopen(path, "rb");
if (midi == NULL)
{
perror("Could not open file path");
return;
}
buffer = malloc(bufSize);
bufRange = fread(buffer, 1, bufSize, midi);
curSeek += filePos + bufRange;
fileEnded = (bufRange != bufSize);
}
void UpdateBuffer()
{
if (!fileEnded)
{
filePos += bufPos;
fseeko(midi, filePos - curSeek, SEEK_CUR);
bufRange = fread(buffer, 1, bufSize, midi);
curSeek = filePos + bufRange;
fileEnded = (bufRange != bufSize);
bufPos = 0;
}
}
void Seek(long long pos)
{
int cond = pos - filePos >= bufRange;
bufPos = pos - filePos;
if (cond)
{
UpdateBuffer();
}
}
int Pushback = -1;
void Skip(unsigned long int count)
{
for (unsigned long int i = 0; i < count; i++)
{
if (Pushback != -1)
{
Pushback = -1;
}
if (bufPos >= bufRange)
{
UpdateBuffer();
}
bufPos++;
}
}
void ResizeBuffer(unsigned long int size)
{
bufSize = size;
free(buffer);
buffer = malloc(size);
UpdateBuffer();
}
unsigned char ReadFast()
{
if (bufPos >= bufRange)
{
UpdateBuffer();
}
bufPos++;
return buffer[bufPos - 1];
}
unsigned char *ReadRange(int size)
{
if (bufPos + size >= bufRange)
{
UpdateBuffer();
}
unsigned char *range = malloc(size + 1);
for (int i = 0; i < size; i++)
{
*(range + i) = *(buffer + bufPos + i);
}
range[size] = '\0';
bufPos += size;
return range;
}
void Copy(unsigned char *target, unsigned long int offset, unsigned long int size)
{
if (bufPos + size >= bufRange)
{
UpdateBuffer();
}
if (size == 0)
{
size = bufSize;
}
memcpy(target + offset, buffer + bufPos, size);
bufPos += size;
}