-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_util.c
129 lines (96 loc) · 1.67 KB
/
test_util.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
int create_file_with_contents(char *fname, unsigned char *data, int len)
{
FILE *f = fopen(fname, "wb");
int ret;
if (!f)
return -1;
ret = fwrite(data, 1, len, f);
if (ret != len)
return -1;
ret = fclose(f);
if (ret != 0)
return -1;
return 0;
}
int get_file_contents(char *fname, unsigned char **pbuf, int *plen)
{
FILE *f = fopen(fname, "rb");
int ret;
long fsize;
unsigned char *fdata;
if (!f)
return -1;
fseek(f, 0, SEEK_END);
fsize = ftell(f);
fseek(f, 0, SEEK_SET);
if (fsize == -1)
goto out;
fdata = malloc(fsize);
if (!fdata)
goto out;
ret = fread(fdata, 1, fsize, f);
if (ret != fsize)
goto out_free;
ret = fclose(f);
if (ret != 0)
goto out_free;
*pbuf = fdata;
*plen = fsize;
return 0;
out_free:
free(fdata);
out:
return -1;
}
int compare_file(char *fname, unsigned char *buf, int len)
{
unsigned char *fdata;
int flen;
int ret;
ret = get_file_contents(fname, &fdata, &flen);
if (ret < 0)
return 0;
if (len != flen) {
free(fdata);
return 0;
}
if (memcmp(fdata, buf, len)) {
free(fdata);
return 0;
}
free(fdata);
return 1;
}
int file_exists(char *fname)
{
struct stat st;
return stat(fname, &st) == 0;
}
int file_size(char *fname)
{
FILE *f = fopen(fname, "rb");
long fsize;
if (!f)
return -1;
fseek(f, 0, SEEK_END);
fsize = ftell(f);
fclose(f);
return fsize;
}
void fail_if(int cond, char *file, int line, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (cond) {
fprintf(stderr, "%s:%d: ", file, line);
vfprintf(stderr, fmt, ap);
fflush(stderr);
exit(1);
}
va_end(ap);
}