simple_fs/
file.rs

1use crate::{Error, Result};
2use std::fs::{self, File};
3use std::io::{BufReader, BufWriter};
4use std::path::Path;
5
6pub fn create_file(file_path: impl AsRef<Path>) -> Result<File> {
7	let file_path = file_path.as_ref();
8	File::create(file_path).map_err(|e| Error::FileCantCreate((file_path, e).into()))
9}
10
11pub fn read_to_string(file_path: impl AsRef<Path>) -> Result<String> {
12	let file_path = file_path.as_ref();
13
14	if !file_path.is_file() {
15		return Err(Error::FileNotFound(file_path.to_string_lossy().to_string()));
16	}
17
18	let content = fs::read_to_string(file_path).map_err(|e| Error::FileCantRead((file_path, e).into()))?;
19
20	Ok(content)
21}
22
23pub fn open_file(path: impl AsRef<Path>) -> Result<File> {
24	let path = path.as_ref();
25	let f = File::open(path).map_err(|e| Error::FileCantOpen((path, e).into()))?;
26	Ok(f)
27}
28
29pub fn get_buf_reader(file: impl AsRef<Path>) -> Result<BufReader<File>> {
30	let file = file.as_ref();
31
32	let file = File::open(file).map_err(|e| Error::FileCantOpen((file, e).into()))?;
33
34	Ok(BufReader::new(file))
35}
36
37pub fn get_buf_writer(file_path: impl AsRef<Path>) -> Result<BufWriter<File>> {
38	let file_path = file_path.as_ref();
39
40	let file = create_file(file_path)?;
41
42	Ok(BufWriter::new(file))
43}