libbeaglebone/
util.rs

1//! General utility functions used internally throughout the crate, such as
2//! writing to sysfs files.
3
4use errors::*;
5use std::fs::File;
6use std::io::{Write, Read};
7
8/// Writes data to a sysfs device file.
9pub fn write_file(data: &str, path: &str) -> Result<()> {
10  // Open the file (write-only) and write data to it
11  File::create(&path)
12    .chain_err(|| format!("Failed to open file {} for writing", &path))?
13    .write_all(data.as_bytes())
14    .chain_err(|| format!("Failed to write to file {}", &path))?;
15  Ok(())
16}
17
18/// Reads from a sysfs device file.
19pub fn read_file(path: &str) -> Result<String> {
20  let mut value_str = String::new();
21
22  // Open the file (read-only) and read it's contents into the string
23  let _ = File::open(path)
24    .chain_err(|| format!("Failed to open file {} for reading", &path))?
25    .read_to_string(&mut value_str)
26    .chain_err(|| format!("Failed to read from file {}", &path))?;
27
28  Ok(value_str)
29}