1 /* 2 * Copyright (c) 2025 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 "stream_instantiator.h" 17 18 #include "file_utils.h" 19 #include "filemgmt_libhilog.h" 20 #include "stream_entity.h" 21 22 namespace OHOS { 23 namespace FileManagement { 24 namespace ModuleFileIO { 25 using namespace std; 26 InstantiateStream(FILE * file)27FsResult<FsStream *> StreamInstantiator::InstantiateStream(FILE *file) 28 { 29 FsResult<FsStream *> result = FsStream::Constructor(); 30 if (!result.IsSuccess()) { 31 HILOGE("Failed to instantiate class"); 32 int ret = fclose(file); 33 if (ret < 0) { 34 HILOGE("Failed to close file"); 35 } 36 return FsResult<FsStream *>::Error(EIO); 37 } 38 39 const FsStream *objStream = result.GetData().value(); 40 if (!objStream) { 41 HILOGE("Failed to get FsStream"); 42 int ret = fclose(file); 43 if (ret < 0) { 44 HILOGE("Failed to close file"); 45 } 46 return FsResult<FsStream *>::Error(EIO); 47 } 48 49 auto *streamEntity = objStream->GetStreamEntity(); 50 if (!streamEntity) { 51 HILOGE("Failed to get streamEntity"); 52 int ret = fclose(file); 53 if (ret < 0) { 54 HILOGE("Failed to close file"); 55 } 56 delete objStream; 57 objStream = nullptr; 58 return FsResult<FsStream *>::Error(EIO); 59 } 60 61 auto fp = std::shared_ptr<FILE>(file, fclose); 62 if (fp == nullptr) { 63 HILOGE("Failed to request heap memory."); 64 int ret = fclose(file); 65 if (ret < 0) { 66 HILOGE("Failed to close file"); 67 } 68 delete objStream; 69 objStream = nullptr; 70 return FsResult<FsStream *>::Error(ENOMEM); 71 } 72 73 streamEntity->fp.swap(fp); 74 return result; 75 } 76 77 } // namespace ModuleFileIO 78 } // namespace FileManagement 79 } // namespace OHOS