Skip to content

Commit c3564f1

Browse files
committed
Add convenience function to read the content from a file into a string given a path
1 parent 15d26be commit c3564f1

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/utils/fs.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
11
use std::path::{Path, Component};
22
use std::error::Error;
3-
use std::io;
3+
use std::io::{self, Read};
44
use std::fs::{self, metadata, File};
55

6+
/// Takes a path to a file and try to read the file into a String
7+
8+
pub fn file_to_string(path: &Path) -> Result<String, Box<Error>> {
9+
let mut file = match File::open(path) {
10+
Ok(f) => f,
11+
Err(e) => {
12+
debug!("[*]: Failed to open {:?}", path);
13+
return Err(Box::new(e));
14+
},
15+
};
16+
17+
let mut content = String::new();
18+
19+
if let Err(e) = file.read_to_string(&mut content) {
20+
debug!("[*]: Failed to read {:?}", path);
21+
return Err(Box::new(e));
22+
}
23+
24+
Ok(content)
25+
}
626

727
/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
828
///

0 commit comments

Comments
 (0)