-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
64 lines (49 loc) · 1.19 KB
/
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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "logger.h"
#include "util.h"
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a > b ? b : a; }
int rand_num(int l, int h, unsigned int seed) {
assert(l <= h);
srand((unsigned int)time(NULL) * seed);
return l + (rand() % (h - l + 1));
}
int bound(int n, int l, int h) {
assert(l <= h);
return min(max(n, l), h);
}
long file_size(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL)
return -1;
if (fseek(fp, 0, SEEK_END) != 0) {
fclose(fp);
return -1;
}
long size = ftell(fp);
fclose(fp);
return size;
}
bool is_little_endian(void) {
int num = 1;
return (*(unsigned char *)&num == 1);
}
#ifdef __TEST__
#include <unistd.h>
void util_test(void) {
assert(max(1, 2) == 2);
assert(min(1, 2) == 1);
assert(bound(2, 1, 3) == 2);
assert(bound(-1, 1, 3) == 1);
assert(bound(4, 1, 3) == 3);
for (unsigned int i = 0; i < 100; i++) {
int n = rand_num(1, 10, i);
assert(n >= 1 && n <= 10);
usleep(1 * 1000);
}
debug("util_test() Ok");
}
#endif