John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 1 | #include "aos/util/file.h" |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 2 | |
| 3 | #include <fcntl.h> |
| 4 | #include <unistd.h> |
| 5 | |
Austin Schuh | cb10841 | 2019-10-13 16:09:54 -0700 | [diff] [blame] | 6 | #include "absl/strings/string_view.h" |
John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 7 | #include "aos/scoped/scoped_fd.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 8 | #include "glog/logging.h" |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 9 | |
| 10 | namespace aos { |
| 11 | namespace util { |
| 12 | |
Austin Schuh | cb10841 | 2019-10-13 16:09:54 -0700 | [diff] [blame] | 13 | ::std::string ReadFileToStringOrDie(const absl::string_view filename) { |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 14 | ::std::string r; |
Austin Schuh | cb10841 | 2019-10-13 16:09:54 -0700 | [diff] [blame] | 15 | ScopedFD fd(open(::std::string(filename).c_str(), O_RDONLY)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 16 | PCHECK(fd.get() != -1) << ": opening " << filename; |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 17 | while (true) { |
| 18 | char buffer[1024]; |
| 19 | const ssize_t result = read(fd.get(), buffer, sizeof(buffer)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 20 | PCHECK(result >= 0) << ": reading from " << filename; |
| 21 | if (result == 0) { |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 22 | break; |
| 23 | } |
| 24 | r.append(buffer, result); |
| 25 | } |
| 26 | return r; |
| 27 | } |
| 28 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 29 | void WriteStringToFileOrDie(const absl::string_view filename, |
| 30 | const absl::string_view contents) { |
| 31 | ::std::string r; |
| 32 | ScopedFD fd(open(::std::string(filename).c_str(), |
| 33 | O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU)); |
| 34 | PCHECK(fd.get() != -1) << ": opening " << filename; |
| 35 | size_t size_written = 0; |
| 36 | while (size_written != contents.size()) { |
| 37 | const ssize_t result = write(fd.get(), contents.data() + size_written, |
| 38 | contents.size() - size_written); |
| 39 | PCHECK(result >= 0) << ": reading from " << filename; |
| 40 | if (result == 0) { |
| 41 | break; |
| 42 | } |
| 43 | |
| 44 | size_written += result; |
| 45 | } |
| 46 | } |
| 47 | |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 48 | } // namespace util |
| 49 | } // namespace aos |