blob: ad298448d8e4749a980080efe951f9fe3f6dac28 [file] [log] [blame]
adlr@google.com3defe6a2009-12-04 20:57:17 +00001// 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"
6#include <errno.h>
7
8namespace chromeos_update_engine {
9
10int DirectFileWriter::Open(const char* path, int flags, mode_t mode) {
11 CHECK_EQ(fd_, -1);
12 fd_ = open(path, flags, mode);
13 if (fd_ < 0)
14 return -errno;
15 return 0;
16}
17
Don Garrette410e0f2011-11-10 15:39:01 -080018bool DirectFileWriter::Write(const void* bytes, size_t count) {
adlr@google.com3defe6a2009-12-04 20:57:17 +000019 CHECK_GE(fd_, 0);
20 const char* char_bytes = reinterpret_cast<const char*>(bytes);
21
22 size_t bytes_written = 0;
23 while (bytes_written < count) {
24 ssize_t rc = write(fd_, char_bytes + bytes_written,
25 count - bytes_written);
26 if (rc < 0)
Don Garrette410e0f2011-11-10 15:39:01 -080027 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +000028 bytes_written += rc;
29 }
30 CHECK_EQ(bytes_written, count);
Don Garrette410e0f2011-11-10 15:39:01 -080031 return bytes_written == count;
adlr@google.com3defe6a2009-12-04 20:57:17 +000032}
33
34int DirectFileWriter::Close() {
35 CHECK_GE(fd_, 0);
36 int rc = close(fd_);
37
38 // This can be any negative number that's not -1. This way, this FileWriter
39 // won't be used again for another file.
40 fd_ = -2;
41
42 if (rc < 0)
43 return -errno;
44 return rc;
45}
46
47} // namespace chromeos_update_engine