Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 1 | // 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 | |
| 10 | namespace art { |
| 11 | |
| 12 | LinuxFile::~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 | |
| 19 | void 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 | |
| 29 | bool LinuxFile::IsClosed() { |
| 30 | return fd_ == kClosedFd; |
| 31 | } |
| 32 | |
| 33 | |
| 34 | int64_t LinuxFile::Read(void* buffer, int64_t num_bytes) { |
| 35 | DCHECK_GE(fd_, 0); |
| 36 | return read(fd_, buffer, num_bytes); |
| 37 | } |
| 38 | |
| 39 | |
| 40 | int64_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 Hughes | 2a2ff56 | 2012-01-06 18:07:59 -0800 | [diff] [blame] | 46 | off_t LinuxFile::Position() { |
Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 47 | DCHECK_GE(fd_, 0); |
Elliott Hughes | 2a2ff56 | 2012-01-06 18:07:59 -0800 | [diff] [blame] | 48 | return lseek(fd_, 0, SEEK_CUR); |
Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | |
Elliott Hughes | 2a2ff56 | 2012-01-06 18:07:59 -0800 | [diff] [blame] | 52 | off_t LinuxFile::Length() { |
Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 53 | DCHECK_GE(fd_, 0); |
Elliott Hughes | 2a2ff56 | 2012-01-06 18:07:59 -0800 | [diff] [blame] | 54 | off_t position = lseek(fd_, 0, SEEK_CUR); |
Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 55 | if (position < 0) { |
| 56 | // The file is not capable of seeking. Return an error. |
| 57 | return -1; |
| 58 | } |
Elliott Hughes | 2a2ff56 | 2012-01-06 18:07:59 -0800 | [diff] [blame] | 59 | off_t result = lseek(fd_, 0, SEEK_END); |
| 60 | lseek(fd_, position, SEEK_SET); |
Brian Carlstrom | db4d540 | 2011-08-09 12:18:28 -0700 | [diff] [blame] | 61 | return result; |
| 62 | } |
| 63 | |
| 64 | } // namespace art |