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 //! filemanager 16 #![allow(missing_docs)] 17 18 use std::fs::OpenOptions; 19 use std::fs::{self, File}; 20 21 pub struct FileManager { 22 path: Option<String>, 23 file: Option<File>, 24 } 25 26 impl FileManager { remove_file(path: &str) -> std::io::Result<()>27 pub fn remove_file(path: &str) -> std::io::Result<()> { 28 fs::remove_file(path) 29 } 30 new(file_path: String) -> FileManager31 pub fn new(file_path: String) -> FileManager { 32 FileManager { 33 path: Some(file_path), 34 file: None, 35 } 36 } 37 open(&mut self) -> (bool, String)38 pub fn open(&mut self) -> (bool, String) { 39 let mut result = false; 40 let mut err_msg = String::from(""); 41 if let Some(path) = &self.path { 42 let mut _file = OpenOptions::new().read(true).open(path); 43 match _file { 44 Ok(f) => { 45 self.file = Some(f); 46 result = true; 47 } 48 Err(_e) => { 49 println!("failed to open file {:?}", _e); 50 err_msg = format!("Transfer {} failed: {:#?}.", path, _e); 51 result = false; 52 } 53 } 54 } 55 (result, err_msg) 56 } 57 file_size(&self) -> u6458 pub fn file_size(&self) -> u64 { 59 if let Some(f) = &self.file { 60 return f.metadata().unwrap().len(); 61 } 62 0 63 } 64 } 65