-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuffer.c
More file actions
58 lines (52 loc) · 990 Bytes
/
buffer.c
File metadata and controls
58 lines (52 loc) · 990 Bytes
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
#include "buffer.h"
#include <stdio.h>
#include <stdlib.h>
int alloc_buffer(struct Buffer *buff, unsigned int size)
{
buff->mem = malloc(size);
if (!buff->mem)
return -1;
buff->max = size;
buff->used = 0;
return 0;
}
void free_buffer(struct Buffer *buff)
{
if (buff->mem)
{
free(buff->mem);
buff->mem = NULL;
buff->used = 0;
buff->max = 0;
}
}
int read_file_to_buffer(char *filename, struct Buffer *buff)
{
FILE *input = fopen(filename, "rb");
if (NULL == input)
{
return -1;
}
fseek(input, 0, SEEK_END);
int size_to_read = ftell(input);
if (size_to_read <= buff->max)
{
fseek(input, 0, SEEK_SET);
buff->used = size_to_read;
fread(buff->mem, buff->used, 1, input);
fclose(input);
return 0;
}
else
{
printf("BUFFER ISSUES! FIX ME!\n");
fclose(input);
return -2;
}
}
int write_buffer_to_file(char *filename, const struct Buffer *buff)
{
FILE *output = fopen(filename, "wb");
fwrite(buff->mem, buff->used, 1, output);
fclose(output);
}