| #include "proto_reader.h" | |
| #include <cerrno> | |
| #include <cstring> | |
| #include <filesystem> // NOLINT(build/c++17) | |
| #include <fstream> | |
| #include <ios> | |
| #include <iterator> | |
| #include <string> | |
| #include "absl/log/log.h" | |
| #include "absl/status/status.h" | |
| #include "absl/status/statusor.h" | |
| #include "absl/strings/string_view.h" | |
| namespace proto_reader { | |
| absl::StatusOr<std::string> ReadFileToString( | |
| const std::filesystem::path& file_name) { | |
| std::ifstream f(file_name.c_str(), std::ios_base::in | std::ios::binary); | |
| if (!f.is_open()) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "read: Failed to open file " << file_name << " " << st_err; | |
| return absl::InvalidArgumentError("read: Failed to open file"); | |
| } | |
| std::string content{std::istreambuf_iterator<char>(f), | |
| std::istreambuf_iterator<char>()}; | |
| if (!f) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "read: Failed to read file " << file_name << " " << st_err; | |
| return absl::UnavailableError("read: Failed to read file"); | |
| } | |
| f.close(); | |
| if (!f) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "read: Failed to close file " << file_name << " " << st_err; | |
| return absl::UnavailableError("read: Failed to close file"); | |
| } | |
| return content; | |
| } | |
| absl::Status WriteFileToString(const std::filesystem::path& file_name, | |
| absl::string_view content) { | |
| std::ofstream f(file_name.c_str(), std::ios_base::out | std::ios::binary); | |
| if (!f.is_open()) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "write: Failed to open file " << file_name << " " << st_err; | |
| return absl::InvalidArgumentError("write: Failed to open file"); | |
| } | |
| f.write(content.data(), content.size()); | |
| if (!f) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "write: Failed to write file " << file_name << " " << st_err; | |
| return absl::UnavailableError("write: Failed to write file"); | |
| } | |
| f.close(); | |
| if (!f) { | |
| char* st_err = strerror(errno); | |
| LOG(ERROR) << "write: Failed to close file " << file_name << " " << st_err; | |
| return absl::UnavailableError("write: Failed to close file"); | |
| } | |
| return absl::OkStatus(); | |
| } | |
| } // namespace proto_reader |