Skip to content

Commit 20c4482

Browse files
committed
ADD: utils functions for simple file operations
1 parent 1d429e9 commit 20c4482

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

utils/utils.h

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//
2+
// Created by user on 26.05.2020.
3+
//
4+
5+
#ifndef FORDTOOLS_UTILS_H
6+
#define FORDTOOLS_UTILS_H
7+
8+
#include <string>
9+
#include <filesystem>
10+
#include <fstream>
11+
#include <vector>
12+
13+
namespace fs = std::filesystem;
14+
15+
namespace FTUtils {
16+
17+
inline void bufferToFile(const std::string& file_name, char *data_ptr, int data_len) {
18+
19+
std::ofstream out_file(file_name, std::ios::out | std::ios::binary);
20+
if (!out_file) {
21+
throw std::runtime_error("file " + file_name + " can't be created");
22+
} else {
23+
out_file.write(data_ptr, data_len);
24+
}
25+
out_file.close();
26+
}
27+
28+
inline void fileToVector(const fs::path& file_path, std::vector<uint8_t>& data) {
29+
30+
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
31+
if(file.fail()) {
32+
throw std::runtime_error("Can't open file '" + file_path.string() + "'");
33+
}
34+
auto file_sz = file.tellg();
35+
file.seekg(0, std::ios::beg);
36+
37+
data.resize(file_sz);
38+
if (!file.read(reinterpret_cast<char *>(data.data()), file_sz)) {
39+
throw std::runtime_error("Can't read file '" + file_path.string() + "'");
40+
}
41+
42+
file.close();
43+
}
44+
45+
}
46+
47+
#endif //FORDTOOLS_UTILS_H

0 commit comments

Comments
 (0)