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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "memory.h"
#include "buffer.h"
struct buffer buffer_make(size_t capacity) {
struct buffer buffer = (struct buffer){malloc(capacity, char), capacity + 1, 0};
return buffer;
}
void buffer_free(struct buffer buffer) {
free(buffer.buf);
}
void buffer_append_mem(struct buffer *buffer, const char *str, size_t len) {
if (buffer->len + len >= buffer->cap) {
do buffer->cap *= 2; while (buffer->len + len >= buffer->cap);
buffer->buf = realloc(buffer->buf, buffer->cap, char);
}
memcpy(buffer->buf + buffer->len, str, len);
buffer->len += len;
buffer->buf[buffer->len] = 0;
}
void buffer_append_str(struct buffer *buffer, const char *str) {
buffer_append_mem(buffer, str, strlen(str));
}
// returns whether successful
bool buffer_append_file(struct buffer *buffer, const char *path) {
FILE *f = fopen(path, "rb");
if (!f) return false;
char block[4096];
while (true) {
size_t nr = fread(block, 1, sizeof block, f);
if (nr > 0) buffer_append_mem(buffer, block, nr);
if (nr < sizeof block) break;
}
bool has_error = ferror(f);
fclose(f);
return !has_error;
}
|