adlr@google.com | 3defe6a | 2009-12-04 20:57:17 +0000 | [diff] [blame] | 1 | // Copyright (c) 2009 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "update_engine/file_writer.h" |
Alex Deymo | aab50e3 | 2014-11-10 19:55:35 -0800 | [diff] [blame^] | 6 | |
adlr@google.com | 3defe6a | 2009-12-04 20:57:17 +0000 | [diff] [blame] | 7 | #include <errno.h> |
| 8 | |
| 9 | namespace chromeos_update_engine { |
| 10 | |
| 11 | int DirectFileWriter::Open(const char* path, int flags, mode_t mode) { |
| 12 | CHECK_EQ(fd_, -1); |
| 13 | fd_ = open(path, flags, mode); |
| 14 | if (fd_ < 0) |
| 15 | return -errno; |
| 16 | return 0; |
| 17 | } |
| 18 | |
Don Garrett | e410e0f | 2011-11-10 15:39:01 -0800 | [diff] [blame] | 19 | bool DirectFileWriter::Write(const void* bytes, size_t count) { |
adlr@google.com | 3defe6a | 2009-12-04 20:57:17 +0000 | [diff] [blame] | 20 | CHECK_GE(fd_, 0); |
| 21 | const char* char_bytes = reinterpret_cast<const char*>(bytes); |
| 22 | |
| 23 | size_t bytes_written = 0; |
| 24 | while (bytes_written < count) { |
| 25 | ssize_t rc = write(fd_, char_bytes + bytes_written, |
| 26 | count - bytes_written); |
| 27 | if (rc < 0) |
Don Garrett | e410e0f | 2011-11-10 15:39:01 -0800 | [diff] [blame] | 28 | return false; |
adlr@google.com | 3defe6a | 2009-12-04 20:57:17 +0000 | [diff] [blame] | 29 | bytes_written += rc; |
| 30 | } |
| 31 | CHECK_EQ(bytes_written, count); |
Don Garrett | e410e0f | 2011-11-10 15:39:01 -0800 | [diff] [blame] | 32 | return bytes_written == count; |
adlr@google.com | 3defe6a | 2009-12-04 20:57:17 +0000 | [diff] [blame] | 33 | } |
| 34 | |
| 35 | int DirectFileWriter::Close() { |
| 36 | CHECK_GE(fd_, 0); |
| 37 | int rc = close(fd_); |
| 38 | |
| 39 | // This can be any negative number that's not -1. This way, this FileWriter |
| 40 | // won't be used again for another file. |
| 41 | fd_ = -2; |
| 42 | |
| 43 | if (rc < 0) |
| 44 | return -errno; |
| 45 | return rc; |
| 46 | } |
| 47 | |
| 48 | } // namespace chromeos_update_engine |