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> {
let file = std::fs::File::open("/etc/timezone")?;
use std::io::{BufRead, BufReader};
let mut reader = BufReader::new(file);
let mut line = String::new();
let _ = reader.read_line(&mut line)?;
let line = tools::file_read_firstline("/etc/timezone")?;
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) })
}
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
/// is then renamed.
pub fn file_set_contents<P: AsRef<Path>>(