1use std::fmt::Display;
2use std::fs;
3use std::io::{Read, Write};
4use std::path::Path;
5
6pub struct File;
8
9impl File {
10 pub fn read<P: AsRef<Path>>(path: P) -> Result<String, String> {
12 let mut file = fs::OpenOptions::new().read(true).open(&path);
13
14 match &mut file {
15 Ok(f) => {
16 let mut contents = String::from("");
17 match f.read_to_string(&mut contents) {
18 Ok(_) => Ok(contents),
19 Err(e) => Err(format!(
20 "Could not read from file '{}' because {}",
21 match path.as_ref().to_str() {
22 Some(s) => s,
23 None => "",
24 },
25 e.to_string()
26 )),
27 }
28 }
29 Err(e) => Err(format!(
30 "Could not open file '{}' because {}",
31 match path.as_ref().to_str() {
32 Some(s) => s,
33 None => "",
34 },
35 e.to_string()
36 )),
37 }
38 }
39
40 pub fn write<P: AsRef<Path>, S: Display>(path: P, contents: S) -> Result<(), String> {
44 let mut file = fs::OpenOptions::new()
45 .create(true)
46 .write(true)
47 .truncate(true)
48 .open(&path);
49
50 match &mut file {
51 Ok(f) => match writeln!(f, "{}", contents) {
52 Ok(_) => Ok(()),
53 Err(e) => Err(format!(
54 "Could not open file '{}' because {}",
55 match path.as_ref().to_str() {
56 Some(s) => s,
57 None => "",
58 },
59 e.to_string()
60 )),
61 },
62 Err(e) => Err(format!(
63 "Could not open file '{}' because {}",
64 match path.as_ref().to_str() {
65 Some(s) => s,
66 None => "",
67 },
68 e.to_string()
69 )),
70 }
71 }
72
73 pub fn append<P: AsRef<Path>, S: Display>(path: P, contents: S) -> Result<(), String> {
76 let mut file = fs::OpenOptions::new().append(true).write(true).open(&path);
77
78 match &mut file {
79 Ok(f) => match writeln!(f, "{}", contents) {
80 Ok(_) => Ok(()),
81 Err(e) => Err(format!(
82 "Could not open file '{}' because {}",
83 match path.as_ref().to_str() {
84 Some(s) => s,
85 None => "",
86 },
87 e.to_string()
88 )),
89 },
90 Err(e) => Err(format!(
91 "Could not open file '{}' because {}",
92 match path.as_ref().to_str() {
93 Some(s) => s,
94 None => "",
95 },
96 e.to_string()
97 )),
98 }
99 }
100}