-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.h
58 lines (51 loc) · 1.36 KB
/
file.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
53
54
55
56
57
58
#ifndef SIK_UDP_FILE_READER_H
#define SIK_UDP_FILE_READER_H
#include <string>
#include <stdexcept>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
class File {
private:
/// File descriptor
int file;
public:
/**
* Opens file descriptor in read only mode.
* @param filename file to open.
* @throws std::invalid_argument when file cannot be opened
*/
File(const std::string &filename) {
if ((file = open(filename.c_str(), O_RDONLY)) == -1) {
throw std::invalid_argument("Could not open file");
}
}
/**
* Reads file content.
* @return file content.
* @throws std::runtime_error if reading file returns an error
*/
std::string read_content() const {
char buffer[64 * 1024u];
std::string content;
ssize_t length;
do {
length = read(file, buffer, sizeof(buffer) - 1);
if (length < 0) {
throw std::runtime_error("Error reading file");
}
buffer[length] = '\0';
content.append(buffer);
} while (length > 0);
return std::move(content);
}
/**
* Destroys file instance. Closes the descriptor.
*/
~File() {
if (close(file) == -1) {
std::cerr << "Error closing file" << std::endl;
}
}
};
#endif //SIK_UDP_FILE_READER_H