blob: 4319c1ce902f012df97c8b17e56a638504e2bae6 [file] [log] [blame]
aimitakeshid074e302010-07-29 10:12:27 +09001/*
2 * Copyright (C) 2010 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 <ReadWriteUtils.h>
18#include <sys/mman.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <fcntl.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <unistd.h>
25#include <utils/FileMap.h>
26#include <utils/String8.h>
27
28using namespace android;
29
30#define FAILURE -1
31
32String8 ReadWriteUtils::readBytes(const String8& filePath) {
33 FILE* file = NULL;
34 file = fopen(filePath.string(), "r");
35
36 String8 string("");
37 if (NULL != file) {
38 int fd = fileno(file);
39 struct stat sb;
40
41 if (fstat(fd, &sb) == 0 && sb.st_size > 0) {
42 FileMap* fileMap = new FileMap();
43 if (fileMap->create(filePath.string(), fd, 0, sb.st_size, true)) {
44 char* addr = (char*)fileMap->getDataPtr();
45 string.append(addr, sb.st_size);
46 fileMap->release();
47 }
48 }
49 fclose(file);
50 }
51 return string;
52}
53
54void ReadWriteUtils::writeToFile(const String8& filePath, const String8& data) {
55 FILE* file = NULL;
56 file = fopen(filePath.string(), "w+");
57
58 if (NULL != file) {
59 int fd = fileno(file);
60
61 int size = data.size();
62 if (FAILURE != ftruncate(fd, size)) {
63 FileMap* fileMap = NULL;
64 fileMap = new FileMap();
65 if (fileMap->create(filePath.string(), fd, 0, size, false)) {
66 char* addr = (char*)fileMap->getDataPtr();
67 memcpy(addr, data.string(), size);
68 fileMap->release();
69 }
70 }
71 fclose(file);
72 }
73}
74
75void ReadWriteUtils::appendToFile(const String8& filePath, const String8& data) {
76 FILE* file = NULL;
77 file = fopen(filePath.string(), "a+");
78
79 if (NULL != file) {
80 int fd = fileno(file);
81
82 int offset = lseek(fd, 0, SEEK_END);
83 if (FAILURE != offset) {
84 int newEntrySize = data.size();
85 int fileSize = offset + newEntrySize;
86
87 if (FAILURE != ftruncate(fd, fileSize)) {
88 FileMap* fileMap = NULL;
89 fileMap = new FileMap();
90 if (fileMap->create(filePath.string(), fd, offset, fileSize, false)) {
91 char* addr = (char*)fileMap->getDataPtr();
92 memcpy(addr, data.string(), data.size());
93 fileMap->release();
94 }
95 }
96 }
97 fclose(file);
98 }
99}
100