1use std::{fs, io};
2use std::fs::File;
3use std::io::Read;
4use std::path::Path;
5use cbsk_base::log;
6pub use write::*;
7
8pub mod write;
9
10#[allow(non_upper_case_globals)]
12pub static separator: char = {
13 #[cfg(windows)] { '\\' }
14 #[cfg(not(windows))] '/'
15};
16
17#[allow(non_upper_case_globals)]
19pub static separator_str: &str = {
20 #[cfg(windows)] { "\\" }
21 #[cfg(not(windows))] "/"
22};
23
24macro_rules! err_log {
26 ($f:ident($file:expr),$name:expr) => {
27 if let Err(e) = $f($file) {
28 log::error!("{}[{:?}] fail: {e:?}",$name,$file);
29 }
30 };
31}
32
33pub fn create_dir(dir: &Path) {
38 err_log!(try_create_dir(dir),"create dir");
39}
40
41pub fn try_create_dir(dir: &Path) -> io::Result<()> {
44 if dir.exists() {
45 return Ok(());
46 }
47 just_create_dir(dir)
48}
49
50pub fn create_file(file: &Path) {
55 err_log!(try_create_file(file),"create file");
56}
57
58pub fn try_create_file(file: &Path) -> io::Result<()> {
62 if file.exists() {
63 return Ok(());
64 }
65 if file.is_dir() {
66 return Err(io::Error::other(format!("{file:?} is a directory")));
67 }
68
69 just_create_parent_dir(file)?;
70 File::create(file)?;
71 Ok(())
72}
73
74fn just_create_parent_dir(dir: &Path) -> io::Result<()> {
76 let parent = cbsk_base::match_some_return!(dir.parent(),Ok(()));
80 fs::create_dir_all(parent)
81}
82
83fn just_create_dir(dir: &Path) -> io::Result<()> {
85 if dir.is_dir() {
86 return fs::create_dir_all(dir);
87 }
88
89 just_create_parent_dir(dir)
90}
91
92pub fn read_to_vec(file: &Path) -> Vec<u8> {
97 try_read_to_vec(file).unwrap_or_else(|e| {
98 log::error!("read file[{file:?}] to vec fail: {e:?}");
99 Vec::new()
100 })
101}
102
103pub fn try_read_to_vec(file: &Path) -> io::Result<Vec<u8>> {
106 let mut file = File::open(file)?;
107 let mut buf = Vec::new();
108 file.read_to_end(&mut buf)?;
109 Ok(buf)
110}
111
112pub fn read_to_str(file: &Path) -> String {
117 try_read_to_str(file).unwrap_or_else(|e| {
118 log::error!("read file[{file:?}] to string fail: {e:?}");
119 String::new()
120 })
121}
122
123pub fn try_read_to_str(file: &Path) -> io::Result<String> {
126 let mut file = File::open(file)?;
127 let mut buf = String::new();
128 file.read_to_string(&mut buf)?;
129 Ok(buf)
130}
131
132pub fn recreate_file(path: &Path) -> io::Result<File> {
134 if path.exists() {
135 fs::remove_file(path)?;
136 }
137
138 just_create_parent_dir(path)?;
139 just_create_file(path)
140}
141
142pub fn open_create_file(path: &Path) -> io::Result<File> {
144 if path.exists() {
145 return File::options().read(true).write(true).append(true).open(path);
146 }
147
148 just_create_parent_dir(path)?;
149 just_create_file(path)
150}
151
152pub fn just_create_file(path: &Path) -> io::Result<File> {
156 File::options().read(true).write(true).create(true).truncate(true).open(path)
157}
158
159pub fn just_open_file(path: &Path) -> io::Result<File> {
163 File::options().read(true).write(true).append(true).open(path)
164}