-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
fs.rs
2764 lines (2654 loc) · 90.7 KB
/
fs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Filesystem manipulation operations.
//!
//! This module contains basic methods to manipulate the contents of the local
//! filesystem. All methods in this module represent cross-platform filesystem
//! operations. Extra platform-specific functionality can be found in the
//! extension traits of `std::os::$platform`.
#![stable(feature = "rust1", since = "1.0.0")]
#![deny(unsafe_op_in_unsafe_fn)]
#[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx", target_os = "xous"))))]
mod tests;
use crate::ffi::OsString;
use crate::fmt;
use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
use crate::path::{Path, PathBuf};
use crate::sealed::Sealed;
use crate::sync::Arc;
use crate::sys::fs as fs_imp;
use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
use crate::time::SystemTime;
/// An object providing access to an open file on the filesystem.
///
/// An instance of a `File` can be read and/or written depending on what options
/// it was opened with. Files also implement [`Seek`] to alter the logical cursor
/// that the file contains internally.
///
/// Files are automatically closed when they go out of scope. Errors detected
/// on closing are ignored by the implementation of `Drop`. Use the method
/// [`sync_all`] if these errors must be manually handled.
///
/// `File` does not buffer reads and writes. For efficiency, consider wrapping the
/// file in a [`BufReader`] or [`BufWriter`] when performing many small [`read`]
/// or [`write`] calls, unless unbuffered reads and writes are required.
///
/// # Examples
///
/// Creates a new file and write bytes to it (you can also use [`write`]):
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let mut file = File::create("foo.txt")?;
/// file.write_all(b"Hello, world!")?;
/// Ok(())
/// }
/// ```
///
/// Reads the contents of a file into a [`String`] (you can also use [`read`]):
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let mut file = File::open("foo.txt")?;
/// let mut contents = String::new();
/// file.read_to_string(&mut contents)?;
/// assert_eq!(contents, "Hello, world!");
/// Ok(())
/// }
/// ```
///
/// Using a buffered [`Read`]er:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let file = File::open("foo.txt")?;
/// let mut buf_reader = BufReader::new(file);
/// let mut contents = String::new();
/// buf_reader.read_to_string(&mut contents)?;
/// assert_eq!(contents, "Hello, world!");
/// Ok(())
/// }
/// ```
///
/// Note that, although read and write methods require a `&mut File`, because
/// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
/// still modify the file, either through methods that take `&File` or by
/// retrieving the underlying OS object and modifying the file that way.
/// Additionally, many operating systems allow concurrent modification of files
/// by different processes. Avoid assuming that holding a `&File` means that the
/// file will not change.
///
/// # Platform-specific behavior
///
/// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
/// perform synchronous I/O operations. Therefore the underlying file must not
/// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
///
/// [`BufReader`]: io::BufReader
/// [`BufWriter`]: io::BufWriter
/// [`sync_all`]: File::sync_all
/// [`write`]: File::write
/// [`read`]: File::read
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "File")]
pub struct File {
inner: fs_imp::File,
}
/// Metadata information about a file.
///
/// This structure is returned from the [`metadata`] or
/// [`symlink_metadata`] function or method and represents known
/// metadata about a file such as its permissions, size, modification
/// times, etc.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Clone)]
pub struct Metadata(fs_imp::FileAttr);
/// Iterator over the entries in a directory.
///
/// This iterator is returned from the [`read_dir`] function of this module and
/// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
/// information like the entry's path and possibly other metadata can be
/// learned.
///
/// The order in which this iterator returns entries is platform and filesystem
/// dependent.
///
/// # Errors
///
/// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
/// IO error during iteration.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Debug)]
pub struct ReadDir(fs_imp::ReadDir);
/// Entries returned by the [`ReadDir`] iterator.
///
/// An instance of `DirEntry` represents an entry inside of a directory on the
/// filesystem. Each entry can be inspected via methods to learn about the full
/// path or possibly other metadata through per-platform extension traits.
///
/// # Platform-specific behavior
///
/// On Unix, the `DirEntry` struct contains an internal reference to the open
/// directory. Holding `DirEntry` objects will consume a file handle even
/// after the `ReadDir` iterator is dropped.
///
/// Note that this [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[stable(feature = "rust1", since = "1.0.0")]
pub struct DirEntry(fs_imp::DirEntry);
/// Options and flags which can be used to configure how a file is opened.
///
/// This builder exposes the ability to configure how a [`File`] is opened and
/// what operations are permitted on the open file. The [`File::open`] and
/// [`File::create`] methods are aliases for commonly used options using this
/// builder.
///
/// Generally speaking, when using `OpenOptions`, you'll first call
/// [`OpenOptions::new`], then chain calls to methods to set each option, then
/// call [`OpenOptions::open`], passing the path of the file you're trying to
/// open. This will give you a [`io::Result`] with a [`File`] inside that you
/// can further operate on.
///
/// # Examples
///
/// Opening a file to read:
///
/// ```no_run
/// use std::fs::OpenOptions;
///
/// let file = OpenOptions::new().read(true).open("foo.txt");
/// ```
///
/// Opening a file for both reading and writing, as well as creating it if it
/// doesn't exist:
///
/// ```no_run
/// use std::fs::OpenOptions;
///
/// let file = OpenOptions::new()
/// .read(true)
/// .write(true)
/// .create(true)
/// .open("foo.txt");
/// ```
#[derive(Clone, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "FsOpenOptions")]
pub struct OpenOptions(fs_imp::OpenOptions);
/// Representation of the various timestamps on a file.
#[derive(Copy, Clone, Debug, Default)]
#[stable(feature = "file_set_times", since = "1.75.0")]
pub struct FileTimes(fs_imp::FileTimes);
/// Representation of the various permissions on a file.
///
/// This module only currently provides one bit of information,
/// [`Permissions::readonly`], which is exposed on all currently supported
/// platforms. Unix-specific functionality, such as mode bits, is available
/// through the [`PermissionsExt`] trait.
///
/// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "FsPermissions")]
pub struct Permissions(fs_imp::FilePermissions);
/// A structure representing a type of file with accessors for each file type.
/// It is returned by [`Metadata::file_type`] method.
#[stable(feature = "file_type", since = "1.1.0")]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
pub struct FileType(fs_imp::FileType);
/// A builder used to create directories in various manners.
///
/// This builder also supports platform-specific options.
#[stable(feature = "dir_builder", since = "1.6.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
#[derive(Debug)]
pub struct DirBuilder {
inner: fs_imp::DirBuilder,
recursive: bool,
}
/// Reads the entire contents of a file into a bytes vector.
///
/// This is a convenience function for using [`File::open`] and [`read_to_end`]
/// with fewer imports and without an intermediate variable.
///
/// [`read_to_end`]: Read::read_to_end
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
/// with automatic retries. See [io::Read] documentation for details.
///
/// # Examples
///
/// ```no_run
/// use std::fs;
///
/// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
/// let data: Vec<u8> = fs::read("image.jpg")?;
/// assert_eq!(data[0..3], [0xFF, 0xD8, 0xFF]);
/// Ok(())
/// }
/// ```
#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
fn inner(path: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let size = file.metadata().map(|m| m.len() as usize).ok();
let mut bytes = Vec::new();
bytes.try_reserve_exact(size.unwrap_or(0))?;
io::default_read_to_end(&mut file, &mut bytes, size)?;
Ok(bytes)
}
inner(path.as_ref())
}
/// Reads the entire contents of a file into a string.
///
/// This is a convenience function for using [`File::open`] and [`read_to_string`]
/// with fewer imports and without an intermediate variable.
///
/// [`read_to_string`]: Read::read_to_string
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// If the contents of the file are not valid UTF-8, then an error will also be
/// returned.
///
/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
/// with automatic retries. See [io::Read] documentation for details.
///
/// # Examples
///
/// ```no_run
/// use std::fs;
/// use std::error::Error;
///
/// fn main() -> Result<(), Box<dyn Error>> {
/// let message: String = fs::read_to_string("message.txt")?;
/// println!("{}", message);
/// Ok(())
/// }
/// ```
#[stable(feature = "fs_read_write", since = "1.26.0")]
pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
fn inner(path: &Path) -> io::Result<String> {
let mut file = File::open(path)?;
let size = file.metadata().map(|m| m.len() as usize).ok();
let mut string = String::new();
string.try_reserve_exact(size.unwrap_or(0))?;
io::default_read_to_string(&mut file, &mut string, size)?;
Ok(string)
}
inner(path.as_ref())
}
/// Writes a slice as the entire contents of a file.
///
/// This function will create a file if it does not exist,
/// and will entirely replace its contents if it does.
///
/// Depending on the platform, this function may fail if the
/// full directory path does not exist.
///
/// This is a convenience function for using [`File::create`] and [`write_all`]
/// with fewer imports.
///
/// [`write_all`]: Write::write_all
///
/// # Examples
///
/// ```no_run
/// use std::fs;
///
/// fn main() -> std::io::Result<()> {
/// fs::write("foo.txt", b"Lorem ipsum")?;
/// fs::write("bar.txt", "dolor sit")?;
/// Ok(())
/// }
/// ```
#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
File::create(path)?.write_all(contents)
}
inner(path.as_ref(), contents.as_ref())
}
impl File {
/// Attempts to open a file in read-only mode.
///
/// See the [`OpenOptions::open`] method for more details.
///
/// If you only need to read the entire file contents,
/// consider [`std::fs::read()`][self::read] or
/// [`std::fs::read_to_string()`][self::read_to_string] instead.
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::Read;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::open("foo.txt")?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().read(true).open(path.as_ref())
}
/// Opens a file in write-only mode.
///
/// This function will create a file if it does not exist,
/// and will truncate it if it does.
///
/// Depending on the platform, this function may fail if the
/// full directory path does not exist.
/// See the [`OpenOptions::open`] function for more details.
///
/// See also [`std::fs::write()`][self::write] for a simple function to
/// create a file with some given data.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::Write;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create("foo.txt")?;
/// f.write_all(&1234_u32.to_be_bytes())?;
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
}
/// Creates a new file in read-write mode; error if the file exists.
///
/// This function will create a file if it does not exist, or return an error if it does. This
/// way, if the call succeeds, the file returned is guaranteed to be new.
/// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
/// or another error based on the situation. See [`OpenOptions::open`] for a
/// non-exhaustive list of likely errors.
///
/// This option is useful because it is atomic. Otherwise between checking whether a file
/// exists and creating a new one, the file may have been created by another process (a TOCTOU
/// race condition / attack).
///
/// This can also be written using
/// `File::options().read(true).write(true).create_new(true).open(...)`.
///
/// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::Write;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create_new("foo.txt")?;
/// f.write_all("Hello, world!".as_bytes())?;
/// Ok(())
/// }
/// ```
#[stable(feature = "file_create_new", since = "1.77.0")]
pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
}
/// Returns a new OpenOptions object.
///
/// This function returns a new OpenOptions object that you can use to
/// open or create a file with specific options if `open()` or `create()`
/// are not appropriate.
///
/// It is equivalent to `OpenOptions::new()`, but allows you to write more
/// readable code. Instead of
/// `OpenOptions::new().append(true).open("example.log")`,
/// you can write `File::options().append(true).open("example.log")`. This
/// also avoids the need to import `OpenOptions`.
///
/// See the [`OpenOptions::new`] function for more details.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::Write;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::options().append(true).open("example.log")?;
/// writeln!(&mut f, "new line")?;
/// Ok(())
/// }
/// ```
#[must_use]
#[stable(feature = "with_options", since = "1.58.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "file_options")]
pub fn options() -> OpenOptions {
OpenOptions::new()
}
/// Attempts to sync all OS-internal file content and metadata to disk.
///
/// This function will attempt to ensure that all in-memory data reaches the
/// filesystem before returning.
///
/// This can be used to handle errors that would otherwise only be caught
/// when the `File` is closed, as dropping a `File` will ignore all errors.
/// Note, however, that `sync_all` is generally more expensive than closing
/// a file by dropping it, because the latter is not required to block until
/// the data has been written to the filesystem.
///
/// If synchronizing the metadata is not required, use [`sync_data`] instead.
///
/// [`sync_data`]: File::sync_data
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create("foo.txt")?;
/// f.write_all(b"Hello, world!")?;
///
/// f.sync_all()?;
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(alias = "fsync")]
pub fn sync_all(&self) -> io::Result<()> {
self.inner.fsync()
}
/// This function is similar to [`sync_all`], except that it might not
/// synchronize file metadata to the filesystem.
///
/// This is intended for use cases that must synchronize content, but don't
/// need the metadata on disk. The goal of this method is to reduce disk
/// operations.
///
/// Note that some platforms may simply implement this in terms of
/// [`sync_all`].
///
/// [`sync_all`]: File::sync_all
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create("foo.txt")?;
/// f.write_all(b"Hello, world!")?;
///
/// f.sync_data()?;
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(alias = "fdatasync")]
pub fn sync_data(&self) -> io::Result<()> {
self.inner.datasync()
}
/// Truncates or extends the underlying file, updating the size of
/// this file to become `size`.
///
/// If the `size` is less than the current file's size, then the file will
/// be shrunk. If it is greater than the current file's size, then the file
/// will be extended to `size` and have all of the intermediate data filled
/// in with 0s.
///
/// The file's cursor isn't changed. In particular, if the cursor was at the
/// end and the file is shrunk using this operation, the cursor will now be
/// past the end.
///
/// # Errors
///
/// This function will return an error if the file is not opened for writing.
/// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
/// will be returned if the desired length would cause an overflow due to
/// the implementation specifics.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create("foo.txt")?;
/// f.set_len(10)?;
/// Ok(())
/// }
/// ```
///
/// Note that this method alters the content of the underlying file, even
/// though it takes `&self` rather than `&mut self`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set_len(&self, size: u64) -> io::Result<()> {
self.inner.truncate(size)
}
/// Queries metadata about the underlying file.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::open("foo.txt")?;
/// let metadata = f.metadata()?;
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn metadata(&self) -> io::Result<Metadata> {
self.inner.file_attr().map(Metadata)
}
/// Creates a new `File` instance that shares the same underlying file handle
/// as the existing `File` instance. Reads, writes, and seeks will affect
/// both `File` instances simultaneously.
///
/// # Examples
///
/// Creates two handles for a file named `foo.txt`:
///
/// ```no_run
/// use std::fs::File;
///
/// fn main() -> std::io::Result<()> {
/// let mut file = File::open("foo.txt")?;
/// let file_copy = file.try_clone()?;
/// Ok(())
/// }
/// ```
///
/// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
/// two handles, seek one of them, and read the remaining bytes from the
/// other handle:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::SeekFrom;
/// use std::io::prelude::*;
///
/// fn main() -> std::io::Result<()> {
/// let mut file = File::open("foo.txt")?;
/// let mut file_copy = file.try_clone()?;
///
/// file.seek(SeekFrom::Start(3))?;
///
/// let mut contents = vec![];
/// file_copy.read_to_end(&mut contents)?;
/// assert_eq!(contents, b"def\n");
/// Ok(())
/// }
/// ```
#[stable(feature = "file_try_clone", since = "1.9.0")]
pub fn try_clone(&self) -> io::Result<File> {
Ok(File { inner: self.inner.duplicate()? })
}
/// Changes the permissions on the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `fchmod` function on Unix and
/// the `SetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission change
/// attributes on the underlying file. It may also return an error in other
/// os-specific unspecified cases.
///
/// # Examples
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
/// use std::fs::File;
///
/// let file = File::open("foo.txt")?;
/// let mut perms = file.metadata()?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms)?;
/// Ok(())
/// }
/// ```
///
/// Note that this method alters the permissions of the underlying file,
/// even though it takes `&self` rather than `&mut self`.
#[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
#[stable(feature = "set_permissions_atomic", since = "1.16.0")]
pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
self.inner.set_permissions(perm.0)
}
/// Changes the timestamps of the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `futimens` function on Unix (falling back to
/// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission to change timestamps on the
/// underlying file. It may also return an error in other os-specific unspecified cases.
///
/// This function may return an error if the operating system lacks support to change one or
/// more of the timestamps set in the `FileTimes` structure.
///
/// # Examples
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
/// use std::fs::{self, File, FileTimes};
///
/// let src = fs::metadata("src")?;
/// let dest = File::options().write(true).open("dest")?;
/// let times = FileTimes::new()
/// .set_accessed(src.accessed()?)
/// .set_modified(src.modified()?);
/// dest.set_times(times)?;
/// Ok(())
/// }
/// ```
#[stable(feature = "file_set_times", since = "1.75.0")]
#[doc(alias = "futimens")]
#[doc(alias = "futimes")]
#[doc(alias = "SetFileTime")]
pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
self.inner.set_times(times.0)
}
/// Changes the modification time of the underlying file.
///
/// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
#[stable(feature = "file_set_times", since = "1.75.0")]
#[inline]
pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
self.set_times(FileTimes::new().set_modified(time))
}
}
// In addition to the `impl`s here, `File` also has `impl`s for
// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
impl AsInner<fs_imp::File> for File {
#[inline]
fn as_inner(&self) -> &fs_imp::File {
&self.inner
}
}
impl FromInner<fs_imp::File> for File {
fn from_inner(f: fs_imp::File) -> File {
File { inner: f }
}
}
impl IntoInner<fs_imp::File> for File {
fn into_inner(self) -> fs_imp::File {
self.inner
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
/// Indicates how much extra capacity is needed to read the rest of the file.
fn buffer_capacity_required(mut file: &File) -> Option<usize> {
let size = file.metadata().map(|m| m.len()).ok()?;
let pos = file.stream_position().ok()?;
// Don't worry about `usize` overflow because reading will fail regardless
// in that case.
Some(size.saturating_sub(pos) as usize)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Read for &File {
/// Reads some bytes from the file.
///
/// See [`Read::read`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `read` function on Unix and
/// the `NtReadFile` function on Windows. Note that this [may change in
/// the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
/// Like `read`, except that it reads into a slice of buffers.
///
/// See [`Read::read_vectored`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `readv` function on Unix and
/// falls back to the `read` implementation on Windows. Note that this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[inline]
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.inner.read_vectored(bufs)
}
#[inline]
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
self.inner.read_buf(cursor)
}
/// Determines if `File` has an efficient `read_vectored` implementation.
///
/// See [`Read::is_read_vectored`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently returns `true` on Unix an `false` on Windows.
/// Note that this [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[inline]
fn is_read_vectored(&self) -> bool {
self.inner.is_read_vectored()
}
// Reserves space in the buffer based on the file size when available.
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
let size = buffer_capacity_required(self);
buf.try_reserve(size.unwrap_or(0))?;
io::default_read_to_end(self, buf, size)
}
// Reserves space in the buffer based on the file size when available.
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
let size = buffer_capacity_required(self);
buf.try_reserve(size.unwrap_or(0))?;
io::default_read_to_string(self, buf, size)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Write for &File {
/// Writes some bytes to the file.
///
/// See [`Write::write`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `write` function on Unix and
/// the `NtWriteFile` function on Windows. Note that this [may change in
/// the future][changes].
///
/// [changes]: io#platform-specific-behavior
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(buf)
}
/// Like `write`, except that it writes into a slice of buffers.
///
/// See [`Write::write_vectored`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `writev` function on Unix
/// and falls back to the `write` implementation on Windows. Note that this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.inner.write_vectored(bufs)
}
/// Determines if `File` has an efficient `write_vectored` implementation.
///
/// See [`Write::is_write_vectored`] docs for more info.
///
/// # Platform-specific behavior
///
/// This function currently returns `true` on Unix an `false` on Windows.
/// Note that this [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[inline]
fn is_write_vectored(&self) -> bool {
self.inner.is_write_vectored()
}
/// Flushes the file, ensuring that all intermediately buffered contents
/// reach their destination.
///
/// See [`Write::flush`] docs for more info.
///
/// # Platform-specific behavior
///
/// Since a `File` structure doesn't contain any buffers, this function is
/// currently a no-op on Unix and Windows. Note that this [may change in
/// the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Seek for &File {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.inner.seek(pos)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Read for File {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&*self).read(buf)
}
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
(&*self).read_vectored(bufs)
}
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
(&*self).read_buf(cursor)
}
#[inline]
fn is_read_vectored(&self) -> bool {
(&&*self).is_read_vectored()
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(&*self).read_to_end(buf)
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(&*self).read_to_string(buf)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Write for File {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&*self).write(buf)
}
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
(&*self).write_vectored(bufs)
}
#[inline]
fn is_write_vectored(&self) -> bool {
(&&*self).is_write_vectored()
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
(&*self).flush()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Seek for File {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
(&*self).seek(pos)
}
}
#[stable(feature = "io_traits_arc", since = "1.73.0")]
impl Read for Arc<File> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&**self).read(buf)
}
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
(&**self).read_vectored(bufs)
}
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
(&**self).read_buf(cursor)
}
#[inline]
fn is_read_vectored(&self) -> bool {
(&**self).is_read_vectored()
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(&**self).read_to_end(buf)
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(&**self).read_to_string(buf)
}
}
#[stable(feature = "io_traits_arc", since = "1.73.0")]
impl Write for Arc<File> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&**self).write(buf)
}
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
(&**self).write_vectored(bufs)
}
#[inline]
fn is_write_vectored(&self) -> bool {
(&**self).is_write_vectored()
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
(&**self).flush()
}
}
#[stable(feature = "io_traits_arc", since = "1.73.0")]
impl Seek for Arc<File> {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
(&**self).seek(pos)
}
}
impl OpenOptions {