1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "file_packer_stream.h"
17 #include <cerrno>
18 #include "directory_ex.h"
19 #include "image_utils.h"
20
21 namespace OHOS {
22 namespace Media {
23 using namespace OHOS::HiviewDFX;
24
FilePackerStream(const std::string & filePath)25 FilePackerStream::FilePackerStream(const std::string &filePath)
26 {
27 std::string dirPath = ExtractFilePath(filePath);
28 std::string fileName = ExtractFileName(filePath);
29 std::string realPath;
30 if (!ImageUtils::PathToRealPath(dirPath, realPath)) {
31 file_ = nullptr;
32 HiLog::Error(LABEL, "convert to real path failed.");
33 return;
34 }
35
36 if (!ForceCreateDirectory(realPath)) {
37 file_ = nullptr;
38 HiLog::Error(LABEL, "create directory failed.");
39 return;
40 }
41
42 std::string fullPath = realPath + "/" + fileName;
43 file_ = fopen(fullPath.c_str(), "wb");
44 if (file_ == nullptr) {
45 HiLog::Error(LABEL, "fopen file failed, error:%{public}d", errno);
46 return;
47 }
48 }
FilePackerStream(const int fd)49 FilePackerStream::FilePackerStream(const int fd)
50 {
51 file_ = fdopen(fd, "wb");
52 if (file_ == nullptr) {
53 HiLog::Error(LABEL, "fopen file failed, error:%{public}d", errno);
54 return;
55 }
56 }
~FilePackerStream()57 FilePackerStream::~FilePackerStream()
58 {
59 if (file_ != nullptr) {
60 fclose(file_);
61 file_ = nullptr;
62 }
63 }
64
Write(const uint8_t * buffer,uint32_t size)65 bool FilePackerStream::Write(const uint8_t *buffer, uint32_t size)
66 {
67 if ((buffer == nullptr) || (size == 0)) {
68 HiLog::Error(LABEL, "input parameter invalid.");
69 return false;
70 }
71 if (file_ == nullptr) {
72 HiLog::Error(LABEL, "output file is null.");
73 return false;
74 }
75 if (fwrite(buffer, sizeof(uint8_t), size, file_) != size) {
76 HiLog::Error(LABEL, "write %{public}u bytes failed.", size);
77 fclose(file_);
78 file_ = nullptr;
79 return false;
80 }
81 return true;
82 }
83
Flush()84 void FilePackerStream::Flush()
85 {
86 if (file_ != nullptr) {
87 fflush(file_);
88 }
89 }
90
BytesWritten()91 int64_t FilePackerStream::BytesWritten()
92 {
93 return (file_ != nullptr) ? ftell(file_) : 0;
94 }
95 } // namespace Media
96 } // namespace OHOS
97