Confrontare files in Rust
In questo articolo vi propongo due funzioni per confrontare due files in Rust.
La prima è abbastanza generica, ma è consigliata soprattutto per piccoli files.
Inoltre io ho fatto il trim delle stringhe; vedete se invece volete controllare anche gli spazi.
La seconda è consigliata nel caso di files di grandi dimensioni.
Non sono richieste librerie esterne.
Ecco il codice:
/// Confronta il contenuto di due files
pub fn files_are_equal(path1: &str, path2: &str) -> io::Result<bool> {
let file1 = fs::read_to_string(path1)?;
let file2 = fs::read_to_string(path2)?;
Ok(file1.trim() == file2.trim())
}
/// Confronta il contenuto di due files
/// Da usare principalmente con file di grandi dimensioni
pub fn files_big_are_equal(path1: &str, path2: &str) -> io::Result<bool> {
let mut f1 = File::open(path1)?;
let mut f2 = File::open(path2)?;
let mut buf1 = [0u8; 8192];
let mut buf2 = [0u8; 8192];
loop {
let n1 = f1.read(&mut buf1)?;
let n2 = f2.read(&mut buf2)?;
if n1 != n2 {
return Ok(false);
}
if n1 == 0 {
break;
}
if buf1[..n1] != buf2[..n2] {
return Ok(false);
}
}
Ok(true)
}
Voi conoscete altri modi?
Enjoy!
rust read_to_string
Commentami!