-
Notifications
You must be signed in to change notification settings - Fork 3
/
buffer.c
38 lines (33 loc) · 821 Bytes
/
buffer.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
#include <stdio.h>
typedef struct {
char *base;
unsigned int capacity;
unsigned int bytesRead;
} Buffer;
Buffer allocBuffer(int initCapacity) {
return (Buffer){
.base = malloc(initCapacity),
.capacity = initCapacity,
.bytesRead = 0,
};
}
void growBuffer(Buffer *buf, int newSize) {
if (buf->capacity >= newSize) {
return;
}
buf->base = realloc(buf->base, newSize);
buf->capacity = newSize;
}
Buffer readIntoBuffer(FILE *file) {
int n;
Buffer buf = allocBuffer(10);
while ((n = fread(buf.base + buf.bytesRead, sizeof(char),
buf.capacity - buf.bytesRead, file)) > 0) {
buf.bytesRead += n;
if (buf.bytesRead == buf.capacity) {
growBuffer(&buf, buf.capacity * 2);
}
}
return buf;
}
void freeBuffer(Buffer *buf) { free(buf->base); }