blob: aa35ff242ae8f79b6a76f7378466127adc8c9e8c [file] [log] [blame]
Elliott Hughesdec12b22015-02-02 17:31:27 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "utils/file.h"
18
19#include <errno.h>
20#include <fcntl.h>
21#include <sys/stat.h>
22#include <sys/types.h>
23
Elliott Hughesaf4885a2015-02-03 13:02:57 -080024#include <utils/Compat.h> // For TEMP_FAILURE_RETRY on Darwin.
25
Elliott Hughesdec12b22015-02-02 17:31:27 -080026bool android::ReadFileToString(const std::string& path, std::string* content) {
27 content->clear();
28
29 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
30 if (fd == -1) {
31 return false;
32 }
33
34 while (true) {
35 char buf[BUFSIZ];
36 ssize_t n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)));
37 if (n == -1) {
38 TEMP_FAILURE_RETRY(close(fd));
39 return false;
40 }
41 if (n == 0) {
42 TEMP_FAILURE_RETRY(close(fd));
43 return true;
44 }
45 content->append(buf, n);
46 }
47}
48
49bool android::WriteStringToFile(const std::string& content, const std::string& path) {
50 int fd = TEMP_FAILURE_RETRY(open(path.c_str(),
51 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
52 DEFFILEMODE));
53 if (fd == -1) {
54 return false;
55 }
56
57 const char* p = content.data();
58 size_t left = content.size();
59 while (left > 0) {
60 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
61 if (n == -1) {
62 TEMP_FAILURE_RETRY(close(fd));
63 return false;
64 }
65 p += n;
66 left -= n;
67 }
68 TEMP_FAILURE_RETRY(close(fd));
69 return true;
70}