-
Notifications
You must be signed in to change notification settings - Fork 2
/
file.c
55 lines (43 loc) · 874 Bytes
/
file.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
#include "file.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void fload(void *ptr, size_t size, FILE *stream)
{
if (fread(ptr, 1, size, stream) < size) {
abort();
}
}
void fsave(void *ptr, size_t size, FILE *stream)
{
if (fwrite(ptr, 1, size, stream) < size) {
abort();
}
}
size_t fsize(FILE *stream)
{
long begin = ftell(stream);
if (begin == (long)-1) {
fprintf(stderr, "Stream is not seekable\n");
abort();
}
if (fseek(stream, 0, SEEK_END)) {
abort();
}
long end = ftell(stream);
if (end == (long)-1) {
abort();
}
if (fseek(stream, begin, SEEK_SET)) {
abort();
}
return (size_t)end - (size_t)begin;
}
FILE *force_fopen(const char *pathname, const char *mode, int force)
{
if (force == 0 && access(pathname, F_OK) != -1) {
fprintf(stderr, "File already exists\n");
abort();
}
return fopen(pathname, mode);
}