-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfileio.c
48 lines (44 loc) · 1.02 KB
/
fileio.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
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
/* reads a binary file into memory */
void *read_file(char *name, size_t *length) {
void *mem = NULL;
FILE *fh = NULL;
struct stat s;
size_t len;
if (!stat(name, &s)) {
if (S_ISDIR(s.st_mode)) {
errno = EISDIR;
}
else {
len = (size_t) s.st_size;
if ((mem = malloc(len)) &&
(fh = fopen(name, "rb")) &&
fread(mem, 1, len, fh) == len)
{
if (length) *length = len;
fclose(fh);
return mem;
}
}
}
if (mem) free(mem);
if (fh) fclose(fh);
perror(name);
return NULL;
}
/* writes binary data to disk */
int write_file(char *name, void *mem, size_t length) {
FILE *fh;
int ok = 0;
if ((fh = fopen(name, "wb"))) {
ok = (fwrite(mem, 1, length, fh) == length);
fclose(fh);
}
if (!ok) {
perror(name);
}
return ok;
}