aboutsummaryrefslogtreecommitdiff
path: root/src/utility.h
blob: 9c88b3821c40555fb9cfcd64548db2cc6acbabd7 (plain)
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
#ifndef UTILITY_H_
#define UTILITY_H_

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <cstddef>
#include <cstdio>

namespace {

const int OpenFlags   = O_RDONLY;
const mode_t OpenMode = S_IRUSR | S_IWUSR;

}

std::string readFile(const std::string& path) {
	int descriptor(
		open(path.data(), OpenFlags, OpenMode)
	);

	if ( descriptor == -1 ) {
		close(descriptor);

		return "io error";
	} else {
		struct stat info;
		fstat(descriptor, &info);
		const std::size_t size(info.st_size);

		char* buffer(new char[size]);

		ssize_t readSize(read(
			descriptor,
			reinterpret_cast<void*>(buffer),
			size
		));

		close(descriptor);

		std::string content(
			buffer,
			readSize
		);

		delete[] buffer;

		return content;
	}
}

#endif  // UTILITY_H_