-
Notifications
You must be signed in to change notification settings - Fork 75
/
fileio_linux.cpp
65 lines (52 loc) · 1.22 KB
/
fileio_linux.cpp
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
#include "fileio.h"
#include <cstdio>
#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>
#include <ftw.h>
#include <unistd.h>
using std::cerr;
using std::endl;
bool IsDirectory(const char* path) {
struct stat sb;
if (!stat(path, &sb))
return (sb.st_mode & S_IFDIR) != 0;
return false;
}
// traverse directory and call callback() for each file
void TraversePath(const char* dir, int callback(const char* file_path, const struct stat* sb, int typeflag)) {
if (!IsDirectory(dir)) {
callback(dir, nullptr, FTW_F);
return;
}
if (ftw(dir, callback, 16))
perror("ftw");
}
File::File(const char* filepath) {
fd_ = open(filepath, O_RDWR);
if (fd_ == -1) {
perror("Open file error");
return;
}
struct stat sb;
if (fstat(fd_, &sb) == -1) {
perror("fstat");
return;
}
size_ = sb.st_size;
// map the file into memory
fp_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
if (fp_ == MAP_FAILED) {
perror("Map file error");
fp_ = nullptr;
}
}
void File::UnMapFile(size_t new_size) {
if (munmap(fp_, size_) == -1)
perror("munmap");
if (new_size)
if (ftruncate(fd_, new_size) == -1)
perror("ftruncate");
close(fd_);
fp_ = nullptr;
}