3 unstable releases
0.2.1 | Jul 25, 2024 |
---|---|
0.2.0 | Dec 22, 2023 |
0.1.0 | May 18, 2023 |
#696 in Filesystem
287 downloads per month
82KB
1.5K
SLoC
GitHub | crates.io | Documentation | Issues | Changelog
The in_place
library provides an InPlace
type for reading & writing a file
"in-place": data that you write ends up at the same filepath that you read
from, and in_place
takes care of all the necessary mucking about with
temporary files for you.
For example, given the file somefile.txt
:
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
and the following program:
use in_place::InPlace;
use std::io::{BufRead, BufReader, Write};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let inp = InPlace::new("somefile.txt").open()?;
let reader = BufReader::new(inp.reader());
let mut writer = inp.writer();
for line in reader.lines() {
let mut line = line?;
line.retain(|ch| !"AEIOUaeiou".contains(ch));
writeln!(writer, "{line}")?;
}
inp.save()?;
Ok(())
}
after running the program, somefile.txt
will have been edited in place,
reducing it to just:
'Tws brllg, nd th slthy tvs
Dd gyr nd gmbl n th wb;
ll mmsy wr th brgvs,
nd th mm rths tgrb.
and no sign of those pesky vowels remains! If you want a sign of those pesky
vowels to remain, you can instead save the file's original contents in, say,
somefile.txt~
by opening the file with:
let inp = InPlace::new("somefile.txt")
.backup(in_place::Backup::Append("~".into()))
.open()?;
or save to someotherfile.txt
with:
let inp = InPlace::new("somefile.txt")
.backup(in_place::Backup::Path("someotherfile.txt".into()))
.open()?;
If you decide halfway through that you don't want to edit the file (say,
because an unrecoverable error occurs), calling inp.discard()
instead of
inp.save()
will close the file handles and reset things to the way they were
before. Any changes are also discarded if inp
is dropped without saving,
except that in that case any errors are silently ignored.
Dependencies
~1.7–9.5MB
~114K SLoC