1/* 2 * Copyright (c) 2023 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 <filesystem> 17#include <fstream> 18#include <iostream> 19#include <sstream> 20#include <sys/stat.h> 21#include <unistd.h> 22 23#include "oaid_hilog_wreapper.h" 24#include "oaid_file_operator.h" 25 26namespace OHOS { 27namespace Cloud { 28bool OAIDFileOperator::IsFileExsit(const std::string &fileName) 29{ 30 if (fileName.empty()) { 31 OAID_HILOGE(OAID_MODULE_COMMON, "filename is empty"); 32 return false; 33 } 34 if (access(fileName.c_str(), F_OK) != 0) { 35 OAID_HILOGW(OAID_MODULE_COMMON, "file not exist"); 36 return false; 37 } 38 return true; 39} 40 41bool OAIDFileOperator::OpenAndReadFile(const std::string &fileName, std::string &destContent) 42{ 43 std::ifstream inStream(fileName.c_str(), std::ios::in | std::ios::binary); 44 if (inStream) { 45 inStream.seekg(0, std::ios::end); 46 destContent.resize(inStream.tellg()); 47 inStream.seekg(0, std::ios::beg); 48 inStream.read(&destContent[0], destContent.size()); 49 inStream.close(); 50 OAID_HILOGE(OAID_MODULE_COMMON, "OpenAndReadFile success"); 51 return true; 52 } 53 OAID_HILOGE(OAID_MODULE_COMMON, "OpenAndReadFile failed"); 54 return false; 55} 56 57bool OAIDFileOperator::ClearFile(const std::string &fileName) 58{ 59 struct stat statbuf {}; 60 if (lstat(fileName.c_str(), &statbuf) != 0) { 61 OAID_HILOGE(OAID_MODULE_COMMON, "clear object is not file"); 62 return false; 63 } 64 if (S_ISREG(statbuf.st_mode)) { 65 if (access(fileName.c_str(), F_OK) != 0) { 66 OAID_HILOGE(OAID_MODULE_COMMON, "RemoveFile success, file is not exist"); 67 return true; 68 } 69 remove(fileName.c_str()); 70 } 71 return true; 72} 73} 74}