-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesize.h
52 lines (45 loc) · 879 Bytes
/
filesize.h
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
#ifndef __FILESIZE_H_
#define __FILESIZE_H_
#include <unistd.h>
#include <err.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
static inline off_t
alignup(off_t off, unsigned bits)
{
off_t mask = (1ULL << bits)-1;
return (off + mask) & (~mask);
}
static inline off_t
aligndown(off_t off, unsigned bits)
{
return off & ~((1ULL << bits) - 1);
}
static inline off_t
fgetsize(int fd)
{
struct stat st;
off_t out = 0;
if (fstat(fd, &st) < 0)
err(1, "fstat %d", fd);
out = st.st_size;
if (!out && st.st_rdev) {
out = ioctl(fd, BLKGETSIZE64, &out) == 0 ? out : 0;
}
return out;
}
static inline off_t
getsize(const char *path)
{
off_t out;
int fd = open(path, O_RDONLY);
if (fd < 0)
err(1, "open %s", path);
out = fgetsize(fd);
close(fd);
return out;
}
#endif