blob: b334ded59991dac6a001938cc3629efb59866100 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/util/file.h"
Brian Silverman61175fb2016-03-13 15:35:56 -04002
3#include <fcntl.h>
Austin Schuhfccb2d02020-01-26 16:11:19 -08004#include <sys/stat.h>
5#include <sys/types.h>
Brian Silverman61175fb2016-03-13 15:35:56 -04006#include <unistd.h>
7
James Kuszmaul3ae42262019-11-08 12:33:41 -08008#include <string_view>
9
John Park33858a32018-09-28 23:05:48 -070010#include "aos/scoped/scoped_fd.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include "glog/logging.h"
Brian Silverman61175fb2016-03-13 15:35:56 -040012
13namespace aos {
14namespace util {
15
James Kuszmaul3ae42262019-11-08 12:33:41 -080016::std::string ReadFileToStringOrDie(const std::string_view filename) {
Brian Silverman61175fb2016-03-13 15:35:56 -040017 ::std::string r;
Austin Schuhcb108412019-10-13 16:09:54 -070018 ScopedFD fd(open(::std::string(filename).c_str(), O_RDONLY));
Alex Perrycb7da4b2019-08-28 19:35:56 -070019 PCHECK(fd.get() != -1) << ": opening " << filename;
Brian Silverman61175fb2016-03-13 15:35:56 -040020 while (true) {
21 char buffer[1024];
22 const ssize_t result = read(fd.get(), buffer, sizeof(buffer));
Alex Perrycb7da4b2019-08-28 19:35:56 -070023 PCHECK(result >= 0) << ": reading from " << filename;
24 if (result == 0) {
Brian Silverman61175fb2016-03-13 15:35:56 -040025 break;
26 }
27 r.append(buffer, result);
28 }
29 return r;
30}
31
James Kuszmaul3ae42262019-11-08 12:33:41 -080032void WriteStringToFileOrDie(const std::string_view filename,
33 const std::string_view contents) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070034 ::std::string r;
35 ScopedFD fd(open(::std::string(filename).c_str(),
36 O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU));
37 PCHECK(fd.get() != -1) << ": opening " << filename;
38 size_t size_written = 0;
39 while (size_written != contents.size()) {
40 const ssize_t result = write(fd.get(), contents.data() + size_written,
41 contents.size() - size_written);
42 PCHECK(result >= 0) << ": reading from " << filename;
43 if (result == 0) {
44 break;
45 }
46
47 size_written += result;
48 }
49}
50
Austin Schuhfccb2d02020-01-26 16:11:19 -080051void MkdirP(std::string_view path, mode_t mode) {
52 auto last_slash_pos = path.find_last_of("/");
53
54 std::string folder(last_slash_pos == std::string_view::npos
55 ? std::string_view("")
56 : path.substr(0, last_slash_pos));
57 if (folder.empty()) return;
58 MkdirP(folder, mode);
59 const int result = mkdir(folder.c_str(), mode);
60 if (result == -1 && errno == EEXIST) {
61 VLOG(2) << folder << " already exists";
62 return;
63 } else {
64 VLOG(1) << "Created " << folder;
65 }
66 PCHECK(result == 0) << ": Error creating " << folder;
67}
68
Brian Silverman61175fb2016-03-13 15:35:56 -040069} // namespace util
70} // namespace aos