load_string and save_string in separate files

This commit is contained in:
Patrick Urbanke
2023-10-14 18:59:54 +02:00
parent b9dca17ccb
commit a0d17bd3c5
4 changed files with 62 additions and 23 deletions
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_LOAD_STRING_HPP_
#define RFL_IO_LOAD_STRING_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<std::string> load_string(const std::string& _fname) {
std::ifstream infile(_fname);
if (infile.is_open()) {
auto r = std::string(std::istreambuf_iterator<char>(infile),
std::istreambuf_iterator<char>());
infile.close();
return r;
} else {
return Error("Unable to open file '" + _fname +
"' or file could not be found.");
}
}
} // namespace io
} // namespace rfl
#endif
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_SAVE_STRING_HPP_
#define RFL_IO_SAVE_STRING_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<Nothing> save_string(const std::string& _fname,
const std::string& _str) {
try {
std::ofstream outfile;
outfile.open(_fname);
outfile << _str;
outfile.close();
} catch (std::exception& e) {
return Error(e.what());
}
return Nothing{};
}
} // namespace io
} // namespace rfl
#endif
+2 -14
View File
@@ -1,11 +1,8 @@
#ifndef RFL_JSON_LOAD_HPP_
#define RFL_JSON_LOAD_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
#include "rfl/io/load_string.hpp"
#include "rfl/json/read.hpp"
namespace rfl {
@@ -13,16 +10,7 @@ namespace json {
template <class T>
Result<T> load(const std::string& _fname) {
std::ifstream infile(_fname);
if (infile.is_open()) {
auto r = read<T>(std::string(std::istreambuf_iterator<char>(infile),
std::istreambuf_iterator<char>()));
infile.close();
return r;
} else {
return Error("Unable to open file '" + _fname +
"' or file could not be found.");
}
return rfl::io::load_string(_fname).and_then(read<T>);
}
} // namespace json
+2 -9
View File
@@ -6,6 +6,7 @@
#include <string>
#include "rfl/Result.hpp"
#include "rfl/io/save_string.hpp"
#include "rfl/json/write.hpp"
namespace rfl {
@@ -13,15 +14,7 @@ namespace json {
template <class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
try {
std::ofstream outfile;
outfile.open(_fname);
outfile << write(_obj);
outfile.close();
} catch (std::exception& e) {
return Error(e.what());
}
return Nothing{};
return rfl::io::save_string(write(_obj));
}
} // namespace json