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 "disk_handler.h" 17 18 #include <fstream> 19 #include <sstream> 20 21 #include "netstack_log.h" 22 23 namespace OHOS::NetStack::Http { DiskHandler(std::string fileName)24DiskHandler::DiskHandler(std::string fileName) : fileName_(std::move(fileName)) {} 25 Write(const std::string & str)26void DiskHandler::Write(const std::string &str) 27 { 28 std::lock_guard<std::mutex> guard(mutex_); 29 std::ofstream w(fileName_); 30 if (!w.is_open()) { 31 return; 32 } 33 w << str; 34 w.close(); 35 } 36 Read()37std::string DiskHandler::Read() 38 { 39 std::lock_guard<std::mutex> guard(mutex_); 40 std::ifstream r(fileName_); 41 if (!r.is_open()) { 42 return {}; 43 } 44 std::stringstream b; 45 b << r.rdbuf(); 46 r.close(); 47 return b.str(); 48 } 49 Delete()50void DiskHandler::Delete() 51 { 52 std::lock_guard<std::mutex> guard(mutex_); 53 if (remove(fileName_.c_str()) < 0) { 54 NETSTACK_LOGI("remove file error %{public}d", errno); 55 } 56 } 57 } // namespace OHOS::NetStack::Http 58