Add convenience function to read the content from a file into a string given a path

This commit is contained in:
Mathieu David 2016-03-27 18:36:57 +02:00
parent 15d26befcc
commit c3564f1699
1 changed files with 21 additions and 1 deletions

View File

@ -1,8 +1,28 @@
use std::path::{Path, Component}; use std::path::{Path, Component};
use std::error::Error; use std::error::Error;
use std::io; use std::io::{self, Read};
use std::fs::{self, metadata, File}; use std::fs::{self, metadata, File};
/// Takes a path to a file and try to read the file into a String
pub fn file_to_string(path: &Path) -> Result<String, Box<Error>> {
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => {
debug!("[*]: Failed to open {:?}", path);
return Err(Box::new(e));
},
};
let mut content = String::new();
if let Err(e) = file.read_to_string(&mut content) {
debug!("[*]: Failed to read {:?}", path);
return Err(Box::new(e));
}
Ok(content)
}
/// Takes a path and returns a path containing just enough `../` to point to the root of the given path. /// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
/// ///