add remove line

This commit is contained in:
grimhilt
2023-06-15 17:32:57 +02:00
parent b00266a93e
commit 35adfab983
4 changed files with 95 additions and 7 deletions

View File

@@ -1,9 +1,7 @@
use std::path::{Path, PathBuf};
use std::io::{self, BufRead};
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Write};
use std::fs::{self, File, OpenOptions};
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
pub fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
@@ -18,3 +16,28 @@ pub fn read_folder(path: PathBuf) -> io::Result<Vec<PathBuf>> {
entries.sort();
Ok(entries)
}
pub fn rm_line(path: PathBuf, line_to_del: &str) -> io::Result<()> {
let file = File::open(path.clone())?;
let reader = BufReader::new(&file);
let mut temp_file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(format!("{}_temp", path.display()))?;
for line in reader.lines() {
let l = line?;
if l.trim() != line_to_del.trim() {
writeln!(temp_file, "{}", l)?;
}
}
drop(file);
drop(temp_file);
fs::remove_file(path.clone())?;
fs::rename(format!("{}_temp", path.display()), path)?;
Ok(())
}