Euphoria
io.cc
Go to the documentation of this file.
1 #include "io/io.h"
2 
3 #include "log/log.h"
4 
5 #include "base/cint.h"
6 
7 #include <fstream>
8 
9 
10 namespace eu::io
11 {
12  void
14  (
15  std::shared_ptr<MemoryChunk> chunk,
16  const std::string& full_path
17  )
18  {
19  std::ofstream file_handle(full_path, std::ios::binary | std::ios::out);
20  if(!file_handle.good())
21  {
22  LOG_ERROR("Failed to open file for writing: {0}", full_path);
23  return;
24  }
25  file_handle.write(chunk->get_data(), chunk->get_size());
26  }
27 
28  namespace
29  {
30  int c_postype_to_int(std::ifstream::pos_type p)
31  {
32  return static_cast<int>(p);
33  }
34  }
35 
36  std::shared_ptr<MemoryChunk>
37  read_file_to_chunk(const std::string& full_path)
38  {
39  std::ifstream is(full_path, std::ifstream::binary);
40  if(!is)
41  {
42  // this is actually not a error since other files might be later on in the vfs
43  // test running test3d for a example where it tries to load real files over virtual ones
44  // LOG_ERROR("Failed to read real file " << full_path);
45  return MemoryChunk::create_null();
46  }
47 
48  is.seekg(0, std::ifstream::end);
49  const auto length = is.tellg();
50  is.seekg(0, std::ifstream::beg);
51 
52  if(length <= 0)
53  {
54  return MemoryChunk::create_null();
55  }
56 
57  auto memory = MemoryChunk::allocate(c_postype_to_int(length));
58  is.read
59  (
60  static_cast<char*>(static_cast<void*>(memory->get_data())),
61  memory->get_size()
62  );
63 
64  return memory;
65  }
66 
67  std::optional<std::string>
68  read_file_to_string(const std::string& full_path)
69  {
70  std::ifstream in(full_path, std::ios::in | std::ios::binary);
71  if (!in) { return std::nullopt; }
72 
73  std::string contents;
74  in.seekg(0, std::ios::end);
75  const auto file_size = in.tellg();
76  contents.resize(file_size);
77  in.seekg(0, std::ios::beg);
78  in.read(contents.data(), file_size);
79  in.close();
80  return(contents);
81  }
82 }
#define LOG_ERROR(...)
Definition: log.h:9
constexpr unit3f in
Definition: vec3.h:135
constexpr unit3f out
Definition: vec3.h:136
Definition: enum.h:8
std::shared_ptr< MemoryChunk > read_file_to_chunk(const std::string &full_path)
Definition: io.cc:37
void write_chunk_to_file(std::shared_ptr< MemoryChunk > chunk, const std::string &full_path)
Definition: io.cc:14
std::optional< std::string > read_file_to_string(const std::string &full_path)
Definition: io.cc:68
static std::shared_ptr< MemoryChunk > allocate(int size)
Definition: memorychunk.cc:40
static std::shared_ptr< MemoryChunk > create_null()
Definition: memorychunk.cc:47