-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_helper.cpp
61 lines (45 loc) · 1.28 KB
/
file_helper.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
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "file_helper.h"
int FileHelper::open_input(const char *filename) {
input_fd = open(filename, O_RDONLY);
if(input_fd == -1) {
throw runtime_error(format("Error opening {}\n", filename));
}
#ifdef LINUX
if(posix_fadvise(input_fd, 0, 0, POSIX_FADV_SEQUENTIAL) != 0) {
perror("Error advising for sequential access (proceeding anyway)");
}
#endif /* LINUX */
return input_fd;
}
void FileHelper::close_input() {
close(input_fd);
}
int FileHelper::open_output(const char *filename) {
output_fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY | O_APPEND, 0644);
if(output_fd == -1) {
throw runtime_error(format("Error opening {}\n", filename));
exit(EXIT_FAILURE);
}
if(output_buffer == nullptr) {
output_buffer = new char[FileHelper::OUTPUT_BUFFER_LENGTH];
}
return output_fd;
}
void FileHelper::close_output() {
if(output_buffer != nullptr) {
flush_data(output_buffer, output_buffer_watermark);
}
output_buffer_watermark = 0;
}
FileHelper::FileHelper(): input_fd{-1}, output_fd{-1}, output_buffer{nullptr}, output_buffer_watermark{0UL} {
}
FileHelper::~FileHelper() {
if(output_buffer != nullptr) {
delete output_buffer;
}
output_buffer = nullptr;
}