blob: 8f8e989122f56c7539293b47007ec138945a4aed [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"
Alex Deymoaab50e32014-11-10 19:55:35 -08006
adlr@google.com3defe6a2009-12-04 20:57:17 +00007#include <errno.h>
8
9namespace chromeos_update_engine {
10
11int 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 Garrette410e0f2011-11-10 15:39:01 -080019bool DirectFileWriter::Write(const void* bytes, size_t count) {
adlr@google.com3defe6a2009-12-04 20:57:17 +000020 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 Garrette410e0f2011-11-10 15:39:01 -080028 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +000029 bytes_written += rc;
30 }
31 CHECK_EQ(bytes_written, count);
Don Garrette410e0f2011-11-10 15:39:01 -080032 return bytes_written == count;
adlr@google.com3defe6a2009-12-04 20:57:17 +000033}
34
35int 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