github | Crates.io |文档|问题| ChangElog
IN_PLACE库提供了用于读取和编写文件“就地”的内置类型:您编写的数据最终以您从您阅读的同一文件中读取,而IN_Place则需要为您提供临时文件。
例如,给定文件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.
以及以下程序:
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 ( ( ) )
}运行程序后,Somefile.txt将被编辑到位,将其简化为:
'Tws brllg, nd th slthy tvs
Dd gyr nd gmbl n th wb;
ll mmsy wr th brgvs,
nd th mm rths tgrb.
而且没有那些讨厌的元音的迹象!如果要保留这些讨厌的元音的迹象,则可以通过以下方式打开文件来保存文件的原始内容。
let inp = InPlace :: new ( "somefile.txt" )
. backup ( in_place :: Backup :: Append ( "~" . into ( ) ) )
. open ( ) ? ;或将其保存到某个hotherfile.txt上:
let inp = InPlace :: new ( "somefile.txt" )
. backup ( in_place :: Backup :: Path ( "someotherfile.txt" . into ( ) ) )
. open ( ) ? ;如果您不想编辑文件的一半决定(例如,因为发生了不可撤销的错误),请致电INP.Discard(),而不是INP.SAVE()将关闭文件句柄并将其重置为以前的方式。如果在没有保存的情况下删除INP,则任何更改也将丢弃,除非在这种情况下,任何错误都被默默地忽略。
下载源码
通过命令行克隆项目:
git clone https://github.com/jwodder/in-place-rs.git