xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/util/file_helpers.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "sandboxed_api/util/file_helpers.h"
16 
17 #include <fstream>
18 #include <sstream>
19 #include <string>
20 
21 #include "absl/status/status.h"
22 #include "absl/strings/str_cat.h"
23 #include "absl/strings/string_view.h"
24 
25 namespace sapi::file {
26 
Defaults()27 const Options& Defaults() {
28   static auto* instance = new Options{};
29   return *instance;
30 }
31 
GetContents(absl::string_view path,std::string * output,const file::Options & options)32 absl::Status GetContents(absl::string_view path, std::string* output,
33                          const file::Options& options) {
34   std::ifstream in_stream{std::string(path), std::ios_base::binary};
35   std::ostringstream out_stream;
36   out_stream << in_stream.rdbuf();
37   if (!in_stream || !out_stream) {
38     return absl::UnknownError(absl::StrCat("Error during read: ", path));
39   }
40   *output = out_stream.str();
41   return absl::OkStatus();
42 }
43 
SetContents(absl::string_view path,absl::string_view content,const file::Options & options)44 absl::Status SetContents(absl::string_view path, absl::string_view content,
45                          const file::Options& options) {
46   std::ofstream out_stream(std::string(path),
47                            std::ios_base::trunc | std::ios_base::binary);
48   if (!out_stream) {
49     return absl::UnknownError(absl::StrCat("Failed to open file: ", path));
50   }
51   out_stream.write(content.data(), content.size());
52   if (!out_stream) {
53     return absl::UnknownError(absl::StrCat("Error during write: ", path));
54   }
55   return absl::OkStatus();
56 }
57 
58 }  // namespace sapi::file
59