2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 * @file file_output.cpp
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20 * @brief This file is the implementation file of file output
23 #include <dpl/file_output.h>
24 #include <dpl/binary_queue.h>
25 #include <dpl/scoped_free.h>
26 #include <dpl/log/log.h>
34 FileOutput::FileOutput()
39 FileOutput::FileOutput(const std::string& fileName)
45 FileOutput::~FileOutput()
50 void FileOutput::Open(const std::string& fileName)
53 int fd = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, 0664));
55 // Throw an exception if an error occurred
57 ThrowMsg(Exception::OpenFailed, fileName);
59 // Close if any existing
62 // Save new descriptor
65 LogPedantic("Opened file: " << fileName);
68 void FileOutput::Close()
73 if (TEMP_FAILURE_RETRY(close(m_fd)) == -1)
74 Throw(Exception::CloseFailed);
78 LogPedantic("Closed file");
81 size_t FileOutput::Write(const BinaryQueue &buffer, size_t bufferSize)
84 if (bufferSize > buffer.Size())
85 bufferSize = buffer.Size();
87 // FIXME: User write visitor to write !
88 // WriteVisitor visitor
90 ScopedFree<void> flattened(malloc(bufferSize));
91 buffer.Flatten(flattened.Get(), bufferSize);
93 LogPedantic("Trying to write " << bufferSize << " bytes");
95 ssize_t result = TEMP_FAILURE_RETRY(write(m_fd, flattened.Get(), bufferSize));
97 LogPedantic("Wrote " << result << " bytes to file");
101 // Successfuly written some bytes
102 return static_cast<size_t>(result);
104 else if (result == 0)
106 // This is abnormal result
107 ThrowMsg(CommonException::InternalError, "Invalid write result, 0 bytes written");
111 // Interpret error result
112 // FIXME: Handle errno
113 Throw(AbstractOutput::Exception::WriteFailed);
117 WaitableHandle FileOutput::WaitableWriteHandle() const
119 return static_cast<WaitableHandle>(m_fd);