barretenberg
Loading...
Searching...
No Matches
file_io.hpp
1#pragma once
2#include <barretenberg/common/log.hpp>
3#include <cstdint>
4#include <fstream>
5#include <ios>
6#include <vector>
7
8inline size_t get_file_size(std::string const& filename)
9{
10 // Open the file in binary mode and move to the end.
11 std::ifstream file(filename, std::ios::binary | std::ios::ate);
12 if (!file) {
13 return 0;
14 }
15
16 file.seekg(0, std::ios::end);
17 return (size_t)file.tellg();
18}
19
20inline std::vector<uint8_t> read_file(const std::string& filename, size_t bytes = 0)
21{
22 // Get the file size.
23 auto size = get_file_size(filename);
24 if (size <= 0) {
25 throw std::runtime_error("File is empty or there's an error reading it: " + filename);
26 }
27
28 auto to_read = bytes == 0 ? size : bytes;
29
30 std::ifstream file(filename, std::ios::binary);
31 if (!file) {
32 throw std::runtime_error("Unable to open file: " + filename);
33 }
34
35 // Create a vector with enough space for the file data.
36 std::vector<uint8_t> fileData(to_read);
37
38 // Read all its contents.
39 file.read(reinterpret_cast<char*>(fileData.data()), (std::streamsize)to_read);
40
41 return fileData;
42}
43
44inline void write_file(const std::string& filename, std::vector<uint8_t> const& data)
45{
46 std::ofstream file(filename, std::ios::binary);
47 if (!file) {
48 throw std::runtime_error("Failed to open data file for writing");
49 }
50 file.write((char*)data.data(), (std::streamsize)data.size());
51 file.close();
52}