Browse Source

std_utils - templatize file_read_bin() / file_write_bin

LIB-18
heck 11 months ago
parent
commit
b41bba4143
3 changed files with 36 additions and 28 deletions
  1. +0
    -26
      src/std_utils.cc
  2. +6
    -2
      src/std_utils.hh
  3. +30
    -0
      src/std_utils.hxx

+ 0
- 26
src/std_utils.cc View File

@ -158,32 +158,6 @@ namespace pEp {
return ss.str();
}
std::vector<char> file_read_bin(const std::string &filename)
{
std::vector<char> ret{};
if (pEp::Utils::path_exists(filename)) {
std::ifstream ifs(filename, std::ios_base::binary);
ifs.unsetf(std::ios_base::skipws);
if (ifs.bad()) {
throw std::runtime_error("failed to read file: '" + filename + "'");
}
ret = { std::istream_iterator<char>(ifs), std::istream_iterator<char>() };
} else {
throw std::runtime_error("File does not exist: '" + filename + "'");
}
return ret;
}
void file_write_bin(const std::string &filename, std::vector<char> &data)
{
std::fstream f(filename, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
f.write(data.data(), static_cast<std::streamsize>(data.size()));
if (f.bad()) {
throw std::runtime_error("failed to write file: '" + filename + "'");
}
}
#ifndef WIN32
void path_ensure_not_existing(const string &path)
{


+ 6
- 2
src/std_utils.hh View File

@ -41,8 +41,12 @@ namespace pEp {
// file
std::ofstream file_create(const std::string &filename);
std::string file_read(const std::string &filename);
std::vector<char> file_read_bin(const std::string& filename);
void file_write_bin(const std::string& filename, std::vector<char>& data);
template<typename T = char>
std::vector<T> file_read_bin(const std::string& filename);
template<typename T = char>
void file_write_bin(const std::string& filename, std::vector<T>& data);
// dir
#ifndef WIN32


+ 30
- 0
src/std_utils.hxx View File

@ -5,6 +5,7 @@
#define LIBPEPADAPTER_STD_UTILS_HXX
#include <sstream>
#include <fstream>
namespace pEp {
namespace Utils {
@ -17,6 +18,35 @@ namespace pEp {
}
return ss.str();
}
template<typename T>
std::vector<T> file_read_bin(const std::string &filename)
{
std::vector<T> ret{};
if (pEp::Utils::path_exists(filename)) {
std::ifstream ifs(filename, std::ios_base::binary);
ifs.unsetf(std::ios_base::skipws);
if (ifs.bad()) {
throw std::runtime_error("failed to read file: '" + filename + "'");
}
ret = { std::istream_iterator<T>(ifs), std::istream_iterator<T>() };
} else {
throw std::runtime_error("File does not exist: '" + filename + "'");
}
return ret;
}
template<typename T>
void file_write_bin(const std::string &filename, std::vector<T> &data)
{
std::fstream f(filename, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
f.write(data.data(), static_cast<std::streamsize>(data.size()));
if (f.bad()) {
throw std::runtime_error("failed to write file: '" + filename + "'");
}
}
} // namespace Utils
} // namespace pEp
#endif // LIBPEPADAPTER_STD_UTILS_HXX

Loading…
Cancel
Save