blob: 367dbe8d0e3278df5368b037f62175c239de7f97 [file] [log] [blame]
Brian Carlstromdb4d5402011-08-09 12:18:28 -07001// Copyright 2010 Google Inc. All Rights Reserved.
2
3#include "file_linux.h"
4
5#include <errno.h>
6#include <unistd.h>
7
8#include "logging.h"
9
10namespace art {
11
12LinuxFile::~LinuxFile() {
13 // Close the file if necessary (unless it's a standard stream).
14 if (auto_close_ && fd_ > STDERR_FILENO) {
15 Close();
16 }
17}
18
19void LinuxFile::Close() {
20 DCHECK_GT(fd_, 0);
21 int err = close(fd_);
22 if (err != 0) {
23 PLOG(WARNING) << "Problem closing " << name();
24 }
25 fd_ = kClosedFd;
26}
27
28
29bool LinuxFile::IsClosed() {
30 return fd_ == kClosedFd;
31}
32
33
34int64_t LinuxFile::Read(void* buffer, int64_t num_bytes) {
35 DCHECK_GE(fd_, 0);
36 return read(fd_, buffer, num_bytes);
37}
38
39
40int64_t LinuxFile::Write(const void* buffer, int64_t num_bytes) {
41 DCHECK_GE(fd_, 0);
42 return write(fd_, buffer, num_bytes);
43}
44
45
Elliott Hughes2a2ff562012-01-06 18:07:59 -080046off_t LinuxFile::Position() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070047 DCHECK_GE(fd_, 0);
Elliott Hughes2a2ff562012-01-06 18:07:59 -080048 return lseek(fd_, 0, SEEK_CUR);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070049}
50
51
Elliott Hughes2a2ff562012-01-06 18:07:59 -080052off_t LinuxFile::Length() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070053 DCHECK_GE(fd_, 0);
Elliott Hughes2a2ff562012-01-06 18:07:59 -080054 off_t position = lseek(fd_, 0, SEEK_CUR);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070055 if (position < 0) {
56 // The file is not capable of seeking. Return an error.
57 return -1;
58 }
Elliott Hughes2a2ff562012-01-06 18:07:59 -080059 off_t result = lseek(fd_, 0, SEEK_END);
60 lseek(fd_, position, SEEK_SET);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070061 return result;
62}
63
64} // namespace art