From c3564f1699d46ec6172b989b6b54d7fa213b9f0d Mon Sep 17 00:00:00 2001 From: Mathieu David Date: Sun, 27 Mar 2016 18:36:57 +0200 Subject: [PATCH] Add convenience function to read the content from a file into a string given a path --- src/utils/fs.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/utils/fs.rs b/src/utils/fs.rs index fd227ded..189cca92 100644 --- a/src/utils/fs.rs +++ b/src/utils/fs.rs @@ -1,8 +1,28 @@ use std::path::{Path, Component}; use std::error::Error; -use std::io; +use std::io::{self, Read}; 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> { + 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. ///