blob: 15bda7f5fad410953a2a7da00a9d071f0b159e4b [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
24bool android::ReadFileToString(const std::string& path, std::string* content) {
25 content->clear();
26
27 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
28 if (fd == -1) {
29 return false;
30 }
31
32 while (true) {
33 char buf[BUFSIZ];
34 ssize_t n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)));
35 if (n == -1) {
36 TEMP_FAILURE_RETRY(close(fd));
37 return false;
38 }
39 if (n == 0) {
40 TEMP_FAILURE_RETRY(close(fd));
41 return true;
42 }
43 content->append(buf, n);
44 }
45}
46
47bool android::WriteStringToFile(const std::string& content, const std::string& path) {
48 int fd = TEMP_FAILURE_RETRY(open(path.c_str(),
49 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
50 DEFFILEMODE));
51 if (fd == -1) {
52 return false;
53 }
54
55 const char* p = content.data();
56 size_t left = content.size();
57 while (left > 0) {
58 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
59 if (n == -1) {
60 TEMP_FAILURE_RETRY(close(fd));
61 return false;
62 }
63 p += n;
64 left -= n;
65 }
66 TEMP_FAILURE_RETRY(close(fd));
67 return true;
68}