-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrawfile.c
89 lines (74 loc) · 1.98 KB
/
rawfile.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __APPLE__
#include "macos_endian.h"
#else
#include <endian.h>
#endif
#include <rawfile.h>
#ifdef DEBUG
#include <printhex.h>
#endif
int RAWFILE_Read(const char *path, void **rawdata, size_t *size)
{
FILE *file;
// open file
file = fopen(path, "rb");
if(file == NULL)
{
fprintf(stderr, "Opening \"%s\" failed with error \"%s\"\n", path, strerror(errno));
return RAWFILEERROR_PATHERROR;
}
// get size
long filesize;
fseek(file, 0, SEEK_END); // go to the end of file
filesize = ftell(file); // get position in file
fseek(file, 0, SEEK_SET); // go to the begin of file
if(filesize < 0)
{
fprintf(stderr, "Determine size of file \"%s\" failed with error \"%s\"\n", path, strerror(errno));
return RAWFILEERROR_FATAL;
}
// allocate memory
unsigned char *data;
data = malloc(filesize);
if(data == NULL)
{
fprintf(stderr, "%s, %i: ", __FILE__, __LINE__);
fprintf(stderr, "Fatal Error! - malloc returned NULL!\n");
return RAWFILEERROR_FATAL;
}
// read data
fread(data, 1, filesize, file);
// close file
fclose(file);
file = NULL;
// return everything
if(rawdata)
*rawdata = data;
if(size)
*size = (size_t)filesize;
return RAWFILEERROR_NOERROR;
}
//////////////////////////////////////////////////////////////////////////////
int RAWFILE_Write(const char *path, const void *rawdata, size_t size)
{
FILE *file;
// open file
file = fopen(path, "wb");
if(file == NULL)
{
fprintf(stderr, "Opening \"%s\" failed with error \"%s\"\n", path, strerror(errno));
return RAWFILEERROR_PATHERROR;
}
// read data
fwrite(rawdata, 1, size, file);
// close file
fclose(file);
file = NULL;
return RAWFILEERROR_NOERROR;
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4