Add function for reading the whole file in one go

This commit is contained in:
Moritz Bunkus 2012-08-26 14:27:29 +02:00
parent f225d01d4f
commit 985211760f
5 changed files with 35 additions and 0 deletions

View File

@ -161,6 +161,16 @@ mm_file_io_c::prepare_path(const std::string &path) {
throw mtx::mm_io::create_directory_x(path, strerror(error_code.value()), error_code.value());
}
memory_cptr
mm_file_io_c::slurp(std::string const &file_name) {
mm_file_io_c in(file_name, MODE_READ);
auto content = memory_c::alloc(in.get_size());
if (in.get_size() != in.read(content, in.get_size()))
throw mtx::mm_io::end_of_file_x{};
return content;
}
uint64
mm_file_io_c::getFilePointer() {
return m_current_position;

View File

@ -216,6 +216,7 @@ public:
virtual ~mm_file_io_c();
static void prepare_path(const std::string &path);
static memory_cptr slurp(std::string const &file_name);
virtual uint64 getFilePointer();
#if defined(SYS_WINDOWS)

View File

@ -0,0 +1,17 @@
#include "common/common_pch.h"
#include "gtest/gtest.h"
#include "tests/unit/util.h"
namespace {
TEST(MmIo, Slurp) {
memory_cptr m;
ASSERT_NO_THROW(m = mm_file_io_c::slurp("tests/unit/data/text/chunky_bacon.txt"));
EXPECT_EQ(*m, std::string{"Chunky Bacon\n"});
ASSERT_THROW(mm_file_io_c::slurp("doesnotexist"), mtx::mm_io::exception);
}
}

View File

@ -0,0 +1 @@
Chunky Bacon

View File

@ -51,4 +51,10 @@ public:
}
inline bool
operator ==(memory_c const &a,
std::string const &b) {
return (a.get_size() == b.length()) && !memcmp(a.get_buffer(), b.c_str(), b.length());
}
#endif // MTX_TESTS_UNIT_UTIL_H