blob: cd272fb0bbde4a21993ec9be1834df921a24c0aa [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Brian Carlstromdb4d5402011-08-09 12:18:28 -070016
17#include "file_linux.h"
18
19#include <errno.h>
20#include <unistd.h>
21
22#include "logging.h"
23
24namespace art {
25
26LinuxFile::~LinuxFile() {
27 // Close the file if necessary (unless it's a standard stream).
28 if (auto_close_ && fd_ > STDERR_FILENO) {
29 Close();
30 }
31}
32
33void LinuxFile::Close() {
34 DCHECK_GT(fd_, 0);
35 int err = close(fd_);
36 if (err != 0) {
37 PLOG(WARNING) << "Problem closing " << name();
38 }
39 fd_ = kClosedFd;
40}
41
42
43bool LinuxFile::IsClosed() {
44 return fd_ == kClosedFd;
45}
46
47
48int64_t LinuxFile::Read(void* buffer, int64_t num_bytes) {
49 DCHECK_GE(fd_, 0);
50 return read(fd_, buffer, num_bytes);
51}
52
53
54int64_t LinuxFile::Write(const void* buffer, int64_t num_bytes) {
55 DCHECK_GE(fd_, 0);
56 return write(fd_, buffer, num_bytes);
57}
58
59
Elliott Hughes2a2ff562012-01-06 18:07:59 -080060off_t LinuxFile::Position() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070061 DCHECK_GE(fd_, 0);
Elliott Hughes2a2ff562012-01-06 18:07:59 -080062 return lseek(fd_, 0, SEEK_CUR);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070063}
64
65
Elliott Hughes2a2ff562012-01-06 18:07:59 -080066off_t LinuxFile::Length() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070067 DCHECK_GE(fd_, 0);
Elliott Hughes2a2ff562012-01-06 18:07:59 -080068 off_t position = lseek(fd_, 0, SEEK_CUR);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070069 if (position < 0) {
70 // The file is not capable of seeking. Return an error.
71 return -1;
72 }
Elliott Hughes2a2ff562012-01-06 18:07:59 -080073 off_t result = lseek(fd_, 0, SEEK_END);
74 lseek(fd_, position, SEEK_SET);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070075 return result;
76}
77
78} // namespace art