1use std::io::{Read, Seek, SeekFrom, Write};
2use crate::myerror::MyError;
3use std::path::Path;
4
5
6
7
8pub fn file_read(path:&str)->Result<String,MyError>{
9 let mut file = std::fs::File::open(path)?;
10 let mut contents = String::new();
11 file.read_to_string(&mut contents)?;
12 Ok(contents)
13}
14pub fn file_write(path:&str,content:&str)-> Result<usize,MyError> {
15 let mut file=std::fs::OpenOptions::new().create(true).append(false).write(true).truncate(true).open(path)?;
16 let bytes=content.as_bytes();
17 file.write_all(bytes)?;
18 file.write_all("\n".as_bytes());
19 Ok(bytes.len())
20}
21
22pub fn file_read_string(path:&str)->String{
23 let fileresult=file_read(path);
24 fileresult.is_err() && return String::new();
25 fileresult.unwrap()
26}
27pub fn file_read_bytes(path:&str)->Result<Vec<u8>,MyError>{
28 let mut file = std::fs::File::open(path)?;
29 let mut bytes= vec![];
30 file.seek(SeekFrom::Start(0));
31 file.read_to_end(&mut bytes);
32 Ok(bytes)
33}
34
35pub fn file_write_bytes(path:&str,bytes:&[u8])-> Result<usize,MyError> {
36
37 let target_path = Path::new(path);
38 let mut file:std::fs::File;
39 if !target_path.exists(){
40 file = std::fs::File::create(path)?;
41 } else{
42 file = std::fs::File::open(path)?;
43 }
44
45 file.write_all(bytes)?;
46 Ok(bytes.len())
47}
48
49pub fn file_append(path:&str,content:&str)-> Result<usize,MyError> {
50 let mut file=std::fs::OpenOptions::new().create(true).write(true).append(true).open(path)?;
51 let bytes=content.as_bytes();
52 file.write_all(bytes)?;
53 file.write_all("\n".as_bytes());
54 Ok(bytes.len())
55}