tools.rs: implement file_read_firstline

This commit is contained in:
Dietmar Maurer 2019-01-24 10:43:30 +01:00
parent 0463602a79
commit 447787ab7c
2 changed files with 18 additions and 9 deletions

View File

@ -9,15 +9,7 @@ use chrono::prelude::*;
fn read_etc_localtime() -> Result<String, Error> { fn read_etc_localtime() -> Result<String, Error> {
let file = std::fs::File::open("/etc/timezone")?; let line = tools::file_read_firstline("/etc/timezone")?;
use std::io::{BufRead, BufReader};
let mut reader = BufReader::new(file);
let mut line = String::new();
let _ = reader.read_line(&mut line)?;
Ok(line.trim().to_owned()) Ok(line.trim().to_owned())
} }

View File

@ -59,6 +59,23 @@ pub fn map_struct_mut<T>(buffer: &mut [u8]) -> Result<&mut T, Error> {
Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }) Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) })
} }
pub fn file_read_firstline<P: AsRef<Path>>(path: P) -> Result<String, std::io::Error> {
let path = path.as_ref();
let file = std::fs::File::open(path)?;
use std::io::{BufRead, BufReader};
let mut reader = BufReader::new(file);
let mut line = String::new();
let _ = reader.read_line(&mut line)?;
Ok(line)
}
/// Atomically write a file. We first create a temporary file, which /// Atomically write a file. We first create a temporary file, which
/// is then renamed. /// is then renamed.
pub fn file_set_contents<P: AsRef<Path>>( pub fn file_set_contents<P: AsRef<Path>>(