Browse Source

src/util/file: add functions to load and save files from string

ghassmo 4 years ago
parent
commit
e521a8a05c
1 changed files with 19 additions and 1 deletions
  1. 19 1
      src/util/file.rs

+ 19 - 1
src/util/file.rs

@@ -1,9 +1,27 @@
-use std::{fs::File, io::BufReader, path::Path};
+use std::{
+    fs::File,
+    io::{BufReader, Read, Write},
+    path::Path,
+};
 
 use serde::{de::DeserializeOwned, Serialize};
 
 use crate::Result;
 
+pub fn load_file(path: &Path) -> Result<String> {
+    let file = File::open(path)?;
+    let mut reader = BufReader::new(file);
+    let mut st = String::new();
+    reader.read_to_string(&mut st)?;
+    Ok(st)
+}
+
+pub fn save_file(path: &Path, st: &str) -> Result<()> {
+    let mut file = File::create(path)?;
+    file.write_all(st.as_bytes())?;
+    Ok(())
+}
+
 pub fn load_json_file<T: DeserializeOwned>(path: &Path) -> Result<T> {
     let file = File::open(path)?;
     let reader = BufReader::new(file);