1 /* 2 * Copyright (c) 2022-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 #ifndef OHOS_FILEMGMT_BACKUP_B_FILE_H 17 #define OHOS_FILEMGMT_BACKUP_B_FILE_H 18 19 #include <memory> 20 #include <string> 21 22 #include "unique_fd.h" 23 24 #include "b_anony/b_anony.h" 25 26 namespace OHOS::FileManagement::Backup { 27 using namespace std; 28 class BFile { 29 public: 30 /** 31 * @brief 一次性读取文件全部内容 32 * 33 * @param fd 文件描述符 34 * @return std::unique_ptr<char[]> 文件全部内容,保证最后一个字节为'\0' 35 * @throw std::system_error IO异常 36 */ 37 static std::unique_ptr<char[]> ReadFile(const UniqueFd &fd); 38 39 /** 40 * @brief linux sendfile 二次封装 41 * @param outFd 参数是待写入内容的文件描述符 42 * @param inFd 参数是待读出内容的文件描述符 43 * @throw std::system_error IO异常 44 */ 45 static void SendFile(int outFd, int inFd); 46 47 /** 48 * @brief linux write 二次封装 49 * @param fd 参数是待写入内容的文件描述符 50 * @param str 待写入文件的字符串 51 * @throw std::system_error IO异常 52 */ 53 static void Write(const UniqueFd &fd, const string &str); 54 55 /** 56 * @brief copy file from old path to new path 57 * 58 * @param from old path 59 * @param to new path 60 * @return true copy succeess 61 * @return false some error occur 62 */ 63 static bool CopyFile(const string &from, const string &to); 64 65 /** 66 * @brief move file from old path to new path 67 * 68 * @param from old path 69 * @param to new path 70 * @return true move succeess 71 * @return false some error occur 72 */ 73 static bool MoveFile(const string &from, const string &to); 74 75 /** 76 * @brief get real path 77 * 78 * @param path src path 79 * @param realPath real path 80 * @return true get real path success 81 * @return false some error occur 82 */ 83 static bool GetRealPath(const string &path, string &realPath); 84 85 /** 86 * @brief check if string is endswith suffix 87 * 88 * @param str str 89 * @param suffix suffix str 90 * @return true str is endswith suffix 91 * @return false str is not endswith suffix 92 */ 93 static bool EndsWith(const string &str, const string &suffix); 94 95 /** 96 * @brief get file size by path 97 * 98 * @param path file path 99 * @param error 错误码 100 * @return 0 if path is invalid 101 * @return file size in byte if path is valid 102 */ 103 static uint64_t GetFileSize(const string &path, int32_t &error); 104 private: 105 }; 106 } // namespace OHOS::FileManagement::Backup 107 108 #endif // OHOS_FILEMGMT_BACKUP_B_FILE_H