-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutility.c
More file actions
115 lines (100 loc) · 2.25 KB
/
utility.c
File metadata and controls
115 lines (100 loc) · 2.25 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "global.h"
#include "utility.h"
byte *load_binary_file (const char *filename, size_t *len_out)
{
FILE *in = fopen(filename, "rb");
if (!in) return 0;
else {
fseek(in, 0, SEEK_END);
long size = ftell(in);
if (size < 1)
{
fclose(in);
return NULL;
}
byte *dest = calloc(1, size+1);
if (!dest)
{
fclose(in);
return NULL;
}
rewind(in);
int tmp = fread(dest, size, 1, in);
fclose(in);
if (tmp == 1) {
if (len_out) *len_out = size;
return dest;
} else {
free(dest);
return NULL;
}
}
}
int load_binary_data (const char *filename, void *dest, size_t size)
{
FILE *in = fopen(filename, "rb");
if (!in) return 0;
else {
int tmp = fread(dest, size, 1, in);
fclose(in);
return tmp==1;
}
}
int save_binary_data (const char *filename, const void *data, size_t size)
{
FILE *out = fopen(filename, "wb");
if (!out) return 0;
else {
int tmp = fwrite(data, size, 1, out);
fclose(out);
return tmp==1;
}
}
int probe_file (const char *path)
{
struct stat st;
return !stat(path, &st);
}
int probe_regular_file (const char *path)
{
struct stat st;
if (stat(path, &st)) return 0;
else return S_ISREG(st.st_mode);
}
time_t file_write_date (const char *path)
{
struct stat st;
if (!stat(path, &st)) return st.st_mtime;
else return (time_t)0;
}
char *make_absolute_filename (const char *filename)
{
#ifdef _WIN32
printf("FIXME make absolute filename\n");
return strdup(filename);
#else
if (filename[0] == '/') return strdup(filename);
else {
char buf[1024];
// Non standard, but documented to work on OS X and glibc.
char *cwd = getcwd(NULL,0);
snprintf(buf, sizeof(buf), "%s/%s", cwd, filename);
free(cwd);
return strdup(buf);
}
#endif
}
const char *format_binary (byte x)
{
int i;
static char buf[9];
for (i=0; i<8; i++) {
buf[i] = (x & 0x80)? '1' : '0';
x <<= 1;
}
buf[8] = 0;
return buf;
}