use std::{fs, io};
use std::fs::File;
use std::io::Read;
use std::path::Path;
use cbsk_base::log;
pub use write::*;
pub mod write;
#[allow(non_upper_case_globals)]
pub static separator: char = {
#[cfg(windows)] { '\\' }
#[cfg(not(windows))] '/'
};
#[allow(non_upper_case_globals)]
pub static separator_str: &str = {
#[cfg(windows)] { "\\" }
#[cfg(not(windows))] "/"
};
macro_rules! err_log {
($f:ident($file:expr),$name:expr) => {
if let Err(e) = $f($file) {
log::error!("{}[{:?}] fail: {e:?}",$name,$file);
}
};
}
pub fn create_dir(dir: &Path) {
err_log!(try_create_dir(dir),"create dir");
}
pub fn try_create_dir(dir: &Path) -> io::Result<()> {
if dir.exists() {
return Ok(());
}
just_create_dir(dir)
}
pub fn create_file(file: &Path) {
err_log!(try_create_file(file),"create file");
}
pub fn try_create_file(file: &Path) -> io::Result<()> {
if file.exists() {
return Ok(());
}
if file.is_dir() {
return Err(io::Error::other(format!("{file:?} is a directory")));
}
just_create_parent_dir(file)?;
File::create(file)?;
Ok(())
}
fn just_create_parent_dir(dir: &Path) -> io::Result<()> {
let parent = cbsk_base::match_some_return!(dir.parent(),Ok(()));
fs::create_dir_all(parent)
}
fn just_create_dir(dir: &Path) -> io::Result<()> {
if dir.is_dir() {
return fs::create_dir_all(dir);
}
just_create_parent_dir(dir)
}
pub fn read_to_vec(file: &Path) -> Vec<u8> {
try_read_to_vec(file).unwrap_or_else(|e| {
log::error!("read file[{file:?}] to vec fail: {e:?}");
Vec::new()
})
}
pub fn try_read_to_vec(file: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(file)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
Ok(buf)
}
pub fn read_to_str(file: &Path) -> String {
try_read_to_str(file).unwrap_or_else(|e| {
log::error!("read file[{file:?}] to string fail: {e:?}");
String::new()
})
}
pub fn try_read_to_str(file: &Path) -> io::Result<String> {
let mut file = File::open(file)?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
Ok(buf)
}
pub fn recreate_file(path: &Path) -> io::Result<File> {
if path.exists() {
fs::remove_file(path)?;
}
just_create_parent_dir(path)?;
just_create_file(path)
}
pub fn open_create_file(path: &Path) -> io::Result<File> {
if path.exists() {
return File::options().read(true).write(true).append(true).open(path);
}
just_create_parent_dir(path)?;
just_create_file(path)
}
pub fn just_create_file(path: &Path) -> io::Result<File> {
File::options().read(true).write(true).create(true).truncate(true).open(path)
}
pub fn just_open_file(path: &Path) -> io::Result<File> {
File::options().read(true).write(true).append(true).open(path)
}