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" |
Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 7 | #include "aos/logging/logging.h" |
John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 8 | #include "aos/scoped/scoped_fd.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)); |
| 16 | if (fd.get() == -1) { |
| 17 | PLOG(FATAL, "opening %*s", static_cast<int>(filename.size()), |
| 18 | filename.data()); |
| 19 | } |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 20 | while (true) { |
| 21 | char buffer[1024]; |
| 22 | const ssize_t result = read(fd.get(), buffer, sizeof(buffer)); |
| 23 | if (result < 0) { |
Austin Schuh | cb10841 | 2019-10-13 16:09:54 -0700 | [diff] [blame^] | 24 | PLOG(FATAL, "reading from %*s", static_cast<int>(filename.size()), |
| 25 | filename.data()); |
Brian Silverman | 61175fb | 2016-03-13 15:35:56 -0400 | [diff] [blame] | 26 | } else if (result == 0) { |
| 27 | break; |
| 28 | } |
| 29 | r.append(buffer, result); |
| 30 | } |
| 31 | return r; |
| 32 | } |
| 33 | |
| 34 | } // namespace util |
| 35 | } // namespace aos |