xref: /drstd/src/std/fs.rs (revision 9670759b785600bf6315e4173e46a602f16add7a)
1 //! Filesystem manipulation operations.
2 //!
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
7 
8 #![deny(unsafe_op_in_unsafe_fn)]
9 
10 use crate::std::ffi::OsString;
11 use crate::std::fmt;
12 use crate::std::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
13 use crate::std::path::{Path, PathBuf};
14 use crate::std::sealed::Sealed;
15 use crate::std::sync::Arc;
16 use crate::std::sys::fs as fs_imp;
17 use crate::std::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
18 use crate::std::time::SystemTime;
19 
20 /// An object providing access to an open file on the filesystem.
21 ///
22 /// An instance of a `File` can be read and/or written depending on what options
23 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
24 /// that the file contains internally.
25 ///
26 /// Files are automatically closed when they go out of scope.  Errors detected
27 /// on closing are ignored by the implementation of `Drop`.  Use the method
28 /// [`sync_all`] if these errors must be manually handled.
29 ///
30 /// # Examples
31 ///
32 /// Creates a new file and write bytes to it (you can also use [`write()`]):
33 ///
34 /// ```no_run
35 /// use std::fs::File;
36 /// use std::io::prelude::*;
37 ///
38 /// fn main() -> std::io::Result<()> {
39 ///     let mut file = File::create("foo.txt")?;
40 ///     file.write_all(b"Hello, world!")?;
41 ///     Ok(())
42 /// }
43 /// ```
44 ///
45 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
46 ///
47 /// ```no_run
48 /// use std::fs::File;
49 /// use std::io::prelude::*;
50 ///
51 /// fn main() -> std::io::Result<()> {
52 ///     let mut file = File::open("foo.txt")?;
53 ///     let mut contents = String::new();
54 ///     file.read_to_string(&mut contents)?;
55 ///     assert_eq!(contents, "Hello, world!");
56 ///     Ok(())
57 /// }
58 /// ```
59 ///
60 /// It can be more efficient to read the contents of a file with a buffered
61 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
62 ///
63 /// ```no_run
64 /// use std::fs::File;
65 /// use std::io::BufReader;
66 /// use std::io::prelude::*;
67 ///
68 /// fn main() -> std::io::Result<()> {
69 ///     let file = File::open("foo.txt")?;
70 ///     let mut buf_reader = BufReader::new(file);
71 ///     let mut contents = String::new();
72 ///     buf_reader.read_to_string(&mut contents)?;
73 ///     assert_eq!(contents, "Hello, world!");
74 ///     Ok(())
75 /// }
76 /// ```
77 ///
78 /// Note that, although read and write methods require a `&mut File`, because
79 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
80 /// still modify the file, either through methods that take `&File` or by
81 /// retrieving the underlying OS object and modifying the file that way.
82 /// Additionally, many operating systems allow concurrent modification of files
83 /// by different processes. Avoid assuming that holding a `&File` means that the
84 /// file will not change.
85 ///
86 /// # Platform-specific behavior
87 ///
88 /// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
89 /// perform synchronous I/O operations. Therefore the underlying file must not
90 /// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
91 ///
92 /// [`BufReader<R>`]: io::BufReader
93 /// [`sync_all`]: File::sync_all
94 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
95 pub struct File {
96     inner: fs_imp::File,
97 }
98 
99 /// Metadata information about a file.
100 ///
101 /// This structure is returned from the [`metadata`] or
102 /// [`symlink_metadata`] function or method and represents known
103 /// metadata about a file such as its permissions, size, modification
104 /// times, etc.
105 #[derive(Clone)]
106 pub struct Metadata(fs_imp::FileAttr);
107 
108 /// Iterator over the entries in a directory.
109 ///
110 /// This iterator is returned from the [`read_dir`] function of this module and
111 /// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
112 /// information like the entry's path and possibly other metadata can be
113 /// learned.
114 ///
115 /// The order in which this iterator returns entries is platform and filesystem
116 /// dependent.
117 ///
118 /// # Errors
119 ///
120 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
121 /// IO error during iteration.
122 #[derive(Debug)]
123 pub struct ReadDir(fs_imp::ReadDir);
124 
125 /// Entries returned by the [`ReadDir`] iterator.
126 ///
127 /// An instance of `DirEntry` represents an entry inside of a directory on the
128 /// filesystem. Each entry can be inspected via methods to learn about the full
129 /// path or possibly other metadata through per-platform extension traits.
130 ///
131 /// # Platform-specific behavior
132 ///
133 /// On Unix, the `DirEntry` struct contains an internal reference to the open
134 /// directory. Holding `DirEntry` objects will consume a file handle even
135 /// after the `ReadDir` iterator is dropped.
136 ///
137 /// Note that this [may change in the future][changes].
138 ///
139 /// [changes]: io#platform-specific-behavior
140 pub struct DirEntry(fs_imp::DirEntry);
141 
142 /// Options and flags which can be used to configure how a file is opened.
143 ///
144 /// This builder exposes the ability to configure how a [`File`] is opened and
145 /// what operations are permitted on the open file. The [`File::open`] and
146 /// [`File::create`] methods are aliases for commonly used options using this
147 /// builder.
148 ///
149 /// Generally speaking, when using `OpenOptions`, you'll first call
150 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
151 /// call [`OpenOptions::open`], passing the path of the file you're trying to
152 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
153 /// can further operate on.
154 ///
155 /// # Examples
156 ///
157 /// Opening a file to read:
158 ///
159 /// ```no_run
160 /// use std::fs::OpenOptions;
161 ///
162 /// let file = OpenOptions::new().read(true).open("foo.txt");
163 /// ```
164 ///
165 /// Opening a file for both reading and writing, as well as creating it if it
166 /// doesn't exist:
167 ///
168 /// ```no_run
169 /// use std::fs::OpenOptions;
170 ///
171 /// let file = OpenOptions::new()
172 ///             .read(true)
173 ///             .write(true)
174 ///             .create(true)
175 ///             .open("foo.txt");
176 /// ```
177 #[derive(Clone, Debug)]
178 pub struct OpenOptions(fs_imp::OpenOptions);
179 
180 /// Representation of the various timestamps on a file.
181 #[derive(Copy, Clone, Debug, Default)]
182 pub struct FileTimes(fs_imp::FileTimes);
183 
184 /// Representation of the various permissions on a file.
185 ///
186 /// This module only currently provides one bit of information,
187 /// [`Permissions::readonly`], which is exposed on all currently supported
188 /// platforms. Unix-specific functionality, such as mode bits, is available
189 /// through the [`PermissionsExt`] trait.
190 ///
191 /// [`PermissionsExt`]: crate::std::os::unix::fs::PermissionsExt
192 #[derive(Clone, PartialEq, Eq, Debug)]
193 pub struct Permissions(fs_imp::FilePermissions);
194 
195 /// A structure representing a type of file with accessors for each file type.
196 /// It is returned by [`Metadata::file_type`] method.
197 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
198 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
199 pub struct FileType(fs_imp::FileType);
200 
201 /// A builder used to create directories in various manners.
202 ///
203 /// This builder also supports platform-specific options.
204 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
205 #[derive(Debug)]
206 pub struct DirBuilder {
207     inner: fs_imp::DirBuilder,
208     recursive: bool,
209 }
210 
211 /// Read the entire contents of a file into a bytes vector.
212 ///
213 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
214 /// with fewer imports and without an intermediate variable.
215 ///
216 /// [`read_to_end`]: Read::read_to_end
217 ///
218 /// # Errors
219 ///
220 /// This function will return an error if `path` does not already exist.
221 /// Other errors may also be returned according to [`OpenOptions::open`].
222 ///
223 /// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
224 /// with automatic retries. See [io::Read] documentation for details.
225 ///
226 /// # Examples
227 ///
228 /// ```no_run
229 /// use std::fs;
230 /// use std::net::SocketAddr;
231 ///
232 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
233 ///     let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
234 ///     Ok(())
235 /// }
236 /// ```
read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>>237 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
238     fn inner(path: &Path) -> io::Result<Vec<u8>> {
239         let mut file = File::open(path)?;
240         let size = file.metadata().map(|m| m.len() as usize).ok();
241         let mut bytes = Vec::with_capacity(size.unwrap_or(0));
242         io::default_read_to_end(&mut file, &mut bytes, size)?;
243         Ok(bytes)
244     }
245     inner(path.as_ref())
246 }
247 
248 /// Read the entire contents of a file into a string.
249 ///
250 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
251 /// with fewer imports and without an intermediate variable.
252 ///
253 /// [`read_to_string`]: Read::read_to_string
254 ///
255 /// # Errors
256 ///
257 /// This function will return an error if `path` does not already exist.
258 /// Other errors may also be returned according to [`OpenOptions::open`].
259 ///
260 /// If the contents of the file are not valid UTF-8, then an error will also be
261 /// returned.
262 ///
263 /// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
264 /// with automatic retries. See [io::Read] documentation for details.
265 ///
266 /// # Examples
267 ///
268 /// ```no_run
269 /// use std::fs;
270 /// use std::net::SocketAddr;
271 /// use std::error::Error;
272 ///
273 /// fn main() -> Result<(), Box<dyn Error>> {
274 ///     let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
275 ///     Ok(())
276 /// }
277 /// ```
read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String>278 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
279     fn inner(path: &Path) -> io::Result<String> {
280         let mut file = File::open(path)?;
281         let size = file.metadata().map(|m| m.len() as usize).ok();
282         let mut string = String::with_capacity(size.unwrap_or(0));
283         io::default_read_to_string(&mut file, &mut string, size)?;
284         Ok(string)
285     }
286     inner(path.as_ref())
287 }
288 
289 /// Write a slice as the entire contents of a file.
290 ///
291 /// This function will create a file if it does not exist,
292 /// and will entirely replace its contents if it does.
293 ///
294 /// Depending on the platform, this function may fail if the
295 /// full directory path does not exist.
296 ///
297 /// This is a convenience function for using [`File::create`] and [`write_all`]
298 /// with fewer imports.
299 ///
300 /// [`write_all`]: Write::write_all
301 ///
302 /// # Examples
303 ///
304 /// ```no_run
305 /// use std::fs;
306 ///
307 /// fn main() -> std::io::Result<()> {
308 ///     fs::write("foo.txt", b"Lorem ipsum")?;
309 ///     fs::write("bar.txt", "dolor sit")?;
310 ///     Ok(())
311 /// }
312 /// ```
write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()>313 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
314     fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
315         File::create(path)?.write_all(contents)
316     }
317     inner(path.as_ref(), contents.as_ref())
318 }
319 
320 impl File {
321     /// Attempts to open a file in read-only mode.
322     ///
323     /// See the [`OpenOptions::open`] method for more details.
324     ///
325     /// If you only need to read the entire file contents,
326     /// consider [`std::fs::read()`][self::read] or
327     /// [`std::fs::read_to_string()`][self::read_to_string] instead.
328     ///
329     /// # Errors
330     ///
331     /// This function will return an error if `path` does not already exist.
332     /// Other errors may also be returned according to [`OpenOptions::open`].
333     ///
334     /// # Examples
335     ///
336     /// ```no_run
337     /// use std::fs::File;
338     /// use std::io::Read;
339     ///
340     /// fn main() -> std::io::Result<()> {
341     ///     let mut f = File::open("foo.txt")?;
342     ///     let mut data = vec![];
343     ///     f.read_to_end(&mut data)?;
344     ///     Ok(())
345     /// }
346     /// ```
open<P: AsRef<Path>>(path: P) -> io::Result<File>347     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
348         OpenOptions::new().read(true).open(path.as_ref())
349     }
350 
351     /// Opens a file in write-only mode.
352     ///
353     /// This function will create a file if it does not exist,
354     /// and will truncate it if it does.
355     ///
356     /// Depending on the platform, this function may fail if the
357     /// full directory path does not exist.
358     /// See the [`OpenOptions::open`] function for more details.
359     ///
360     /// See also [`std::fs::write()`][self::write] for a simple function to
361     /// create a file with a given data.
362     ///
363     /// # Examples
364     ///
365     /// ```no_run
366     /// use std::fs::File;
367     /// use std::io::Write;
368     ///
369     /// fn main() -> std::io::Result<()> {
370     ///     let mut f = File::create("foo.txt")?;
371     ///     f.write_all(&1234_u32.to_be_bytes())?;
372     ///     Ok(())
373     /// }
374     /// ```
create<P: AsRef<Path>>(path: P) -> io::Result<File>375     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
376         OpenOptions::new()
377             .write(true)
378             .create(true)
379             .truncate(true)
380             .open(path.as_ref())
381     }
382 
383     /// Creates a new file in read-write mode; error if the file exists.
384     ///
385     /// This function will create a file if it does not exist, or return an error if it does. This
386     /// way, if the call succeeds, the file returned is guaranteed to be new.
387     ///
388     /// This option is useful because it is atomic. Otherwise between checking whether a file
389     /// exists and creating a new one, the file may have been created by another process (a TOCTOU
390     /// race condition / attack).
391     ///
392     /// This can also be written using
393     /// `File::options().read(true).write(true).create_new(true).open(...)`.
394     ///
395     /// # Examples
396     ///
397     /// ```no_run
398     /// #![feature(file_create_new)]
399     ///
400     /// use std::fs::File;
401     /// use std::io::Write;
402     ///
403     /// fn main() -> std::io::Result<()> {
404     ///     let mut f = File::create_new("foo.txt")?;
405     ///     f.write_all("Hello, world!".as_bytes())?;
406     ///     Ok(())
407     /// }
408     /// ```
create_new<P: AsRef<Path>>(path: P) -> io::Result<File>409     pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
410         OpenOptions::new()
411             .read(true)
412             .write(true)
413             .create_new(true)
414             .open(path.as_ref())
415     }
416 
417     /// Returns a new OpenOptions object.
418     ///
419     /// This function returns a new OpenOptions object that you can use to
420     /// open or create a file with specific options if `open()` or `create()`
421     /// are not appropriate.
422     ///
423     /// It is equivalent to `OpenOptions::new()`, but allows you to write more
424     /// readable code. Instead of
425     /// `OpenOptions::new().append(true).open("example.log")`,
426     /// you can write `File::options().append(true).open("example.log")`. This
427     /// also avoids the need to import `OpenOptions`.
428     ///
429     /// See the [`OpenOptions::new`] function for more details.
430     ///
431     /// # Examples
432     ///
433     /// ```no_run
434     /// use std::fs::File;
435     /// use std::io::Write;
436     ///
437     /// fn main() -> std::io::Result<()> {
438     ///     let mut f = File::options().append(true).open("example.log")?;
439     ///     writeln!(&mut f, "new line")?;
440     ///     Ok(())
441     /// }
442     /// ```
443     #[must_use]
options() -> OpenOptions444     pub fn options() -> OpenOptions {
445         OpenOptions::new()
446     }
447 
448     /// Attempts to sync all OS-internal metadata to disk.
449     ///
450     /// This function will attempt to ensure that all in-memory data reaches the
451     /// filesystem before returning.
452     ///
453     /// This can be used to handle errors that would otherwise only be caught
454     /// when the `File` is closed.  Dropping a file will ignore errors in
455     /// synchronizing this in-memory data.
456     ///
457     /// # Examples
458     ///
459     /// ```no_run
460     /// use std::fs::File;
461     /// use std::io::prelude::*;
462     ///
463     /// fn main() -> std::io::Result<()> {
464     ///     let mut f = File::create("foo.txt")?;
465     ///     f.write_all(b"Hello, world!")?;
466     ///
467     ///     f.sync_all()?;
468     ///     Ok(())
469     /// }
470     /// ```
sync_all(&self) -> io::Result<()>471     pub fn sync_all(&self) -> io::Result<()> {
472         self.inner.fsync()
473     }
474 
475     /// This function is similar to [`sync_all`], except that it might not
476     /// synchronize file metadata to the filesystem.
477     ///
478     /// This is intended for use cases that must synchronize content, but don't
479     /// need the metadata on disk. The goal of this method is to reduce disk
480     /// operations.
481     ///
482     /// Note that some platforms may simply implement this in terms of
483     /// [`sync_all`].
484     ///
485     /// [`sync_all`]: File::sync_all
486     ///
487     /// # Examples
488     ///
489     /// ```no_run
490     /// use std::fs::File;
491     /// use std::io::prelude::*;
492     ///
493     /// fn main() -> std::io::Result<()> {
494     ///     let mut f = File::create("foo.txt")?;
495     ///     f.write_all(b"Hello, world!")?;
496     ///
497     ///     f.sync_data()?;
498     ///     Ok(())
499     /// }
500     /// ```
sync_data(&self) -> io::Result<()>501     pub fn sync_data(&self) -> io::Result<()> {
502         self.inner.datasync()
503     }
504 
505     /// Truncates or extends the underlying file, updating the size of
506     /// this file to become `size`.
507     ///
508     /// If the `size` is less than the current file's size, then the file will
509     /// be shrunk. If it is greater than the current file's size, then the file
510     /// will be extended to `size` and have all of the intermediate data filled
511     /// in with 0s.
512     ///
513     /// The file's cursor isn't changed. In particular, if the cursor was at the
514     /// end and the file is shrunk using this operation, the cursor will now be
515     /// past the end.
516     ///
517     /// # Errors
518     ///
519     /// This function will return an error if the file is not opened for writing.
520     /// Also, [`std::io::ErrorKind::InvalidInput`](crate::std::io::ErrorKind::InvalidInput)
521     /// will be returned if the desired length would cause an overflow due to
522     /// the implementation specifics.
523     ///
524     /// # Examples
525     ///
526     /// ```no_run
527     /// use std::fs::File;
528     ///
529     /// fn main() -> std::io::Result<()> {
530     ///     let mut f = File::create("foo.txt")?;
531     ///     f.set_len(10)?;
532     ///     Ok(())
533     /// }
534     /// ```
535     ///
536     /// Note that this method alters the content of the underlying file, even
537     /// though it takes `&self` rather than `&mut self`.
set_len(&self, size: u64) -> io::Result<()>538     pub fn set_len(&self, size: u64) -> io::Result<()> {
539         self.inner.truncate(size)
540     }
541 
542     /// Queries metadata about the underlying file.
543     ///
544     /// # Examples
545     ///
546     /// ```no_run
547     /// use std::fs::File;
548     ///
549     /// fn main() -> std::io::Result<()> {
550     ///     let mut f = File::open("foo.txt")?;
551     ///     let metadata = f.metadata()?;
552     ///     Ok(())
553     /// }
554     /// ```
metadata(&self) -> io::Result<Metadata>555     pub fn metadata(&self) -> io::Result<Metadata> {
556         self.inner.file_attr().map(Metadata)
557     }
558 
559     /// Creates a new `File` instance that shares the same underlying file handle
560     /// as the existing `File` instance. Reads, writes, and seeks will affect
561     /// both `File` instances simultaneously.
562     ///
563     /// # Examples
564     ///
565     /// Creates two handles for a file named `foo.txt`:
566     ///
567     /// ```no_run
568     /// use std::fs::File;
569     ///
570     /// fn main() -> std::io::Result<()> {
571     ///     let mut file = File::open("foo.txt")?;
572     ///     let file_copy = file.try_clone()?;
573     ///     Ok(())
574     /// }
575     /// ```
576     ///
577     /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
578     /// two handles, seek one of them, and read the remaining bytes from the
579     /// other handle:
580     ///
581     /// ```no_run
582     /// use std::fs::File;
583     /// use std::io::SeekFrom;
584     /// use std::io::prelude::*;
585     ///
586     /// fn main() -> std::io::Result<()> {
587     ///     let mut file = File::open("foo.txt")?;
588     ///     let mut file_copy = file.try_clone()?;
589     ///
590     ///     file.seek(SeekFrom::Start(3))?;
591     ///
592     ///     let mut contents = vec![];
593     ///     file_copy.read_to_end(&mut contents)?;
594     ///     assert_eq!(contents, b"def\n");
595     ///     Ok(())
596     /// }
597     /// ```
try_clone(&self) -> io::Result<File>598     pub fn try_clone(&self) -> io::Result<File> {
599         Ok(File {
600             inner: self.inner.duplicate()?,
601         })
602     }
603 
604     /// Changes the permissions on the underlying file.
605     ///
606     /// # Platform-specific behavior
607     ///
608     /// This function currently corresponds to the `fchmod` function on Unix and
609     /// the `SetFileInformationByHandle` function on Windows. Note that, this
610     /// [may change in the future][changes].
611     ///
612     /// [changes]: io#platform-specific-behavior
613     ///
614     /// # Errors
615     ///
616     /// This function will return an error if the user lacks permission change
617     /// attributes on the underlying file. It may also return an error in other
618     /// os-specific unspecified cases.
619     ///
620     /// # Examples
621     ///
622     /// ```no_run
623     /// fn main() -> std::io::Result<()> {
624     ///     use std::fs::File;
625     ///
626     ///     let file = File::open("foo.txt")?;
627     ///     let mut perms = file.metadata()?.permissions();
628     ///     perms.set_readonly(true);
629     ///     file.set_permissions(perms)?;
630     ///     Ok(())
631     /// }
632     /// ```
633     ///
634     /// Note that this method alters the permissions of the underlying file,
635     /// even though it takes `&self` rather than `&mut self`.
set_permissions(&self, perm: Permissions) -> io::Result<()>636     pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
637         self.inner.set_permissions(perm.0)
638     }
639 
640     /// Changes the timestamps of the underlying file.
641     ///
642     /// # Platform-specific behavior
643     ///
644     /// This function currently corresponds to the `futimens` function on Unix (falling back to
645     /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
646     /// [may change in the future][changes].
647     ///
648     /// [changes]: io#platform-specific-behavior
649     ///
650     /// # Errors
651     ///
652     /// This function will return an error if the user lacks permission to change timestamps on the
653     /// underlying file. It may also return an error in other os-specific unspecified cases.
654     ///
655     /// This function may return an error if the operating system lacks support to change one or
656     /// more of the timestamps set in the `FileTimes` structure.
657     ///
658     /// # Examples
659     ///
660     /// ```no_run
661     /// #![feature(file_set_times)]
662     ///
663     /// fn main() -> std::io::Result<()> {
664     ///     use std::fs::{self, File, FileTimes};
665     ///
666     ///     let src = fs::metadata("src")?;
667     ///     let dest = File::options().write(true).open("dest")?;
668     ///     let times = FileTimes::new()
669     ///         .set_accessed(src.accessed()?)
670     ///         .set_modified(src.modified()?);
671     ///     dest.set_times(times)?;
672     ///     Ok(())
673     /// }
674     /// ```
675     #[doc(alias = "futimens")]
676     #[doc(alias = "futimes")]
677     #[doc(alias = "SetFileTime")]
set_times(&self, times: FileTimes) -> io::Result<()>678     pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
679         self.inner.set_times(times.0)
680     }
681 
682     /// Changes the modification time of the underlying file.
683     ///
684     /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
685     #[inline]
set_modified(&self, time: SystemTime) -> io::Result<()>686     pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
687         self.set_times(FileTimes::new().set_modified(time))
688     }
689 }
690 
691 // In addition to the `impl`s here, `File` also has `impl`s for
692 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
693 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
694 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
695 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
696 
697 impl AsInner<fs_imp::File> for File {
698     #[inline]
as_inner(&self) -> &fs_imp::File699     fn as_inner(&self) -> &fs_imp::File {
700         &self.inner
701     }
702 }
703 impl FromInner<fs_imp::File> for File {
from_inner(f: fs_imp::File) -> File704     fn from_inner(f: fs_imp::File) -> File {
705         File { inner: f }
706     }
707 }
708 impl IntoInner<fs_imp::File> for File {
into_inner(self) -> fs_imp::File709     fn into_inner(self) -> fs_imp::File {
710         self.inner
711     }
712 }
713 
714 impl fmt::Debug for File {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result715     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716         self.inner.fmt(f)
717     }
718 }
719 
720 /// Indicates how much extra capacity is needed to read the rest of the file.
buffer_capacity_required(mut file: &File) -> Option<usize>721 fn buffer_capacity_required(mut file: &File) -> Option<usize> {
722     let size = file.metadata().map(|m| m.len()).ok()?;
723     let pos = file.stream_position().ok()?;
724     // Don't worry about `usize` overflow because reading will fail regardless
725     // in that case.
726     Some(size.saturating_sub(pos) as usize)
727 }
728 
729 impl Read for &File {
730     #[inline]
read(&mut self, buf: &mut [u8]) -> io::Result<usize>731     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
732         self.inner.read(buf)
733     }
734 
735     #[inline]
read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>736     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
737         self.inner.read_vectored(bufs)
738     }
739 
740     #[inline]
read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()>741     fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
742         self.inner.read_buf(cursor)
743     }
744 
745     #[inline]
is_read_vectored(&self) -> bool746     fn is_read_vectored(&self) -> bool {
747         self.inner.is_read_vectored()
748     }
749 
750     // Reserves space in the buffer based on the file size when available.
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>751     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
752         let size = buffer_capacity_required(self);
753         buf.reserve(size.unwrap_or(0));
754         io::default_read_to_end(self, buf, size)
755     }
756 
757     // Reserves space in the buffer based on the file size when available.
read_to_string(&mut self, buf: &mut String) -> io::Result<usize>758     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
759         let size = buffer_capacity_required(self);
760         buf.reserve(size.unwrap_or(0));
761         io::default_read_to_string(self, buf, size)
762     }
763 }
764 impl Write for &File {
write(&mut self, buf: &[u8]) -> io::Result<usize>765     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
766         self.inner.write(buf)
767     }
768 
write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>769     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
770         self.inner.write_vectored(bufs)
771     }
772 
773     #[inline]
is_write_vectored(&self) -> bool774     fn is_write_vectored(&self) -> bool {
775         self.inner.is_write_vectored()
776     }
777 
778     #[inline]
flush(&mut self) -> io::Result<()>779     fn flush(&mut self) -> io::Result<()> {
780         self.inner.flush()
781     }
782 }
783 impl Seek for &File {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>784     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
785         self.inner.seek(pos)
786     }
787 }
788 
789 impl Read for File {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>790     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
791         (&*self).read(buf)
792     }
read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>793     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
794         (&*self).read_vectored(bufs)
795     }
read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()>796     fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
797         (&*self).read_buf(cursor)
798     }
799     #[inline]
is_read_vectored(&self) -> bool800     fn is_read_vectored(&self) -> bool {
801         (&&*self).is_read_vectored()
802     }
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>803     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
804         (&*self).read_to_end(buf)
805     }
read_to_string(&mut self, buf: &mut String) -> io::Result<usize>806     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
807         (&*self).read_to_string(buf)
808     }
809 }
810 impl Write for File {
write(&mut self, buf: &[u8]) -> io::Result<usize>811     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
812         (&*self).write(buf)
813     }
write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>814     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
815         (&*self).write_vectored(bufs)
816     }
817     #[inline]
is_write_vectored(&self) -> bool818     fn is_write_vectored(&self) -> bool {
819         (&&*self).is_write_vectored()
820     }
821     #[inline]
flush(&mut self) -> io::Result<()>822     fn flush(&mut self) -> io::Result<()> {
823         (&*self).flush()
824     }
825 }
826 impl Seek for File {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>827     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
828         (&*self).seek(pos)
829     }
830 }
831 
832 impl Read for Arc<File> {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>833     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
834         (&**self).read(buf)
835     }
read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>836     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
837         (&**self).read_vectored(bufs)
838     }
read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()>839     fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
840         (&**self).read_buf(cursor)
841     }
842     #[inline]
is_read_vectored(&self) -> bool843     fn is_read_vectored(&self) -> bool {
844         (&**self).is_read_vectored()
845     }
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>846     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
847         (&**self).read_to_end(buf)
848     }
read_to_string(&mut self, buf: &mut String) -> io::Result<usize>849     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
850         (&**self).read_to_string(buf)
851     }
852 }
853 impl Write for Arc<File> {
write(&mut self, buf: &[u8]) -> io::Result<usize>854     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
855         (&**self).write(buf)
856     }
write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>857     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
858         (&**self).write_vectored(bufs)
859     }
860     #[inline]
is_write_vectored(&self) -> bool861     fn is_write_vectored(&self) -> bool {
862         (&**self).is_write_vectored()
863     }
864     #[inline]
flush(&mut self) -> io::Result<()>865     fn flush(&mut self) -> io::Result<()> {
866         (&**self).flush()
867     }
868 }
869 impl Seek for Arc<File> {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>870     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
871         (&**self).seek(pos)
872     }
873 }
874 
875 impl OpenOptions {
876     /// Creates a blank new set of options ready for configuration.
877     ///
878     /// All options are initially set to `false`.
879     ///
880     /// # Examples
881     ///
882     /// ```no_run
883     /// use std::fs::OpenOptions;
884     ///
885     /// let mut options = OpenOptions::new();
886     /// let file = options.read(true).open("foo.txt");
887     /// ```
888     #[must_use]
new() -> Self889     pub fn new() -> Self {
890         OpenOptions(fs_imp::OpenOptions::new())
891     }
892 
893     /// Sets the option for read access.
894     ///
895     /// This option, when true, will indicate that the file should be
896     /// `read`-able if opened.
897     ///
898     /// # Examples
899     ///
900     /// ```no_run
901     /// use std::fs::OpenOptions;
902     ///
903     /// let file = OpenOptions::new().read(true).open("foo.txt");
904     /// ```
read(&mut self, read: bool) -> &mut Self905     pub fn read(&mut self, read: bool) -> &mut Self {
906         self.0.read(read);
907         self
908     }
909 
910     /// Sets the option for write access.
911     ///
912     /// This option, when true, will indicate that the file should be
913     /// `write`-able if opened.
914     ///
915     /// If the file already exists, any write calls on it will overwrite its
916     /// contents, without truncating it.
917     ///
918     /// # Examples
919     ///
920     /// ```no_run
921     /// use std::fs::OpenOptions;
922     ///
923     /// let file = OpenOptions::new().write(true).open("foo.txt");
924     /// ```
write(&mut self, write: bool) -> &mut Self925     pub fn write(&mut self, write: bool) -> &mut Self {
926         self.0.write(write);
927         self
928     }
929 
930     /// Sets the option for the append mode.
931     ///
932     /// This option, when true, means that writes will append to a file instead
933     /// of overwriting previous contents.
934     /// Note that setting `.write(true).append(true)` has the same effect as
935     /// setting only `.append(true)`.
936     ///
937     /// For most filesystems, the operating system guarantees that all writes are
938     /// atomic: no writes get mangled because another process writes at the same
939     /// time.
940     ///
941     /// One maybe obvious note when using append-mode: make sure that all data
942     /// that belongs together is written to the file in one operation. This
943     /// can be done by concatenating strings before passing them to [`write()`],
944     /// or using a buffered writer (with a buffer of adequate size),
945     /// and calling [`flush()`] when the message is complete.
946     ///
947     /// If a file is opened with both read and append access, beware that after
948     /// opening, and after every write, the position for reading may be set at the
949     /// end of the file. So, before writing, save the current position (using
950     /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
951     ///
952     /// ## Note
953     ///
954     /// This function doesn't create the file if it doesn't exist. Use the
955     /// [`OpenOptions::create`] method to do so.
956     ///
957     /// [`write()`]: Write::write "io::Write::write"
958     /// [`flush()`]: Write::flush "io::Write::flush"
959     /// [seek]: Seek::seek "io::Seek::seek"
960     /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
961     ///
962     /// # Examples
963     ///
964     /// ```no_run
965     /// use std::fs::OpenOptions;
966     ///
967     /// let file = OpenOptions::new().append(true).open("foo.txt");
968     /// ```
append(&mut self, append: bool) -> &mut Self969     pub fn append(&mut self, append: bool) -> &mut Self {
970         self.0.append(append);
971         self
972     }
973 
974     /// Sets the option for truncating a previous file.
975     ///
976     /// If a file is successfully opened with this option set it will truncate
977     /// the file to 0 length if it already exists.
978     ///
979     /// The file must be opened with write access for truncate to work.
980     ///
981     /// # Examples
982     ///
983     /// ```no_run
984     /// use std::fs::OpenOptions;
985     ///
986     /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
987     /// ```
truncate(&mut self, truncate: bool) -> &mut Self988     pub fn truncate(&mut self, truncate: bool) -> &mut Self {
989         self.0.truncate(truncate);
990         self
991     }
992 
993     /// Sets the option to create a new file, or open it if it already exists.
994     ///
995     /// In order for the file to be created, [`OpenOptions::write`] or
996     /// [`OpenOptions::append`] access must be used.
997     ///
998     /// See also [`std::fs::write()`][self::write] for a simple function to
999     /// create a file with a given data.
1000     ///
1001     /// # Examples
1002     ///
1003     /// ```no_run
1004     /// use std::fs::OpenOptions;
1005     ///
1006     /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
1007     /// ```
create(&mut self, create: bool) -> &mut Self1008     pub fn create(&mut self, create: bool) -> &mut Self {
1009         self.0.create(create);
1010         self
1011     }
1012 
1013     /// Sets the option to create a new file, failing if it already exists.
1014     ///
1015     /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1016     /// way, if the call succeeds, the file returned is guaranteed to be new.
1017     ///
1018     /// This option is useful because it is atomic. Otherwise between checking
1019     /// whether a file exists and creating a new one, the file may have been
1020     /// created by another process (a TOCTOU race condition / attack).
1021     ///
1022     /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1023     /// ignored.
1024     ///
1025     /// The file must be opened with write or append access in order to create
1026     /// a new file.
1027     ///
1028     /// [`.create()`]: OpenOptions::create
1029     /// [`.truncate()`]: OpenOptions::truncate
1030     ///
1031     /// # Examples
1032     ///
1033     /// ```no_run
1034     /// use std::fs::OpenOptions;
1035     ///
1036     /// let file = OpenOptions::new().write(true)
1037     ///                              .create_new(true)
1038     ///                              .open("foo.txt");
1039     /// ```
create_new(&mut self, create_new: bool) -> &mut Self1040     pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1041         self.0.create_new(create_new);
1042         self
1043     }
1044 
1045     /// Opens a file at `path` with the options specified by `self`.
1046     ///
1047     /// # Errors
1048     ///
1049     /// This function will return an error under a number of different
1050     /// circumstances. Some of these error conditions are listed here, together
1051     /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1052     /// part of the compatibility contract of the function.
1053     ///
1054     /// * [`NotFound`]: The specified file does not exist and neither `create`
1055     ///   or `create_new` is set.
1056     /// * [`NotFound`]: One of the directory components of the file path does
1057     ///   not exist.
1058     /// * [`PermissionDenied`]: The user lacks permission to get the specified
1059     ///   access rights for the file.
1060     /// * [`PermissionDenied`]: The user lacks permission to open one of the
1061     ///   directory components of the specified path.
1062     /// * [`AlreadyExists`]: `create_new` was specified and the file already
1063     ///   exists.
1064     /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1065     ///   without write access, no access mode set, etc.).
1066     ///
1067     /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1068     /// * One of the directory components of the specified file path
1069     ///   was not, in fact, a directory.
1070     /// * Filesystem-level errors: full disk, write permission
1071     ///   requested on a read-only file system, exceeded disk quota, too many
1072     ///   open files, too long filename, too many symbolic links in the
1073     ///   specified path (Unix-like systems only), etc.
1074     ///
1075     /// # Examples
1076     ///
1077     /// ```no_run
1078     /// use std::fs::OpenOptions;
1079     ///
1080     /// let file = OpenOptions::new().read(true).open("foo.txt");
1081     /// ```
1082     ///
1083     /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1084     /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1085     /// [`NotFound`]: io::ErrorKind::NotFound
1086     /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
open<P: AsRef<Path>>(&self, path: P) -> io::Result<File>1087     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1088         self._open(path.as_ref())
1089     }
1090 
_open(&self, path: &Path) -> io::Result<File>1091     fn _open(&self, path: &Path) -> io::Result<File> {
1092         fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1093     }
1094 }
1095 
1096 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1097     #[inline]
as_inner(&self) -> &fs_imp::OpenOptions1098     fn as_inner(&self) -> &fs_imp::OpenOptions {
1099         &self.0
1100     }
1101 }
1102 
1103 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1104     #[inline]
as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions1105     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1106         &mut self.0
1107     }
1108 }
1109 
1110 impl Metadata {
1111     /// Returns the file type for this metadata.
1112     ///
1113     /// # Examples
1114     ///
1115     /// ```no_run
1116     /// fn main() -> std::io::Result<()> {
1117     ///     use std::fs;
1118     ///
1119     ///     let metadata = fs::metadata("foo.txt")?;
1120     ///
1121     ///     println!("{:?}", metadata.file_type());
1122     ///     Ok(())
1123     /// }
1124     /// ```
1125     #[must_use]
file_type(&self) -> FileType1126     pub fn file_type(&self) -> FileType {
1127         FileType(self.0.file_type())
1128     }
1129 
1130     /// Returns `true` if this metadata is for a directory. The
1131     /// result is mutually exclusive to the result of
1132     /// [`Metadata::is_file`], and will be false for symlink metadata
1133     /// obtained from [`symlink_metadata`].
1134     ///
1135     /// # Examples
1136     ///
1137     /// ```no_run
1138     /// fn main() -> std::io::Result<()> {
1139     ///     use std::fs;
1140     ///
1141     ///     let metadata = fs::metadata("foo.txt")?;
1142     ///
1143     ///     assert!(!metadata.is_dir());
1144     ///     Ok(())
1145     /// }
1146     /// ```
1147     #[must_use]
is_dir(&self) -> bool1148     pub fn is_dir(&self) -> bool {
1149         self.file_type().is_dir()
1150     }
1151 
1152     /// Returns `true` if this metadata is for a regular file. The
1153     /// result is mutually exclusive to the result of
1154     /// [`Metadata::is_dir`], and will be false for symlink metadata
1155     /// obtained from [`symlink_metadata`].
1156     ///
1157     /// When the goal is simply to read from (or write to) the source, the most
1158     /// reliable way to test the source can be read (or written to) is to open
1159     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1160     /// a Unix-like system for example. See [`File::open`] or
1161     /// [`OpenOptions::open`] for more information.
1162     ///
1163     /// # Examples
1164     ///
1165     /// ```no_run
1166     /// use std::fs;
1167     ///
1168     /// fn main() -> std::io::Result<()> {
1169     ///     let metadata = fs::metadata("foo.txt")?;
1170     ///
1171     ///     assert!(metadata.is_file());
1172     ///     Ok(())
1173     /// }
1174     /// ```
1175     #[must_use]
is_file(&self) -> bool1176     pub fn is_file(&self) -> bool {
1177         self.file_type().is_file()
1178     }
1179 
1180     /// Returns `true` if this metadata is for a symbolic link.
1181     ///
1182     /// # Examples
1183     ///
1184     #[cfg_attr(unix, doc = "```no_run")]
1185     #[cfg_attr(not(unix), doc = "```ignore")]
1186     /// use std::fs;
1187     /// use std::path::Path;
1188     /// use std::os::unix::fs::symlink;
1189     ///
1190     /// fn main() -> std::io::Result<()> {
1191     ///     let link_path = Path::new("link");
1192     ///     symlink("/origin_does_not_exist/", link_path)?;
1193     ///
1194     ///     let metadata = fs::symlink_metadata(link_path)?;
1195     ///
1196     ///     assert!(metadata.is_symlink());
1197     ///     Ok(())
1198     /// }
1199     /// ```
1200     #[must_use]
is_symlink(&self) -> bool1201     pub fn is_symlink(&self) -> bool {
1202         self.file_type().is_symlink()
1203     }
1204 
1205     /// Returns the size of the file, in bytes, this metadata is for.
1206     ///
1207     /// # Examples
1208     ///
1209     /// ```no_run
1210     /// use std::fs;
1211     ///
1212     /// fn main() -> std::io::Result<()> {
1213     ///     let metadata = fs::metadata("foo.txt")?;
1214     ///
1215     ///     assert_eq!(0, metadata.len());
1216     ///     Ok(())
1217     /// }
1218     /// ```
1219     #[must_use]
len(&self) -> u641220     pub fn len(&self) -> u64 {
1221         self.0.size()
1222     }
1223 
1224     /// Returns the permissions of the file this metadata is for.
1225     ///
1226     /// # Examples
1227     ///
1228     /// ```no_run
1229     /// use std::fs;
1230     ///
1231     /// fn main() -> std::io::Result<()> {
1232     ///     let metadata = fs::metadata("foo.txt")?;
1233     ///
1234     ///     assert!(!metadata.permissions().readonly());
1235     ///     Ok(())
1236     /// }
1237     /// ```
1238     #[must_use]
permissions(&self) -> Permissions1239     pub fn permissions(&self) -> Permissions {
1240         Permissions(self.0.perm())
1241     }
1242 
1243     /// Returns the last modification time listed in this metadata.
1244     ///
1245     /// The returned value corresponds to the `mtime` field of `stat` on Unix
1246     /// platforms and the `ftLastWriteTime` field on Windows platforms.
1247     ///
1248     /// # Errors
1249     ///
1250     /// This field might not be available on all platforms, and will return an
1251     /// `Err` on platforms where it is not available.
1252     ///
1253     /// # Examples
1254     ///
1255     /// ```no_run
1256     /// use std::fs;
1257     ///
1258     /// fn main() -> std::io::Result<()> {
1259     ///     let metadata = fs::metadata("foo.txt")?;
1260     ///
1261     ///     if let Ok(time) = metadata.modified() {
1262     ///         println!("{time:?}");
1263     ///     } else {
1264     ///         println!("Not supported on this platform");
1265     ///     }
1266     ///     Ok(())
1267     /// }
1268     /// ```
modified(&self) -> io::Result<SystemTime>1269     pub fn modified(&self) -> io::Result<SystemTime> {
1270         self.0.modified().map(FromInner::from_inner)
1271     }
1272 
1273     /// Returns the last access time of this metadata.
1274     ///
1275     /// The returned value corresponds to the `atime` field of `stat` on Unix
1276     /// platforms and the `ftLastAccessTime` field on Windows platforms.
1277     ///
1278     /// Note that not all platforms will keep this field update in a file's
1279     /// metadata, for example Windows has an option to disable updating this
1280     /// time when files are accessed and Linux similarly has `noatime`.
1281     ///
1282     /// # Errors
1283     ///
1284     /// This field might not be available on all platforms, and will return an
1285     /// `Err` on platforms where it is not available.
1286     ///
1287     /// # Examples
1288     ///
1289     /// ```no_run
1290     /// use std::fs;
1291     ///
1292     /// fn main() -> std::io::Result<()> {
1293     ///     let metadata = fs::metadata("foo.txt")?;
1294     ///
1295     ///     if let Ok(time) = metadata.accessed() {
1296     ///         println!("{time:?}");
1297     ///     } else {
1298     ///         println!("Not supported on this platform");
1299     ///     }
1300     ///     Ok(())
1301     /// }
1302     /// ```
accessed(&self) -> io::Result<SystemTime>1303     pub fn accessed(&self) -> io::Result<SystemTime> {
1304         self.0.accessed().map(FromInner::from_inner)
1305     }
1306 
1307     /// Returns the creation time listed in this metadata.
1308     ///
1309     /// The returned value corresponds to the `btime` field of `statx` on
1310     /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1311     /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1312     ///
1313     /// # Errors
1314     ///
1315     /// This field might not be available on all platforms, and will return an
1316     /// `Err` on platforms or filesystems where it is not available.
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```no_run
1321     /// use std::fs;
1322     ///
1323     /// fn main() -> std::io::Result<()> {
1324     ///     let metadata = fs::metadata("foo.txt")?;
1325     ///
1326     ///     if let Ok(time) = metadata.created() {
1327     ///         println!("{time:?}");
1328     ///     } else {
1329     ///         println!("Not supported on this platform or filesystem");
1330     ///     }
1331     ///     Ok(())
1332     /// }
1333     /// ```
created(&self) -> io::Result<SystemTime>1334     pub fn created(&self) -> io::Result<SystemTime> {
1335         self.0.created().map(FromInner::from_inner)
1336     }
1337 }
1338 
1339 impl fmt::Debug for Metadata {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1340     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341         f.debug_struct("Metadata")
1342             .field("file_type", &self.file_type())
1343             .field("is_dir", &self.is_dir())
1344             .field("is_file", &self.is_file())
1345             .field("permissions", &self.permissions())
1346             .field("modified", &self.modified())
1347             .field("accessed", &self.accessed())
1348             .field("created", &self.created())
1349             .finish_non_exhaustive()
1350     }
1351 }
1352 
1353 impl AsInner<fs_imp::FileAttr> for Metadata {
1354     #[inline]
as_inner(&self) -> &fs_imp::FileAttr1355     fn as_inner(&self) -> &fs_imp::FileAttr {
1356         &self.0
1357     }
1358 }
1359 
1360 impl FromInner<fs_imp::FileAttr> for Metadata {
from_inner(attr: fs_imp::FileAttr) -> Metadata1361     fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1362         Metadata(attr)
1363     }
1364 }
1365 
1366 impl FileTimes {
1367     /// Create a new `FileTimes` with no times set.
1368     ///
1369     /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
new() -> Self1370     pub fn new() -> Self {
1371         Self::default()
1372     }
1373 
1374     /// Set the last access time of a file.
set_accessed(mut self, t: SystemTime) -> Self1375     pub fn set_accessed(mut self, t: SystemTime) -> Self {
1376         self.0.set_accessed(t.into_inner());
1377         self
1378     }
1379 
1380     /// Set the last modified time of a file.
set_modified(mut self, t: SystemTime) -> Self1381     pub fn set_modified(mut self, t: SystemTime) -> Self {
1382         self.0.set_modified(t.into_inner());
1383         self
1384     }
1385 }
1386 
1387 impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
as_inner_mut(&mut self) -> &mut fs_imp::FileTimes1388     fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
1389         &mut self.0
1390     }
1391 }
1392 
1393 // For implementing OS extension traits in `std::os`
1394 impl Sealed for FileTimes {}
1395 
1396 impl Permissions {
1397     /// Returns `true` if these permissions describe a readonly (unwritable) file.
1398     ///
1399     /// # Note
1400     ///
1401     /// This function does not take Access Control Lists (ACLs) or Unix group
1402     /// membership into account.
1403     ///
1404     /// # Windows
1405     ///
1406     /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1407     /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1408     /// but the user may still have permission to change this flag. If
1409     /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
1410     /// to lack of write permission.
1411     /// The behavior of this attribute for directories depends on the Windows
1412     /// version.
1413     ///
1414     /// # Unix (including macOS)
1415     ///
1416     /// On Unix-based platforms this checks if *any* of the owner, group or others
1417     /// write permission bits are set. It does not check if the current
1418     /// user is in the file's assigned group. It also does not check ACLs.
1419     /// Therefore even if this returns true you may not be able to write to the
1420     /// file, and vice versa. The [`PermissionsExt`] trait gives direct access
1421     /// to the permission bits but also does not read ACLs. If you need to
1422     /// accurately know whether or not a file is writable use the `access()`
1423     /// function from libc.
1424     ///
1425     /// [`PermissionsExt`]: crate::std::os::unix::fs::PermissionsExt
1426     ///
1427     /// # Examples
1428     ///
1429     /// ```no_run
1430     /// use std::fs::File;
1431     ///
1432     /// fn main() -> std::io::Result<()> {
1433     ///     let mut f = File::create("foo.txt")?;
1434     ///     let metadata = f.metadata()?;
1435     ///
1436     ///     assert_eq!(false, metadata.permissions().readonly());
1437     ///     Ok(())
1438     /// }
1439     /// ```
1440     #[must_use = "call `set_readonly` to modify the readonly flag"]
readonly(&self) -> bool1441     pub fn readonly(&self) -> bool {
1442         self.0.readonly()
1443     }
1444 
1445     /// Modifies the readonly flag for this set of permissions. If the
1446     /// `readonly` argument is `true`, using the resulting `Permission` will
1447     /// update file permissions to forbid writing. Conversely, if it's `false`,
1448     /// using the resulting `Permission` will update file permissions to allow
1449     /// writing.
1450     ///
1451     /// This operation does **not** modify the files attributes. This only
1452     /// changes the in-memory value of these attributes for this `Permissions`
1453     /// instance. To modify the files attributes use the [`set_permissions`]
1454     /// function which commits these attribute changes to the file.
1455     ///
1456     /// # Note
1457     ///
1458     /// `set_readonly(false)` makes the file *world-writable* on Unix.
1459     /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
1460     ///
1461     /// It also does not take Access Control Lists (ACLs) or Unix group
1462     /// membership into account.
1463     ///
1464     /// # Windows
1465     ///
1466     /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1467     /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1468     /// but the user may still have permission to change this flag. If
1469     /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
1470     /// the user does not have permission to write to the file.
1471     ///
1472     /// In Windows 7 and earlier this attribute prevents deleting empty
1473     /// directories. It does not prevent modifying the directory contents.
1474     /// On later versions of Windows this attribute is ignored for directories.
1475     ///
1476     /// # Unix (including macOS)
1477     ///
1478     /// On Unix-based platforms this sets or clears the write access bit for
1479     /// the owner, group *and* others, equivalent to `chmod a+w <file>`
1480     /// or `chmod a-w <file>` respectively. The latter will grant write access
1481     /// to all users! You can use the [`PermissionsExt`] trait on Unix
1482     /// to avoid this issue.
1483     ///
1484     /// [`PermissionsExt`]: crate::std::os::unix::fs::PermissionsExt
1485     ///
1486     /// # Examples
1487     ///
1488     /// ```no_run
1489     /// use std::fs::File;
1490     ///
1491     /// fn main() -> std::io::Result<()> {
1492     ///     let f = File::create("foo.txt")?;
1493     ///     let metadata = f.metadata()?;
1494     ///     let mut permissions = metadata.permissions();
1495     ///
1496     ///     permissions.set_readonly(true);
1497     ///
1498     ///     // filesystem doesn't change, only the in memory state of the
1499     ///     // readonly permission
1500     ///     assert_eq!(false, metadata.permissions().readonly());
1501     ///
1502     ///     // just this particular `permissions`.
1503     ///     assert_eq!(true, permissions.readonly());
1504     ///     Ok(())
1505     /// }
1506     /// ```
set_readonly(&mut self, readonly: bool)1507     pub fn set_readonly(&mut self, readonly: bool) {
1508         self.0.set_readonly(readonly)
1509     }
1510 }
1511 
1512 impl FileType {
1513     /// Tests whether this file type represents a directory. The
1514     /// result is mutually exclusive to the results of
1515     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1516     /// tests may pass.
1517     ///
1518     /// [`is_file`]: FileType::is_file
1519     /// [`is_symlink`]: FileType::is_symlink
1520     ///
1521     /// # Examples
1522     ///
1523     /// ```no_run
1524     /// fn main() -> std::io::Result<()> {
1525     ///     use std::fs;
1526     ///
1527     ///     let metadata = fs::metadata("foo.txt")?;
1528     ///     let file_type = metadata.file_type();
1529     ///
1530     ///     assert_eq!(file_type.is_dir(), false);
1531     ///     Ok(())
1532     /// }
1533     /// ```
1534     #[must_use]
is_dir(&self) -> bool1535     pub fn is_dir(&self) -> bool {
1536         self.0.is_dir()
1537     }
1538 
1539     /// Tests whether this file type represents a regular file.
1540     /// The result is mutually exclusive to the results of
1541     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1542     /// tests may pass.
1543     ///
1544     /// When the goal is simply to read from (or write to) the source, the most
1545     /// reliable way to test the source can be read (or written to) is to open
1546     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1547     /// a Unix-like system for example. See [`File::open`] or
1548     /// [`OpenOptions::open`] for more information.
1549     ///
1550     /// [`is_dir`]: FileType::is_dir
1551     /// [`is_symlink`]: FileType::is_symlink
1552     ///
1553     /// # Examples
1554     ///
1555     /// ```no_run
1556     /// fn main() -> std::io::Result<()> {
1557     ///     use std::fs;
1558     ///
1559     ///     let metadata = fs::metadata("foo.txt")?;
1560     ///     let file_type = metadata.file_type();
1561     ///
1562     ///     assert_eq!(file_type.is_file(), true);
1563     ///     Ok(())
1564     /// }
1565     /// ```
1566     #[must_use]
is_file(&self) -> bool1567     pub fn is_file(&self) -> bool {
1568         self.0.is_file()
1569     }
1570 
1571     /// Tests whether this file type represents a symbolic link.
1572     /// The result is mutually exclusive to the results of
1573     /// [`is_dir`] and [`is_file`]; only zero or one of these
1574     /// tests may pass.
1575     ///
1576     /// The underlying [`Metadata`] struct needs to be retrieved
1577     /// with the [`fs::symlink_metadata`] function and not the
1578     /// [`fs::metadata`] function. The [`fs::metadata`] function
1579     /// follows symbolic links, so [`is_symlink`] would always
1580     /// return `false` for the target file.
1581     ///
1582     /// [`fs::metadata`]: metadata
1583     /// [`fs::symlink_metadata`]: symlink_metadata
1584     /// [`is_dir`]: FileType::is_dir
1585     /// [`is_file`]: FileType::is_file
1586     /// [`is_symlink`]: FileType::is_symlink
1587     ///
1588     /// # Examples
1589     ///
1590     /// ```no_run
1591     /// use std::fs;
1592     ///
1593     /// fn main() -> std::io::Result<()> {
1594     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1595     ///     let file_type = metadata.file_type();
1596     ///
1597     ///     assert_eq!(file_type.is_symlink(), false);
1598     ///     Ok(())
1599     /// }
1600     /// ```
1601     #[must_use]
is_symlink(&self) -> bool1602     pub fn is_symlink(&self) -> bool {
1603         self.0.is_symlink()
1604     }
1605 }
1606 
1607 impl AsInner<fs_imp::FileType> for FileType {
1608     #[inline]
as_inner(&self) -> &fs_imp::FileType1609     fn as_inner(&self) -> &fs_imp::FileType {
1610         &self.0
1611     }
1612 }
1613 
1614 impl FromInner<fs_imp::FilePermissions> for Permissions {
from_inner(f: fs_imp::FilePermissions) -> Permissions1615     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1616         Permissions(f)
1617     }
1618 }
1619 
1620 impl AsInner<fs_imp::FilePermissions> for Permissions {
1621     #[inline]
as_inner(&self) -> &fs_imp::FilePermissions1622     fn as_inner(&self) -> &fs_imp::FilePermissions {
1623         &self.0
1624     }
1625 }
1626 
1627 impl Iterator for ReadDir {
1628     type Item = io::Result<DirEntry>;
1629 
next(&mut self) -> Option<io::Result<DirEntry>>1630     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1631         self.0.next().map(|entry| entry.map(DirEntry))
1632     }
1633 }
1634 
1635 impl DirEntry {
1636     /// Returns the full path to the file that this entry represents.
1637     ///
1638     /// The full path is created by joining the original path to `read_dir`
1639     /// with the filename of this entry.
1640     ///
1641     /// # Examples
1642     ///
1643     /// ```no_run
1644     /// use std::fs;
1645     ///
1646     /// fn main() -> std::io::Result<()> {
1647     ///     for entry in fs::read_dir(".")? {
1648     ///         let dir = entry?;
1649     ///         println!("{:?}", dir.path());
1650     ///     }
1651     ///     Ok(())
1652     /// }
1653     /// ```
1654     ///
1655     /// This prints output like:
1656     ///
1657     /// ```text
1658     /// "./whatever.txt"
1659     /// "./foo.html"
1660     /// "./hello_world.rs"
1661     /// ```
1662     ///
1663     /// The exact text, of course, depends on what files you have in `.`.
1664     #[must_use]
path(&self) -> PathBuf1665     pub fn path(&self) -> PathBuf {
1666         self.0.path()
1667     }
1668 
1669     /// Returns the metadata for the file that this entry points at.
1670     ///
1671     /// This function will not traverse symlinks if this entry points at a
1672     /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1673     ///
1674     /// [`fs::metadata`]: metadata
1675     /// [`fs::File::metadata`]: File::metadata
1676     ///
1677     /// # Platform-specific behavior
1678     ///
1679     /// On Windows this function is cheap to call (no extra system calls
1680     /// needed), but on Unix platforms this function is the equivalent of
1681     /// calling `symlink_metadata` on the path.
1682     ///
1683     /// # Examples
1684     ///
1685     /// ```
1686     /// use std::fs;
1687     ///
1688     /// if let Ok(entries) = fs::read_dir(".") {
1689     ///     for entry in entries {
1690     ///         if let Ok(entry) = entry {
1691     ///             // Here, `entry` is a `DirEntry`.
1692     ///             if let Ok(metadata) = entry.metadata() {
1693     ///                 // Now let's show our entry's permissions!
1694     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1695     ///             } else {
1696     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1697     ///             }
1698     ///         }
1699     ///     }
1700     /// }
1701     /// ```
metadata(&self) -> io::Result<Metadata>1702     pub fn metadata(&self) -> io::Result<Metadata> {
1703         self.0.metadata().map(Metadata)
1704     }
1705 
1706     /// Returns the file type for the file that this entry points at.
1707     ///
1708     /// This function will not traverse symlinks if this entry points at a
1709     /// symlink.
1710     ///
1711     /// # Platform-specific behavior
1712     ///
1713     /// On Windows and most Unix platforms this function is free (no extra
1714     /// system calls needed), but some Unix platforms may require the equivalent
1715     /// call to `symlink_metadata` to learn about the target file type.
1716     ///
1717     /// # Examples
1718     ///
1719     /// ```
1720     /// use std::fs;
1721     ///
1722     /// if let Ok(entries) = fs::read_dir(".") {
1723     ///     for entry in entries {
1724     ///         if let Ok(entry) = entry {
1725     ///             // Here, `entry` is a `DirEntry`.
1726     ///             if let Ok(file_type) = entry.file_type() {
1727     ///                 // Now let's show our entry's file type!
1728     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1729     ///             } else {
1730     ///                 println!("Couldn't get file type for {:?}", entry.path());
1731     ///             }
1732     ///         }
1733     ///     }
1734     /// }
1735     /// ```
file_type(&self) -> io::Result<FileType>1736     pub fn file_type(&self) -> io::Result<FileType> {
1737         self.0.file_type().map(FileType)
1738     }
1739 
1740     /// Returns the file name of this directory entry without any
1741     /// leading path component(s).
1742     ///
1743     /// As an example,
1744     /// the output of the function will result in "foo" for all the following paths:
1745     /// - "./foo"
1746     /// - "/the/foo"
1747     /// - "../../foo"
1748     ///
1749     /// # Examples
1750     ///
1751     /// ```
1752     /// use std::fs;
1753     ///
1754     /// if let Ok(entries) = fs::read_dir(".") {
1755     ///     for entry in entries {
1756     ///         if let Ok(entry) = entry {
1757     ///             // Here, `entry` is a `DirEntry`.
1758     ///             println!("{:?}", entry.file_name());
1759     ///         }
1760     ///     }
1761     /// }
1762     /// ```
1763     #[must_use]
file_name(&self) -> OsString1764     pub fn file_name(&self) -> OsString {
1765         self.0.file_name()
1766     }
1767 }
1768 
1769 impl fmt::Debug for DirEntry {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1770     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1771         f.debug_tuple("DirEntry").field(&self.path()).finish()
1772     }
1773 }
1774 
1775 impl AsInner<fs_imp::DirEntry> for DirEntry {
1776     #[inline]
as_inner(&self) -> &fs_imp::DirEntry1777     fn as_inner(&self) -> &fs_imp::DirEntry {
1778         &self.0
1779     }
1780 }
1781 
1782 /// Removes a file from the filesystem.
1783 ///
1784 /// Note that there is no
1785 /// guarantee that the file is immediately deleted (e.g., depending on
1786 /// platform, other open file descriptors may prevent immediate removal).
1787 ///
1788 /// # Platform-specific behavior
1789 ///
1790 /// This function currently corresponds to the `unlink` function on Unix
1791 /// and the `DeleteFile` function on Windows.
1792 /// Note that, this [may change in the future][changes].
1793 ///
1794 /// [changes]: io#platform-specific-behavior
1795 ///
1796 /// # Errors
1797 ///
1798 /// This function will return an error in the following situations, but is not
1799 /// limited to just these cases:
1800 ///
1801 /// * `path` points to a directory.
1802 /// * The file doesn't exist.
1803 /// * The user lacks permissions to remove the file.
1804 ///
1805 /// # Examples
1806 ///
1807 /// ```no_run
1808 /// use std::fs;
1809 ///
1810 /// fn main() -> std::io::Result<()> {
1811 ///     fs::remove_file("a.txt")?;
1812 ///     Ok(())
1813 /// }
1814 /// ```
remove_file<P: AsRef<Path>>(path: P) -> io::Result<()>1815 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1816     fs_imp::unlink(path.as_ref())
1817 }
1818 
1819 /// Given a path, query the file system to get information about a file,
1820 /// directory, etc.
1821 ///
1822 /// This function will traverse symbolic links to query information about the
1823 /// destination file.
1824 ///
1825 /// # Platform-specific behavior
1826 ///
1827 /// This function currently corresponds to the `stat` function on Unix
1828 /// and the `GetFileInformationByHandle` function on Windows.
1829 /// Note that, this [may change in the future][changes].
1830 ///
1831 /// [changes]: io#platform-specific-behavior
1832 ///
1833 /// # Errors
1834 ///
1835 /// This function will return an error in the following situations, but is not
1836 /// limited to just these cases:
1837 ///
1838 /// * The user lacks permissions to perform `metadata` call on `path`.
1839 /// * `path` does not exist.
1840 ///
1841 /// # Examples
1842 ///
1843 /// ```rust,no_run
1844 /// use std::fs;
1845 ///
1846 /// fn main() -> std::io::Result<()> {
1847 ///     let attr = fs::metadata("/some/file/path.txt")?;
1848 ///     // inspect attr ...
1849 ///     Ok(())
1850 /// }
1851 /// ```
metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata>1852 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1853     fs_imp::stat(path.as_ref()).map(Metadata)
1854 }
1855 
1856 /// Query the metadata about a file without following symlinks.
1857 ///
1858 /// # Platform-specific behavior
1859 ///
1860 /// This function currently corresponds to the `lstat` function on Unix
1861 /// and the `GetFileInformationByHandle` function on Windows.
1862 /// Note that, this [may change in the future][changes].
1863 ///
1864 /// [changes]: io#platform-specific-behavior
1865 ///
1866 /// # Errors
1867 ///
1868 /// This function will return an error in the following situations, but is not
1869 /// limited to just these cases:
1870 ///
1871 /// * The user lacks permissions to perform `metadata` call on `path`.
1872 /// * `path` does not exist.
1873 ///
1874 /// # Examples
1875 ///
1876 /// ```rust,no_run
1877 /// use std::fs;
1878 ///
1879 /// fn main() -> std::io::Result<()> {
1880 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1881 ///     // inspect attr ...
1882 ///     Ok(())
1883 /// }
1884 /// ```
symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata>1885 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1886     fs_imp::lstat(path.as_ref()).map(Metadata)
1887 }
1888 
1889 /// Rename a file or directory to a new name, replacing the original file if
1890 /// `to` already exists.
1891 ///
1892 /// This will not work if the new name is on a different mount point.
1893 ///
1894 /// # Platform-specific behavior
1895 ///
1896 /// This function currently corresponds to the `rename` function on Unix
1897 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1898 ///
1899 /// Because of this, the behavior when both `from` and `to` exist differs. On
1900 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1901 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1902 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1903 ///
1904 /// Note that, this [may change in the future][changes].
1905 ///
1906 /// [changes]: io#platform-specific-behavior
1907 ///
1908 /// # Errors
1909 ///
1910 /// This function will return an error in the following situations, but is not
1911 /// limited to just these cases:
1912 ///
1913 /// * `from` does not exist.
1914 /// * The user lacks permissions to view contents.
1915 /// * `from` and `to` are on separate filesystems.
1916 ///
1917 /// # Examples
1918 ///
1919 /// ```no_run
1920 /// use std::fs;
1921 ///
1922 /// fn main() -> std::io::Result<()> {
1923 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1924 ///     Ok(())
1925 /// }
1926 /// ```
rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()>1927 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1928     fs_imp::rename(from.as_ref(), to.as_ref())
1929 }
1930 
1931 /// Copies the contents of one file to another. This function will also
1932 /// copy the permission bits of the original file to the destination file.
1933 ///
1934 /// This function will **overwrite** the contents of `to`.
1935 ///
1936 /// Note that if `from` and `to` both point to the same file, then the file
1937 /// will likely get truncated by this operation.
1938 ///
1939 /// On success, the total number of bytes copied is returned and it is equal to
1940 /// the length of the `to` file as reported by `metadata`.
1941 ///
1942 /// If you want to copy the contents of one file to another and you’re
1943 /// working with [`File`]s, see the [`io::copy()`] function.
1944 ///
1945 /// # Platform-specific behavior
1946 ///
1947 /// This function currently corresponds to the `open` function in Unix
1948 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1949 /// `O_CLOEXEC` is set for returned file descriptors.
1950 ///
1951 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1952 /// and falls back to reading and writing if that is not possible.
1953 ///
1954 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1955 /// NTFS streams are copied but only the size of the main stream is returned by
1956 /// this function.
1957 ///
1958 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1959 ///
1960 /// Note that platform-specific behavior [may change in the future][changes].
1961 ///
1962 /// [changes]: io#platform-specific-behavior
1963 ///
1964 /// # Errors
1965 ///
1966 /// This function will return an error in the following situations, but is not
1967 /// limited to just these cases:
1968 ///
1969 /// * `from` is neither a regular file nor a symlink to a regular file.
1970 /// * `from` does not exist.
1971 /// * The current process does not have the permission rights to read
1972 ///   `from` or write `to`.
1973 ///
1974 /// # Examples
1975 ///
1976 /// ```no_run
1977 /// use std::fs;
1978 ///
1979 /// fn main() -> std::io::Result<()> {
1980 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1981 ///     Ok(())
1982 /// }
1983 /// ```
copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64>1984 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1985     fs_imp::copy(from.as_ref(), to.as_ref())
1986 }
1987 
1988 /// Creates a new hard link on the filesystem.
1989 ///
1990 /// The `link` path will be a link pointing to the `original` path. Note that
1991 /// systems often require these two paths to both be located on the same
1992 /// filesystem.
1993 ///
1994 /// If `original` names a symbolic link, it is platform-specific whether the
1995 /// symbolic link is followed. On platforms where it's possible to not follow
1996 /// it, it is not followed, and the created hard link points to the symbolic
1997 /// link itself.
1998 ///
1999 /// # Platform-specific behavior
2000 ///
2001 /// This function currently corresponds the `CreateHardLink` function on Windows.
2002 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
2003 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2004 /// On MacOS, it uses the `linkat` function if it is available, but on very old
2005 /// systems where `linkat` is not available, `link` is selected at runtime instead.
2006 /// Note that, this [may change in the future][changes].
2007 ///
2008 /// [changes]: io#platform-specific-behavior
2009 ///
2010 /// # Errors
2011 ///
2012 /// This function will return an error in the following situations, but is not
2013 /// limited to just these cases:
2014 ///
2015 /// * The `original` path is not a file or doesn't exist.
2016 ///
2017 /// # Examples
2018 ///
2019 /// ```no_run
2020 /// use std::fs;
2021 ///
2022 /// fn main() -> std::io::Result<()> {
2023 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2024 ///     Ok(())
2025 /// }
2026 /// ```
hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()>2027 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2028     fs_imp::link(original.as_ref(), link.as_ref())
2029 }
2030 
2031 /// Creates a new symbolic link on the filesystem.
2032 ///
2033 /// The `link` path will be a symbolic link pointing to the `original` path.
2034 /// On Windows, this will be a file symlink, not a directory symlink;
2035 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2036 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2037 /// used instead to make the intent explicit.
2038 ///
2039 /// [`std::os::unix::fs::symlink`]: crate::std::os::unix::fs::symlink
2040 /// [`std::os::windows::fs::symlink_file`]: crate::std::os::windows::fs::symlink_file
2041 /// [`symlink_dir`]: crate::std::os::windows::fs::symlink_dir
2042 ///
2043 /// # Examples
2044 ///
2045 /// ```no_run
2046 /// use std::fs;
2047 ///
2048 /// fn main() -> std::io::Result<()> {
2049 ///     fs::soft_link("a.txt", "b.txt")?;
2050 ///     Ok(())
2051 /// }
2052 /// ```
2053 #[deprecated(
2054     since = "1.1.0",
2055     note = "replaced with std::os::unix::fs::symlink and \
2056             std::os::windows::fs::{symlink_file, symlink_dir}"
2057 )]
soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()>2058 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2059     fs_imp::symlink(original.as_ref(), link.as_ref())
2060 }
2061 
2062 /// Reads a symbolic link, returning the file that the link points to.
2063 ///
2064 /// # Platform-specific behavior
2065 ///
2066 /// This function currently corresponds to the `readlink` function on Unix
2067 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2068 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2069 /// Note that, this [may change in the future][changes].
2070 ///
2071 /// [changes]: io#platform-specific-behavior
2072 ///
2073 /// # Errors
2074 ///
2075 /// This function will return an error in the following situations, but is not
2076 /// limited to just these cases:
2077 ///
2078 /// * `path` is not a symbolic link.
2079 /// * `path` does not exist.
2080 ///
2081 /// # Examples
2082 ///
2083 /// ```no_run
2084 /// use std::fs;
2085 ///
2086 /// fn main() -> std::io::Result<()> {
2087 ///     let path = fs::read_link("a.txt")?;
2088 ///     Ok(())
2089 /// }
2090 /// ```
read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf>2091 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2092     fs_imp::readlink(path.as_ref())
2093 }
2094 
2095 /// Returns the canonical, absolute form of a path with all intermediate
2096 /// components normalized and symbolic links resolved.
2097 ///
2098 /// # Platform-specific behavior
2099 ///
2100 /// This function currently corresponds to the `realpath` function on Unix
2101 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2102 /// Note that, this [may change in the future][changes].
2103 ///
2104 /// On Windows, this converts the path to use [extended length path][path]
2105 /// syntax, which allows your program to use longer path names, but means you
2106 /// can only join backslash-delimited paths to it, and it may be incompatible
2107 /// with other applications (if passed to the application on the command-line,
2108 /// or written to a file another application may read).
2109 ///
2110 /// [changes]: io#platform-specific-behavior
2111 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2112 ///
2113 /// # Errors
2114 ///
2115 /// This function will return an error in the following situations, but is not
2116 /// limited to just these cases:
2117 ///
2118 /// * `path` does not exist.
2119 /// * A non-final component in path is not a directory.
2120 ///
2121 /// # Examples
2122 ///
2123 /// ```no_run
2124 /// use std::fs;
2125 ///
2126 /// fn main() -> std::io::Result<()> {
2127 ///     let path = fs::canonicalize("../a/../foo.txt")?;
2128 ///     Ok(())
2129 /// }
2130 /// ```
2131 #[doc(alias = "realpath")]
2132 #[doc(alias = "GetFinalPathNameByHandle")]
canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf>2133 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2134     fs_imp::canonicalize(path.as_ref())
2135 }
2136 
2137 /// Creates a new, empty directory at the provided path
2138 ///
2139 /// # Platform-specific behavior
2140 ///
2141 /// This function currently corresponds to the `mkdir` function on Unix
2142 /// and the `CreateDirectory` function on Windows.
2143 /// Note that, this [may change in the future][changes].
2144 ///
2145 /// [changes]: io#platform-specific-behavior
2146 ///
2147 /// **NOTE**: If a parent of the given path doesn't exist, this function will
2148 /// return an error. To create a directory and all its missing parents at the
2149 /// same time, use the [`create_dir_all`] function.
2150 ///
2151 /// # Errors
2152 ///
2153 /// This function will return an error in the following situations, but is not
2154 /// limited to just these cases:
2155 ///
2156 /// * User lacks permissions to create directory at `path`.
2157 /// * A parent of the given path doesn't exist. (To create a directory and all
2158 ///   its missing parents at the same time, use the [`create_dir_all`]
2159 ///   function.)
2160 /// * `path` already exists.
2161 ///
2162 /// # Examples
2163 ///
2164 /// ```no_run
2165 /// use std::fs;
2166 ///
2167 /// fn main() -> std::io::Result<()> {
2168 ///     fs::create_dir("/some/dir")?;
2169 ///     Ok(())
2170 /// }
2171 /// ```
2172 #[doc(alias = "mkdir")]
create_dir<P: AsRef<Path>>(path: P) -> io::Result<()>2173 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2174     DirBuilder::new().create(path.as_ref())
2175 }
2176 
2177 /// Recursively create a directory and all of its parent components if they
2178 /// are missing.
2179 ///
2180 /// # Platform-specific behavior
2181 ///
2182 /// This function currently corresponds to the `mkdir` function on Unix
2183 /// and the `CreateDirectory` function on Windows.
2184 /// Note that, this [may change in the future][changes].
2185 ///
2186 /// [changes]: io#platform-specific-behavior
2187 ///
2188 /// # Errors
2189 ///
2190 /// This function will return an error in the following situations, but is not
2191 /// limited to just these cases:
2192 ///
2193 /// * If any directory in the path specified by `path`
2194 /// does not already exist and it could not be created otherwise. The specific
2195 /// error conditions for when a directory is being created (after it is
2196 /// determined to not exist) are outlined by [`fs::create_dir`].
2197 ///
2198 /// Notable exception is made for situations where any of the directories
2199 /// specified in the `path` could not be created as it was being created concurrently.
2200 /// Such cases are considered to be successful. That is, calling `create_dir_all`
2201 /// concurrently from multiple threads or processes is guaranteed not to fail
2202 /// due to a race condition with itself.
2203 ///
2204 /// [`fs::create_dir`]: create_dir
2205 ///
2206 /// # Examples
2207 ///
2208 /// ```no_run
2209 /// use std::fs;
2210 ///
2211 /// fn main() -> std::io::Result<()> {
2212 ///     fs::create_dir_all("/some/dir")?;
2213 ///     Ok(())
2214 /// }
2215 /// ```
create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()>2216 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2217     DirBuilder::new().recursive(true).create(path.as_ref())
2218 }
2219 
2220 /// Removes an empty directory.
2221 ///
2222 /// # Platform-specific behavior
2223 ///
2224 /// This function currently corresponds to the `rmdir` function on Unix
2225 /// and the `RemoveDirectory` function on Windows.
2226 /// Note that, this [may change in the future][changes].
2227 ///
2228 /// [changes]: io#platform-specific-behavior
2229 ///
2230 /// # Errors
2231 ///
2232 /// This function will return an error in the following situations, but is not
2233 /// limited to just these cases:
2234 ///
2235 /// * `path` doesn't exist.
2236 /// * `path` isn't a directory.
2237 /// * The user lacks permissions to remove the directory at the provided `path`.
2238 /// * The directory isn't empty.
2239 ///
2240 /// # Examples
2241 ///
2242 /// ```no_run
2243 /// use std::fs;
2244 ///
2245 /// fn main() -> std::io::Result<()> {
2246 ///     fs::remove_dir("/some/dir")?;
2247 ///     Ok(())
2248 /// }
2249 /// ```
2250 #[doc(alias = "rmdir")]
remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()>2251 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2252     fs_imp::rmdir(path.as_ref())
2253 }
2254 
2255 /// Removes a directory at this path, after removing all its contents. Use
2256 /// carefully!
2257 ///
2258 /// This function does **not** follow symbolic links and it will simply remove the
2259 /// symbolic link itself.
2260 ///
2261 /// # Platform-specific behavior
2262 ///
2263 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2264 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2265 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2266 /// Windows. Note that, this [may change in the future][changes].
2267 ///
2268 /// [changes]: io#platform-specific-behavior
2269 ///
2270 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2271 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2272 /// should not be used in security-sensitive code on those platforms. All other platforms are
2273 /// protected.
2274 ///
2275 /// # Errors
2276 ///
2277 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2278 ///
2279 /// `remove_dir_all` will fail if `remove_dir` or `remove_file` fail on any constituent paths, including the root path.
2280 /// As a result, the directory you are deleting must exist, meaning that this function is not idempotent.
2281 ///
2282 /// Consider ignoring the error if validating the removal is not required for your use case.
2283 ///
2284 /// [`fs::remove_file`]: remove_file
2285 /// [`fs::remove_dir`]: remove_dir
2286 ///
2287 /// # Examples
2288 ///
2289 /// ```no_run
2290 /// use std::fs;
2291 ///
2292 /// fn main() -> std::io::Result<()> {
2293 ///     fs::remove_dir_all("/some/dir")?;
2294 ///     Ok(())
2295 /// }
2296 /// ```
remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()>2297 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2298     fs_imp::remove_dir_all(path.as_ref())
2299 }
2300 
2301 /// Returns an iterator over the entries within a directory.
2302 ///
2303 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2304 /// New errors may be encountered after an iterator is initially constructed.
2305 /// Entries for the current and parent directories (typically `.` and `..`) are
2306 /// skipped.
2307 ///
2308 /// # Platform-specific behavior
2309 ///
2310 /// This function currently corresponds to the `opendir` function on Unix
2311 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2312 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2313 /// Note that, this [may change in the future][changes].
2314 ///
2315 /// [changes]: io#platform-specific-behavior
2316 ///
2317 /// The order in which this iterator returns entries is platform and filesystem
2318 /// dependent.
2319 ///
2320 /// # Errors
2321 ///
2322 /// This function will return an error in the following situations, but is not
2323 /// limited to just these cases:
2324 ///
2325 /// * The provided `path` doesn't exist.
2326 /// * The process lacks permissions to view the contents.
2327 /// * The `path` points at a non-directory file.
2328 ///
2329 /// # Examples
2330 ///
2331 /// ```
2332 /// use std::io;
2333 /// use std::fs::{self, DirEntry};
2334 /// use std::path::Path;
2335 ///
2336 /// // one possible implementation of walking a directory only visiting files
2337 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2338 ///     if dir.is_dir() {
2339 ///         for entry in fs::read_dir(dir)? {
2340 ///             let entry = entry?;
2341 ///             let path = entry.path();
2342 ///             if path.is_dir() {
2343 ///                 visit_dirs(&path, cb)?;
2344 ///             } else {
2345 ///                 cb(&entry);
2346 ///             }
2347 ///         }
2348 ///     }
2349 ///     Ok(())
2350 /// }
2351 /// ```
2352 ///
2353 /// ```rust,no_run
2354 /// use std::{fs, io};
2355 ///
2356 /// fn main() -> io::Result<()> {
2357 ///     let mut entries = fs::read_dir(".")?
2358 ///         .map(|res| res.map(|e| e.path()))
2359 ///         .collect::<Result<Vec<_>, io::Error>>()?;
2360 ///
2361 ///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2362 ///     // ordering is required the entries should be explicitly sorted.
2363 ///
2364 ///     entries.sort();
2365 ///
2366 ///     // The entries have now been sorted by their path.
2367 ///
2368 ///     Ok(())
2369 /// }
2370 /// ```
read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir>2371 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2372     fs_imp::readdir(path.as_ref()).map(ReadDir)
2373 }
2374 
2375 /// Changes the permissions found on a file or a directory.
2376 ///
2377 /// # Platform-specific behavior
2378 ///
2379 /// This function currently corresponds to the `chmod` function on Unix
2380 /// and the `SetFileAttributes` function on Windows.
2381 /// Note that, this [may change in the future][changes].
2382 ///
2383 /// [changes]: io#platform-specific-behavior
2384 ///
2385 /// # Errors
2386 ///
2387 /// This function will return an error in the following situations, but is not
2388 /// limited to just these cases:
2389 ///
2390 /// * `path` does not exist.
2391 /// * The user lacks the permission to change attributes of the file.
2392 ///
2393 /// # Examples
2394 ///
2395 /// ```no_run
2396 /// use std::fs;
2397 ///
2398 /// fn main() -> std::io::Result<()> {
2399 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
2400 ///     perms.set_readonly(true);
2401 ///     fs::set_permissions("foo.txt", perms)?;
2402 ///     Ok(())
2403 /// }
2404 /// ```
set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()>2405 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2406     fs_imp::set_perm(path.as_ref(), perm.0)
2407 }
2408 
2409 impl DirBuilder {
2410     /// Creates a new set of options with default mode/security settings for all
2411     /// platforms and also non-recursive.
2412     ///
2413     /// # Examples
2414     ///
2415     /// ```
2416     /// use std::fs::DirBuilder;
2417     ///
2418     /// let builder = DirBuilder::new();
2419     /// ```
2420     #[must_use]
new() -> DirBuilder2421     pub fn new() -> DirBuilder {
2422         DirBuilder {
2423             inner: fs_imp::DirBuilder::new(),
2424             recursive: false,
2425         }
2426     }
2427 
2428     /// Indicates that directories should be created recursively, creating all
2429     /// parent directories. Parents that do not exist are created with the same
2430     /// security and permissions settings.
2431     ///
2432     /// This option defaults to `false`.
2433     ///
2434     /// # Examples
2435     ///
2436     /// ```
2437     /// use std::fs::DirBuilder;
2438     ///
2439     /// let mut builder = DirBuilder::new();
2440     /// builder.recursive(true);
2441     /// ```
recursive(&mut self, recursive: bool) -> &mut Self2442     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2443         self.recursive = recursive;
2444         self
2445     }
2446 
2447     /// Creates the specified directory with the options configured in this
2448     /// builder.
2449     ///
2450     /// It is considered an error if the directory already exists unless
2451     /// recursive mode is enabled.
2452     ///
2453     /// # Examples
2454     ///
2455     /// ```no_run
2456     /// use std::fs::{self, DirBuilder};
2457     ///
2458     /// let path = "/tmp/foo/bar/baz";
2459     /// DirBuilder::new()
2460     ///     .recursive(true)
2461     ///     .create(path).unwrap();
2462     ///
2463     /// assert!(fs::metadata(path).unwrap().is_dir());
2464     /// ```
create<P: AsRef<Path>>(&self, path: P) -> io::Result<()>2465     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2466         self._create(path.as_ref())
2467     }
2468 
_create(&self, path: &Path) -> io::Result<()>2469     fn _create(&self, path: &Path) -> io::Result<()> {
2470         if self.recursive {
2471             self.create_dir_all(path)
2472         } else {
2473             self.inner.mkdir(path)
2474         }
2475     }
2476 
create_dir_all(&self, path: &Path) -> io::Result<()>2477     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2478         if path == Path::new("") {
2479             return Ok(());
2480         }
2481 
2482         match self.inner.mkdir(path) {
2483             Ok(()) => return Ok(()),
2484             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2485             Err(_) if path.is_dir() => return Ok(()),
2486             Err(e) => return Err(e),
2487         }
2488         match path.parent() {
2489             Some(p) => self.create_dir_all(p)?,
2490             None => {
2491                 return Err(io::const_io_error!(
2492                     io::ErrorKind::Uncategorized,
2493                     "failed to create whole tree",
2494                 ));
2495             }
2496         }
2497         match self.inner.mkdir(path) {
2498             Ok(()) => Ok(()),
2499             Err(_) if path.is_dir() => Ok(()),
2500             Err(e) => Err(e),
2501         }
2502     }
2503 }
2504 
2505 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2506     #[inline]
as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder2507     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2508         &mut self.inner
2509     }
2510 }
2511 
2512 /// Returns `Ok(true)` if the path points at an existing entity.
2513 ///
2514 /// This function will traverse symbolic links to query information about the
2515 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2516 ///
2517 /// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
2518 /// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
2519 /// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
2520 /// permission is denied on one of the parent directories.
2521 ///
2522 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2523 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2524 /// where those bugs are not an issue.
2525 ///
2526 /// # Examples
2527 ///
2528 /// ```no_run
2529 /// #![feature(fs_try_exists)]
2530 /// use std::fs;
2531 ///
2532 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2533 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2534 /// ```
2535 ///
2536 /// [`Path::exists`]: crate::std::path::Path::exists
2537 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2538 // instead.
2539 #[inline]
try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool>2540 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2541     fs_imp::try_exists(path.as_ref())
2542 }
2543