Skip to content

Commit

Permalink
Util: Fix reading binary files
Browse files Browse the repository at this point in the history
  • Loading branch information
Riyyi committed Sep 26, 2022
1 parent 6cd2fe4 commit 50fe09e
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/ruc/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#include <cstdint> // int32_t
#include <filesystem>
#include <fstream> // std::ifstream, std::ofstream
#include <memory> // std::make_shared, std::shared_ptr
#include <memory> // std::make_shared, std::make_unique, std::shared_ptr
#include <string>
#include <string_view>

Expand All @@ -19,7 +19,21 @@ namespace ruc {
File::File(std::string_view path)
: m_path(path)
{
m_data = std::string(File::raw(path).get());
// Create input stream object and open file
std::ifstream file(path.data());
VERIFY(file.is_open(), "failed to open file: '{}'", path);

// Get length of the file
int32_t size = File::length(path, file);

// Allocate memory filled with zeros
auto buffer = std::make_unique<char[]>(size);

// Fill buffer with file contents
file.read(buffer.get(), size);
file.close();

m_data = std::string(buffer.get(), size);
}

File::~File()
Expand Down Expand Up @@ -47,6 +61,7 @@ int32_t File::length(std::string_view path, std::ifstream& file)
return length;
}

// FIXME: Deduplicate code with constructor, this broke binary files only
std::shared_ptr<char[]> File::raw(std::string_view path)
{
// Create input stream object and open file
Expand Down

0 comments on commit 50fe09e

Please sign in to comment.