File tree Expand file tree Collapse file tree 1 file changed +8
-1
lines changed
Expand file tree Collapse file tree 1 file changed +8
-1
lines changed Original file line number Diff line number Diff line change @@ -346,7 +346,14 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
346346#[ stable( feature = "fs_read_write_bytes" , since = "1.26.0" ) ]
347347pub fn write < P : AsRef < Path > , C : AsRef < [ u8 ] > > ( path : P , contents : C ) -> io:: Result < ( ) > {
348348 fn inner ( path : & Path , contents : & [ u8 ] ) -> io:: Result < ( ) > {
349- File :: create ( path) ?. write_all ( contents)
349+ // As an optimization we don't truncate.
350+ // Instead we overwrite the existing content and then set the file length
351+ // to the number of written bytes (whether or not writing succeeds).
352+ let mut f = OpenOptions :: new ( ) . write ( true ) . create ( true ) . open ( path) ?;
353+ let r = f. write_all ( contents) ;
354+ let r2 = f. stream_position ( ) . and_then ( |pos| f. set_len ( pos) ) ;
355+ // Return the most pertinent error, if any.
356+ if r. is_err ( ) { r } else { r2 }
350357 }
351358 inner ( path. as_ref ( ) , contents. as_ref ( ) )
352359}
You can’t perform that action at this time.
0 commit comments