• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <ios>
19 #include <sstream>
20 #include <string>
21 
22 #include "absl/status/status.h"
23 #include "absl/strings/str_cat.h"
24 #include "absl/strings/string_view.h"
25 
26 namespace sapi::file {
27 
Defaults()28 const Options& Defaults() {
29   static auto* instance = new Options{};
30   return *instance;
31 }
32 
GetContents(absl::string_view path,std::string * output,const file::Options & options)33 absl::Status GetContents(absl::string_view path, std::string* output,
34                          const file::Options& options) {
35   std::ifstream in_stream{std::string(path), std::ios_base::binary};
36   std::ostringstream out_stream;
37   out_stream << in_stream.rdbuf();
38   if (!in_stream || !out_stream) {
39     return absl::UnknownError(absl::StrCat("Error during read: ", path));
40   }
41   *output = out_stream.str();
42   return absl::OkStatus();
43 }
44 
SetContents(absl::string_view path,absl::string_view content,const file::Options & options)45 absl::Status SetContents(absl::string_view path, absl::string_view content,
46                          const file::Options& options) {
47   std::ofstream out_stream(std::string(path),
48                            std::ios_base::trunc | std::ios_base::binary);
49   if (!out_stream) {
50     return absl::UnknownError(absl::StrCat("Failed to open file: ", path));
51   }
52   out_stream.write(content.data(), content.size());
53   if (!out_stream) {
54     return absl::UnknownError(absl::StrCat("Error during write: ", path));
55   }
56   return absl::OkStatus();
57 }
58 
59 }  // namespace sapi::file
60