Skip to main content

std/
fs.rs

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//! # Time of Check to Time of Use (TOCTOU)
9//!
10//! Many filesystem operations are subject to a race condition known as "Time of Check to Time of Use"
11//! (TOCTOU). This occurs when a program checks a condition (like file existence or permissions)
12//! and then uses the result of that check to make a decision, but the condition may have changed
13//! between the check and the use.
14//!
15//! For example, checking if a file exists and then creating it if it doesn't is vulnerable to
16//! TOCTOU - another process could create the file between your check and creation attempt.
17//!
18//! Another example is with symbolic links: when removing a directory, if another process replaces
19//! the directory with a symbolic link between the check and the removal operation, the removal
20//! might affect the wrong location. This is why operations like [`remove_dir_all`] need to use
21//! atomic operations to prevent such race conditions.
22//!
23//! To avoid TOCTOU issues:
24//! - Be aware that metadata operations (like [`metadata`] or [`symlink_metadata`]) may be affected by
25//! changes made by other processes.
26//! - Use atomic operations when possible (like [`File::create_new`] instead of checking existence then creating).
27//! - Keep file open for the duration of operations.
28
29#![stable(feature = "rust1", since = "1.0.0")]
30#![deny(unsafe_op_in_unsafe_fn)]
31
32#[cfg(all(
33    test,
34    not(any(
35        target_os = "emscripten",
36        target_os = "wasi",
37        target_env = "sgx",
38        target_os = "xous",
39        target_os = "trusty",
40    ))
41))]
42mod tests;
43
44use crate::ffi::OsString;
45use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
46use crate::path::{Path, PathBuf};
47use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner, fs as fs_imp};
48use crate::time::SystemTime;
49use crate::{error, fmt};
50
51/// An object providing access to an open file on the filesystem.
52///
53/// An instance of a `File` can be read and/or written depending on what options
54/// it was opened with. Files also implement [`Seek`] to alter the logical cursor
55/// that the file contains internally.
56///
57/// Files are automatically closed when they go out of scope.  Errors detected
58/// on closing are ignored by the implementation of `Drop`.  Use the method
59/// [`sync_all`] if these errors must be manually handled.
60///
61/// `File` does not buffer reads and writes. For efficiency, consider wrapping the
62/// file in a [`BufReader`] or [`BufWriter`] when performing many small [`read`]
63/// or [`write`] calls, unless unbuffered reads and writes are required.
64///
65/// # Examples
66///
67/// Creates a new file and write bytes to it (you can also use [`write`]):
68///
69/// ```no_run
70/// use std::fs::File;
71/// use std::io::prelude::*;
72///
73/// fn main() -> std::io::Result<()> {
74///     let mut file = File::create("foo.txt")?;
75///     file.write_all(b"Hello, world!")?;
76///     Ok(())
77/// }
78/// ```
79///
80/// Reads the contents of a file into a [`String`] (you can also use [`read`]):
81///
82/// ```no_run
83/// use std::fs::File;
84/// use std::io::prelude::*;
85///
86/// fn main() -> std::io::Result<()> {
87///     let mut file = File::open("foo.txt")?;
88///     let mut contents = String::new();
89///     file.read_to_string(&mut contents)?;
90///     assert_eq!(contents, "Hello, world!");
91///     Ok(())
92/// }
93/// ```
94///
95/// Using a buffered [`Read`]er:
96///
97/// ```no_run
98/// use std::fs::File;
99/// use std::io::BufReader;
100/// use std::io::prelude::*;
101///
102/// fn main() -> std::io::Result<()> {
103///     let file = File::open("foo.txt")?;
104///     let mut buf_reader = BufReader::new(file);
105///     let mut contents = String::new();
106///     buf_reader.read_to_string(&mut contents)?;
107///     assert_eq!(contents, "Hello, world!");
108///     Ok(())
109/// }
110/// ```
111///
112/// Note that, although read and write methods require a `&mut File`, because
113/// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
114/// still modify the file, either through methods that take `&File` or by
115/// retrieving the underlying OS object and modifying the file that way.
116/// Additionally, many operating systems allow concurrent modification of files
117/// by different processes. Avoid assuming that holding a `&File` means that the
118/// file will not change.
119///
120/// # Platform-specific behavior
121///
122/// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
123/// perform synchronous I/O operations. Therefore the underlying file must not
124/// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
125///
126/// [`BufReader`]: io::BufReader
127/// [`BufWriter`]: io::BufWriter
128/// [`sync_all`]: File::sync_all
129/// [`write`]: File::write
130/// [`read`]: File::read
131#[stable(feature = "rust1", since = "1.0.0")]
132#[cfg_attr(not(test), rustc_diagnostic_item = "File")]
133#[diagnostic::on_move(note = "you can use `File::try_clone` to duplicate a `File` instance")]
134pub struct File {
135    inner: fs_imp::File,
136}
137
138/// An enumeration of possible errors which can occur while trying to acquire a lock
139/// from the [`try_lock`] method and [`try_lock_shared`] method on a [`File`].
140///
141/// [`try_lock`]: File::try_lock
142/// [`try_lock_shared`]: File::try_lock_shared
143#[stable(feature = "file_lock", since = "1.89.0")]
144pub enum TryLockError {
145    /// The lock could not be acquired due to an I/O error on the file. The standard library will
146    /// not return an [`ErrorKind::WouldBlock`] error inside [`TryLockError::Error`]
147    ///
148    /// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
149    Error(io::Error),
150    /// The lock could not be acquired at this time because it is held by another handle/process.
151    WouldBlock,
152}
153
154/// An object providing access to a directory on the filesystem.
155///
156/// Directories are automatically closed when they go out of scope.  Errors detected
157/// on closing are ignored by the implementation of `Drop`.
158///
159/// # Platform-specific behavior
160///
161/// On supported systems (including Windows and some UNIX-based OSes), this function acquires a
162/// handle/file descriptor for the directory. This allows functions like [`Dir::open_file`] to
163/// avoid [TOCTOU] errors when the directory itself is being moved.
164///
165/// On other systems, it stores an absolute path (see [`canonicalize()`]). In the latter case, no
166/// [TOCTOU] guarantees are made.
167///
168/// # Examples
169///
170/// Opens a directory and then a file inside it.
171///
172/// ```no_run
173/// #![feature(dirfd)]
174/// use std::{fs::Dir, io};
175///
176/// fn main() -> std::io::Result<()> {
177///     let dir = Dir::open("foo")?;
178///     let mut file = dir.open_file("bar.txt")?;
179///     let contents = io::read_to_string(file)?;
180///     assert_eq!(contents, "Hello, world!");
181///     Ok(())
182/// }
183/// ```
184///
185/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
186#[unstable(feature = "dirfd", issue = "120426")]
187pub struct Dir {
188    inner: fs_imp::Dir,
189}
190
191/// Metadata information about a file.
192///
193/// This structure is returned from the [`metadata`] or
194/// [`symlink_metadata`] function or method and represents known
195/// metadata about a file such as its permissions, size, modification
196/// times, etc.
197#[stable(feature = "rust1", since = "1.0.0")]
198#[derive(Clone)]
199pub struct Metadata(fs_imp::FileAttr);
200
201/// Iterator over the entries in a directory.
202///
203/// This iterator is returned from the [`read_dir`] function of this module and
204/// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
205/// information like the entry's path and possibly other metadata can be
206/// learned.
207///
208/// The order in which this iterator returns entries is platform and filesystem
209/// dependent.
210///
211/// # Errors
212/// This [`io::Result`] will be an [`Err`] if an error occurred while fetching
213/// the next entry from the OS.
214#[stable(feature = "rust1", since = "1.0.0")]
215#[derive(Debug)]
216pub struct ReadDir(fs_imp::ReadDir);
217
218/// Entries returned by the [`ReadDir`] iterator.
219///
220/// An instance of `DirEntry` represents an entry inside of a directory on the
221/// filesystem. Each entry can be inspected via methods to learn about the full
222/// path or possibly other metadata through per-platform extension traits.
223///
224/// # Platform-specific behavior
225///
226/// On Unix, the `DirEntry` struct contains an internal reference to the open
227/// directory. Holding `DirEntry` objects will consume a file handle even
228/// after the `ReadDir` iterator is dropped.
229///
230/// Note that this [may change in the future][changes].
231///
232/// [changes]: io#platform-specific-behavior
233#[stable(feature = "rust1", since = "1.0.0")]
234pub struct DirEntry(fs_imp::DirEntry);
235
236/// Options and flags which can be used to configure how a file is opened.
237///
238/// This builder exposes the ability to configure how a [`File`] is opened and
239/// what operations are permitted on the open file. The [`File::open`] and
240/// [`File::create`] methods are aliases for commonly used options using this
241/// builder.
242///
243/// Generally speaking, when using `OpenOptions`, you'll first call
244/// [`OpenOptions::new`], then chain calls to methods to set each option, then
245/// call [`OpenOptions::open`], passing the path of the file you're trying to
246/// open. This will give you a [`io::Result`] with a [`File`] inside that you
247/// can further operate on.
248///
249/// # Examples
250///
251/// Opening a file to read:
252///
253/// ```no_run
254/// use std::fs::OpenOptions;
255///
256/// let file = OpenOptions::new().read(true).open("foo.txt");
257/// ```
258///
259/// Opening a file for both reading and writing, as well as creating it if it
260/// doesn't exist:
261///
262/// ```no_run
263/// use std::fs::OpenOptions;
264///
265/// let file = OpenOptions::new()
266///             .read(true)
267///             .write(true)
268///             .create(true)
269///             .open("foo.txt");
270/// ```
271#[derive(Clone, Debug)]
272#[stable(feature = "rust1", since = "1.0.0")]
273#[cfg_attr(not(test), rustc_diagnostic_item = "FsOpenOptions")]
274pub struct OpenOptions(fs_imp::OpenOptions);
275
276/// Representation of the various timestamps on a file.
277#[derive(Copy, Clone, Debug, Default)]
278#[stable(feature = "file_set_times", since = "1.75.0")]
279#[must_use = "must be applied to a file via `File::set_times` to have any effect"]
280pub struct FileTimes(fs_imp::FileTimes);
281
282/// Representation of the various permissions on a file.
283///
284/// This module only currently provides one bit of information,
285/// [`Permissions::readonly`], which is exposed on all currently supported
286/// platforms. Unix-specific functionality, such as mode bits, is available
287/// through the [`PermissionsExt`] trait.
288///
289/// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
290#[derive(Clone, PartialEq, Eq, Debug)]
291#[stable(feature = "rust1", since = "1.0.0")]
292#[cfg_attr(not(test), rustc_diagnostic_item = "FsPermissions")]
293pub struct Permissions(fs_imp::FilePermissions);
294
295/// A structure representing a type of file with accessors for each file type.
296/// It is returned by [`Metadata::file_type`] method.
297#[stable(feature = "file_type", since = "1.1.0")]
298#[derive(Copy, Clone, PartialEq, Eq, Hash)]
299#[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
300pub struct FileType(fs_imp::FileType);
301
302/// A builder used to create directories in various manners.
303///
304/// This builder also supports platform-specific options.
305#[stable(feature = "dir_builder", since = "1.6.0")]
306#[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
307#[derive(Debug)]
308pub struct DirBuilder {
309    inner: fs_imp::DirBuilder,
310    recursive: bool,
311}
312
313/// Reads the entire contents of a file into a bytes vector.
314///
315/// This is a convenience function for using [`File::open`] and [`read_to_end`]
316/// with fewer imports and without an intermediate variable.
317///
318/// [`read_to_end`]: Read::read_to_end
319///
320/// # Errors
321///
322/// This function will return an error if `path` does not already exist.
323/// Other errors may also be returned according to [`OpenOptions::open`].
324///
325/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
326/// with automatic retries. See [io::Read] documentation for details.
327///
328/// # Examples
329///
330/// ```no_run
331/// use std::fs;
332///
333/// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
334///     let data: Vec<u8> = fs::read("image.jpg")?;
335///     assert_eq!(data[0..3], [0xFF, 0xD8, 0xFF]);
336///     Ok(())
337/// }
338/// ```
339#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
340pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
341    fn inner(path: &Path) -> io::Result<Vec<u8>> {
342        let mut file = File::open(path)?;
343        let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
344        let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?;
345        io::default_read_to_end(&mut file, &mut bytes, size)?;
346        Ok(bytes)
347    }
348    inner(path.as_ref())
349}
350
351/// Reads the entire contents of a file into a string.
352///
353/// This is a convenience function for using [`File::open`] and [`read_to_string`]
354/// with fewer imports and without an intermediate variable.
355///
356/// [`read_to_string`]: Read::read_to_string
357///
358/// # Errors
359///
360/// This function will return an error if `path` does not already exist.
361/// Other errors may also be returned according to [`OpenOptions::open`].
362///
363/// If the contents of the file are not valid UTF-8, then an error will also be
364/// returned.
365///
366/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
367/// with automatic retries. See [io::Read] documentation for details.
368///
369/// # Examples
370///
371/// ```no_run
372/// use std::fs;
373/// use std::error::Error;
374///
375/// fn main() -> Result<(), Box<dyn Error>> {
376///     let message: String = fs::read_to_string("message.txt")?;
377///     println!("{}", message);
378///     Ok(())
379/// }
380/// ```
381#[stable(feature = "fs_read_write", since = "1.26.0")]
382pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
383    fn inner(path: &Path) -> io::Result<String> {
384        let mut file = File::open(path)?;
385        let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
386        let mut string = String::new();
387        string.try_reserve_exact(size.unwrap_or(0))?;
388        io::default_read_to_string(&mut file, &mut string, size)?;
389        Ok(string)
390    }
391    inner(path.as_ref())
392}
393
394/// Writes a slice as the entire contents of a file.
395///
396/// This function will create a file if it does not exist,
397/// and will entirely replace its contents if it does.
398///
399/// Depending on the platform, this function may fail if the
400/// full directory path does not exist.
401///
402/// This is a convenience function for using [`File::create`] and [`write_all`]
403/// with fewer imports.
404///
405/// [`write_all`]: Write::write_all
406///
407/// # Examples
408///
409/// ```no_run
410/// use std::fs;
411///
412/// fn main() -> std::io::Result<()> {
413///     fs::write("foo.txt", b"Lorem ipsum")?;
414///     fs::write("bar.txt", "dolor sit")?;
415///     Ok(())
416/// }
417/// ```
418#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
419pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
420    fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
421        File::create(path)?.write_all(contents)
422    }
423    inner(path.as_ref(), contents.as_ref())
424}
425
426/// Changes the timestamps of the file or directory at the specified path.
427///
428/// This function will attempt to set the access and modification times
429/// to the times specified. If the path refers to a symbolic link, this function
430/// will follow the link and change the timestamps of the target file.
431///
432/// # Platform-specific behavior
433///
434/// This function currently corresponds to the `utimensat` function on Unix platforms, the
435/// `setattrlist` function on Apple platforms, and the `SetFileTime` function on Windows.
436///
437/// # Errors
438///
439/// This function will return an error if the user lacks permission to change timestamps on the
440/// target file or symlink. It may also return an error if the OS does not support it.
441///
442/// # Examples
443///
444/// ```no_run
445/// #![feature(fs_set_times)]
446/// use std::fs::{self, FileTimes};
447/// use std::time::SystemTime;
448///
449/// fn main() -> std::io::Result<()> {
450///     let now = SystemTime::now();
451///     let times = FileTimes::new()
452///         .set_accessed(now)
453///         .set_modified(now);
454///     fs::set_times("foo.txt", times)?;
455///     Ok(())
456/// }
457/// ```
458#[unstable(feature = "fs_set_times", issue = "147455")]
459#[doc(alias = "utimens")]
460#[doc(alias = "utimes")]
461#[doc(alias = "utime")]
462pub fn set_times<P: AsRef<Path>>(path: P, times: FileTimes) -> io::Result<()> {
463    fs_imp::set_times(path.as_ref(), times.0)
464}
465
466/// Changes the timestamps of the file or symlink at the specified path.
467///
468/// This function will attempt to set the access and modification times
469/// to the times specified. Differ from `set_times`, if the path refers to a symbolic link,
470/// this function will change the timestamps of the symlink itself, not the target file.
471///
472/// # Platform-specific behavior
473///
474/// This function currently corresponds to the `utimensat` function with `AT_SYMLINK_NOFOLLOW` on
475/// Unix platforms, the `setattrlist` function with `FSOPT_NOFOLLOW` on Apple platforms, and the
476/// `SetFileTime` function on Windows.
477///
478/// # Errors
479///
480/// This function will return an error if the user lacks permission to change timestamps on the
481/// target file or symlink. It may also return an error if the OS does not support it.
482///
483/// # Examples
484///
485/// ```no_run
486/// #![feature(fs_set_times)]
487/// use std::fs::{self, FileTimes};
488/// use std::time::SystemTime;
489///
490/// fn main() -> std::io::Result<()> {
491///     let now = SystemTime::now();
492///     let times = FileTimes::new()
493///         .set_accessed(now)
494///         .set_modified(now);
495///     fs::set_times_nofollow("symlink.txt", times)?;
496///     Ok(())
497/// }
498/// ```
499#[unstable(feature = "fs_set_times", issue = "147455")]
500#[doc(alias = "utimensat")]
501#[doc(alias = "lutimens")]
502#[doc(alias = "lutimes")]
503pub fn set_times_nofollow<P: AsRef<Path>>(path: P, times: FileTimes) -> io::Result<()> {
504    fs_imp::set_times_nofollow(path.as_ref(), times.0)
505}
506
507#[stable(feature = "file_lock", since = "1.89.0")]
508impl error::Error for TryLockError {}
509
510#[stable(feature = "file_lock", since = "1.89.0")]
511impl fmt::Debug for TryLockError {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        match self {
514            TryLockError::Error(err) => err.fmt(f),
515            TryLockError::WouldBlock => "WouldBlock".fmt(f),
516        }
517    }
518}
519
520#[stable(feature = "file_lock", since = "1.89.0")]
521impl fmt::Display for TryLockError {
522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523        match self {
524            TryLockError::Error(_) => "lock acquisition failed due to I/O error",
525            TryLockError::WouldBlock => "lock acquisition failed because the operation would block",
526        }
527        .fmt(f)
528    }
529}
530
531#[stable(feature = "file_lock", since = "1.89.0")]
532impl From<TryLockError> for io::Error {
533    fn from(err: TryLockError) -> io::Error {
534        match err {
535            TryLockError::Error(err) => err,
536            TryLockError::WouldBlock => io::ErrorKind::WouldBlock.into(),
537        }
538    }
539}
540
541impl File {
542    /// Attempts to open a file in read-only mode.
543    ///
544    /// See the [`OpenOptions::open`] method for more details.
545    ///
546    /// If you only need to read the entire file contents,
547    /// consider [`std::fs::read()`][self::read] or
548    /// [`std::fs::read_to_string()`][self::read_to_string] instead.
549    ///
550    /// # Errors
551    ///
552    /// This function will return an error if `path` does not already exist.
553    /// Other errors may also be returned according to [`OpenOptions::open`].
554    ///
555    /// # Examples
556    ///
557    /// ```no_run
558    /// use std::fs::File;
559    /// use std::io::Read;
560    ///
561    /// fn main() -> std::io::Result<()> {
562    ///     let mut f = File::open("foo.txt")?;
563    ///     let mut data = vec![];
564    ///     f.read_to_end(&mut data)?;
565    ///     Ok(())
566    /// }
567    /// ```
568    #[stable(feature = "rust1", since = "1.0.0")]
569    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
570        OpenOptions::new().read(true).open(path.as_ref())
571    }
572
573    /// Attempts to open a file in read-only mode with buffering.
574    ///
575    /// See the [`OpenOptions::open`] method, the [`BufReader`][io::BufReader] type,
576    /// and the [`BufRead`][io::BufRead] trait for more details.
577    ///
578    /// If you only need to read the entire file contents,
579    /// consider [`std::fs::read()`][self::read] or
580    /// [`std::fs::read_to_string()`][self::read_to_string] instead.
581    ///
582    /// # Errors
583    ///
584    /// This function will return an error if `path` does not already exist,
585    /// or if memory allocation fails for the new buffer.
586    /// Other errors may also be returned according to [`OpenOptions::open`].
587    ///
588    /// # Examples
589    ///
590    /// ```no_run
591    /// #![feature(file_buffered)]
592    /// use std::fs::File;
593    /// use std::io::BufRead;
594    ///
595    /// fn main() -> std::io::Result<()> {
596    ///     let mut f = File::open_buffered("foo.txt")?;
597    ///     assert!(f.capacity() > 0);
598    ///     for (line, i) in f.lines().zip(1..) {
599    ///         println!("{i:6}: {}", line?);
600    ///     }
601    ///     Ok(())
602    /// }
603    /// ```
604    #[unstable(feature = "file_buffered", issue = "130804")]
605    pub fn open_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufReader<File>> {
606        // Allocate the buffer *first* so we don't affect the filesystem otherwise.
607        let buffer = io::BufReader::<Self>::try_new_buffer()?;
608        let file = File::open(path)?;
609        Ok(io::BufReader::with_buffer(file, buffer))
610    }
611
612    /// Opens a file in write-only mode.
613    ///
614    /// This function will create a file if it does not exist,
615    /// and will truncate it if it does.
616    ///
617    /// Depending on the platform, this function may fail if the
618    /// full directory path does not exist.
619    /// See the [`OpenOptions::open`] function for more details.
620    ///
621    /// See also [`std::fs::write()`][self::write] for a simple function to
622    /// create a file with some given data.
623    ///
624    /// # Examples
625    ///
626    /// ```no_run
627    /// use std::fs::File;
628    /// use std::io::Write;
629    ///
630    /// fn main() -> std::io::Result<()> {
631    ///     let mut f = File::create("foo.txt")?;
632    ///     f.write_all(&1234_u32.to_be_bytes())?;
633    ///     Ok(())
634    /// }
635    /// ```
636    #[stable(feature = "rust1", since = "1.0.0")]
637    pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
638        OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
639    }
640
641    /// Opens a file in write-only mode with buffering.
642    ///
643    /// This function will create a file if it does not exist,
644    /// and will truncate it if it does.
645    ///
646    /// Depending on the platform, this function may fail if the
647    /// full directory path does not exist.
648    ///
649    /// See the [`OpenOptions::open`] method and the
650    /// [`BufWriter`][io::BufWriter] type for more details.
651    ///
652    /// See also [`std::fs::write()`][self::write] for a simple function to
653    /// create a file with some given data.
654    ///
655    /// # Examples
656    ///
657    /// ```no_run
658    /// #![feature(file_buffered)]
659    /// use std::fs::File;
660    /// use std::io::Write;
661    ///
662    /// fn main() -> std::io::Result<()> {
663    ///     let mut f = File::create_buffered("foo.txt")?;
664    ///     assert!(f.capacity() > 0);
665    ///     for i in 0..100 {
666    ///         writeln!(&mut f, "{i}")?;
667    ///     }
668    ///     f.flush()?;
669    ///     Ok(())
670    /// }
671    /// ```
672    #[unstable(feature = "file_buffered", issue = "130804")]
673    pub fn create_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufWriter<File>> {
674        // Allocate the buffer *first* so we don't affect the filesystem otherwise.
675        let buffer = io::BufWriter::<Self>::try_new_buffer()?;
676        let file = File::create(path)?;
677        Ok(io::BufWriter::with_buffer(file, buffer))
678    }
679
680    /// Creates a new file in read-write mode; error if the file exists.
681    ///
682    /// This function will create a file if it does not exist, or return an error if it does. This
683    /// way, if the call succeeds, the file returned is guaranteed to be new.
684    /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
685    /// or another error based on the situation. See [`OpenOptions::open`] for a
686    /// non-exhaustive list of likely errors.
687    ///
688    /// This option is useful because it is atomic. Otherwise between checking whether a file
689    /// exists and creating a new one, the file may have been created by another process (a [TOCTOU]
690    /// race condition / attack).
691    ///
692    /// This can also be written using
693    /// `File::options().read(true).write(true).create_new(true).open(...)`.
694    ///
695    /// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
696    /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
697    ///
698    /// # Examples
699    ///
700    /// ```no_run
701    /// use std::fs::File;
702    /// use std::io::Write;
703    ///
704    /// fn main() -> std::io::Result<()> {
705    ///     let mut f = File::create_new("foo.txt")?;
706    ///     f.write_all("Hello, world!".as_bytes())?;
707    ///     Ok(())
708    /// }
709    /// ```
710    #[stable(feature = "file_create_new", since = "1.77.0")]
711    pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
712        OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
713    }
714
715    /// Returns a new OpenOptions object.
716    ///
717    /// This function returns a new OpenOptions object that you can use to
718    /// open or create a file with specific options if `open()` or `create()`
719    /// are not appropriate.
720    ///
721    /// It is equivalent to `OpenOptions::new()`, but allows you to write more
722    /// readable code. Instead of
723    /// `OpenOptions::new().append(true).open("example.log")`,
724    /// you can write `File::options().append(true).open("example.log")`. This
725    /// also avoids the need to import `OpenOptions`.
726    ///
727    /// See the [`OpenOptions::new`] function for more details.
728    ///
729    /// # Examples
730    ///
731    /// ```no_run
732    /// use std::fs::File;
733    /// use std::io::Write;
734    ///
735    /// fn main() -> std::io::Result<()> {
736    ///     let mut f = File::options().append(true).open("example.log")?;
737    ///     writeln!(&mut f, "new line")?;
738    ///     Ok(())
739    /// }
740    /// ```
741    #[must_use]
742    #[stable(feature = "with_options", since = "1.58.0")]
743    #[cfg_attr(not(test), rustc_diagnostic_item = "file_options")]
744    pub fn options() -> OpenOptions {
745        OpenOptions::new()
746    }
747
748    /// Attempts to sync all OS-internal file content and metadata to disk.
749    ///
750    /// This function will attempt to ensure that all in-memory data reaches the
751    /// filesystem before returning.
752    ///
753    /// This can be used to handle errors that would otherwise only be caught
754    /// when the `File` is closed, as dropping a `File` will ignore all errors.
755    /// Note, however, that `sync_all` is generally more expensive than closing
756    /// a file by dropping it, because the latter is not required to block until
757    /// the data has been written to the filesystem.
758    ///
759    /// If synchronizing the metadata is not required, use [`sync_data`] instead.
760    ///
761    /// [`sync_data`]: File::sync_data
762    ///
763    /// # Examples
764    ///
765    /// ```no_run
766    /// use std::fs::File;
767    /// use std::io::prelude::*;
768    ///
769    /// fn main() -> std::io::Result<()> {
770    ///     let mut f = File::create("foo.txt")?;
771    ///     f.write_all(b"Hello, world!")?;
772    ///
773    ///     f.sync_all()?;
774    ///     Ok(())
775    /// }
776    /// ```
777    #[stable(feature = "rust1", since = "1.0.0")]
778    #[doc(alias = "fsync")]
779    pub fn sync_all(&self) -> io::Result<()> {
780        self.inner.fsync()
781    }
782
783    /// This function is similar to [`sync_all`], except that it might not
784    /// synchronize file metadata to the filesystem.
785    ///
786    /// This is intended for use cases that must synchronize content, but don't
787    /// need the metadata on disk. The goal of this method is to reduce disk
788    /// operations.
789    ///
790    /// Note that some platforms may simply implement this in terms of
791    /// [`sync_all`].
792    ///
793    /// [`sync_all`]: File::sync_all
794    ///
795    /// # Examples
796    ///
797    /// ```no_run
798    /// use std::fs::File;
799    /// use std::io::prelude::*;
800    ///
801    /// fn main() -> std::io::Result<()> {
802    ///     let mut f = File::create("foo.txt")?;
803    ///     f.write_all(b"Hello, world!")?;
804    ///
805    ///     f.sync_data()?;
806    ///     Ok(())
807    /// }
808    /// ```
809    #[stable(feature = "rust1", since = "1.0.0")]
810    #[doc(alias = "fdatasync")]
811    pub fn sync_data(&self) -> io::Result<()> {
812        self.inner.datasync()
813    }
814
815    /// Acquire an exclusive lock on the file. Blocks until the lock can be acquired.
816    ///
817    /// This acquires an exclusive lock. No *other* file handle to this file, in this or any other
818    /// process, may acquire another lock.
819    /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
820    /// is unspecified and platform dependent, including the possibility that it will deadlock.
821    /// However, if this method returns, then an exclusive lock is held.
822    ///
823    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
824    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
825    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
826    /// cause non-lockholders to block.
827    ///
828    /// If the file is not open for writing, it is unspecified whether this function returns an error.
829    ///
830    /// The lock will be released when this file (along with any other file descriptors/handles
831    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
832    ///
833    /// # Platform-specific behavior
834    ///
835    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
836    /// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
837    /// this [may change in the future][changes].
838    ///
839    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
840    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
841    ///
842    /// [changes]: io#platform-specific-behavior
843    ///
844    /// [`lock`]: File::lock
845    /// [`lock_shared`]: File::lock_shared
846    /// [`try_lock`]: File::try_lock
847    /// [`try_lock_shared`]: File::try_lock_shared
848    /// [`unlock`]: File::unlock
849    /// [`read`]: Read::read
850    /// [`write`]: Write::write
851    ///
852    /// # Examples
853    ///
854    /// ```no_run
855    /// use std::fs::File;
856    ///
857    /// fn main() -> std::io::Result<()> {
858    ///     let f = File::create("foo.txt")?;
859    ///     f.lock()?;
860    ///     Ok(())
861    /// }
862    /// ```
863    #[stable(feature = "file_lock", since = "1.89.0")]
864    pub fn lock(&self) -> io::Result<()> {
865        self.inner.lock()
866    }
867
868    /// Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.
869    ///
870    /// This acquires a shared lock. More than one file handle to this file, in this or any other
871    /// process, may hold a shared lock, but no *other* file handle may hold an exclusive lock at
872    /// the same time.
873    /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact
874    /// behavior is unspecified and platform dependent, including the possibility that it will
875    /// deadlock. However, if this method returns, then a shared lock is held.
876    ///
877    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
878    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
879    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
880    /// cause non-lockholders to block.
881    ///
882    /// The lock will be released when this file (along with any other file descriptors/handles
883    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
884    ///
885    /// # Platform-specific behavior
886    ///
887    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
888    /// and the `LockFileEx` function on Windows. Note that, this
889    /// [may change in the future][changes].
890    ///
891    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
892    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
893    ///
894    /// [changes]: io#platform-specific-behavior
895    ///
896    /// [`lock`]: File::lock
897    /// [`lock_shared`]: File::lock_shared
898    /// [`try_lock`]: File::try_lock
899    /// [`try_lock_shared`]: File::try_lock_shared
900    /// [`unlock`]: File::unlock
901    /// [`read`]: Read::read
902    /// [`write`]: Write::write
903    ///
904    /// # Examples
905    ///
906    /// ```no_run
907    /// use std::fs::File;
908    ///
909    /// fn main() -> std::io::Result<()> {
910    ///     let f = File::open("foo.txt")?;
911    ///     f.lock_shared()?;
912    ///     Ok(())
913    /// }
914    /// ```
915    #[stable(feature = "file_lock", since = "1.89.0")]
916    pub fn lock_shared(&self) -> io::Result<()> {
917        self.inner.lock_shared()
918    }
919
920    /// Try to acquire an exclusive lock on the file.
921    ///
922    /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
923    /// (via another handle/descriptor).
924    ///
925    /// This acquires an exclusive lock; no other file handle to this file, in this or any other
926    /// process, may acquire another lock.
927    ///
928    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
929    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
930    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
931    /// cause non-lockholders to block.
932    ///
933    /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
934    /// is unspecified and platform dependent, including the possibility that it will deadlock.
935    /// However, if this method returns `Ok(())`, then it has acquired an exclusive lock.
936    ///
937    /// If the file is not open for writing, it is unspecified whether this function returns an error.
938    ///
939    /// The lock will be released when this file (along with any other file descriptors/handles
940    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
941    ///
942    /// # Platform-specific behavior
943    ///
944    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
945    /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
946    /// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
947    /// [may change in the future][changes].
948    ///
949    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
950    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
951    ///
952    /// [changes]: io#platform-specific-behavior
953    ///
954    /// [`lock`]: File::lock
955    /// [`lock_shared`]: File::lock_shared
956    /// [`try_lock`]: File::try_lock
957    /// [`try_lock_shared`]: File::try_lock_shared
958    /// [`unlock`]: File::unlock
959    /// [`read`]: Read::read
960    /// [`write`]: Write::write
961    ///
962    /// # Examples
963    ///
964    /// ```no_run
965    /// use std::fs::{File, TryLockError};
966    ///
967    /// fn main() -> std::io::Result<()> {
968    ///     let f = File::create("foo.txt")?;
969    ///     // Explicit handling of the WouldBlock error
970    ///     match f.try_lock() {
971    ///         Ok(_) => (),
972    ///         Err(TryLockError::WouldBlock) => (), // Lock not acquired
973    ///         Err(TryLockError::Error(err)) => return Err(err),
974    ///     }
975    ///     // Alternately, propagate the error as an io::Error
976    ///     f.try_lock()?;
977    ///     Ok(())
978    /// }
979    /// ```
980    #[stable(feature = "file_lock", since = "1.89.0")]
981    pub fn try_lock(&self) -> Result<(), TryLockError> {
982        self.inner.try_lock()
983    }
984
985    /// Try to acquire a shared (non-exclusive) lock on the file.
986    ///
987    /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
988    /// (via another handle/descriptor).
989    ///
990    /// This acquires a shared lock; more than one file handle, in this or any other process, may
991    /// hold a shared lock, but none may hold an exclusive lock at the same time.
992    ///
993    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
994    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
995    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
996    /// cause non-lockholders to block.
997    ///
998    /// If this file handle, or a clone of it, already holds a lock, the exact behavior is
999    /// unspecified and platform dependent, including the possibility that it will deadlock.
1000    /// However, if this method returns `Ok(())`, then it has acquired a shared lock.
1001    ///
1002    /// The lock will be released when this file (along with any other file descriptors/handles
1003    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
1004    ///
1005    /// # Platform-specific behavior
1006    ///
1007    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
1008    /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
1009    /// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
1010    /// [may change in the future][changes].
1011    ///
1012    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
1013    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
1014    ///
1015    /// [changes]: io#platform-specific-behavior
1016    ///
1017    /// [`lock`]: File::lock
1018    /// [`lock_shared`]: File::lock_shared
1019    /// [`try_lock`]: File::try_lock
1020    /// [`try_lock_shared`]: File::try_lock_shared
1021    /// [`unlock`]: File::unlock
1022    /// [`read`]: Read::read
1023    /// [`write`]: Write::write
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```no_run
1028    /// use std::fs::{File, TryLockError};
1029    ///
1030    /// fn main() -> std::io::Result<()> {
1031    ///     let f = File::open("foo.txt")?;
1032    ///     // Explicit handling of the WouldBlock error
1033    ///     match f.try_lock_shared() {
1034    ///         Ok(_) => (),
1035    ///         Err(TryLockError::WouldBlock) => (), // Lock not acquired
1036    ///         Err(TryLockError::Error(err)) => return Err(err),
1037    ///     }
1038    ///     // Alternately, propagate the error as an io::Error
1039    ///     f.try_lock_shared()?;
1040    ///
1041    ///     Ok(())
1042    /// }
1043    /// ```
1044    #[stable(feature = "file_lock", since = "1.89.0")]
1045    pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1046        self.inner.try_lock_shared()
1047    }
1048
1049    /// Release all locks on the file.
1050    ///
1051    /// All locks are released when the file (along with any other file descriptors/handles
1052    /// duplicated or inherited from it) is closed. This method allows releasing locks without
1053    /// closing the file.
1054    ///
1055    /// If no lock is currently held via this file descriptor/handle, this method may return an
1056    /// error, or may return successfully without taking any action.
1057    ///
1058    /// # Platform-specific behavior
1059    ///
1060    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
1061    /// and the `UnlockFile` function on Windows. Note that, this
1062    /// [may change in the future][changes].
1063    ///
1064    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
1065    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
1066    ///
1067    /// [changes]: io#platform-specific-behavior
1068    ///
1069    /// # Examples
1070    ///
1071    /// ```no_run
1072    /// use std::fs::File;
1073    ///
1074    /// fn main() -> std::io::Result<()> {
1075    ///     let f = File::open("foo.txt")?;
1076    ///     f.lock()?;
1077    ///     f.unlock()?;
1078    ///     Ok(())
1079    /// }
1080    /// ```
1081    #[stable(feature = "file_lock", since = "1.89.0")]
1082    pub fn unlock(&self) -> io::Result<()> {
1083        self.inner.unlock()
1084    }
1085
1086    /// Truncates or extends the underlying file, updating the size of
1087    /// this file to become `size`.
1088    ///
1089    /// If the `size` is less than the current file's size, then the file will
1090    /// be shrunk. If it is greater than the current file's size, then the file
1091    /// will be extended to `size` and have all of the intermediate data filled
1092    /// in with 0s.
1093    ///
1094    /// The file's cursor isn't changed. In particular, if the cursor was at the
1095    /// end and the file is shrunk using this operation, the cursor will now be
1096    /// past the end.
1097    ///
1098    /// # Errors
1099    ///
1100    /// This function will return an error if the file is not opened for writing.
1101    /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
1102    /// will be returned if the desired length would cause an overflow due to
1103    /// the implementation specifics.
1104    ///
1105    /// # Examples
1106    ///
1107    /// ```no_run
1108    /// use std::fs::File;
1109    ///
1110    /// fn main() -> std::io::Result<()> {
1111    ///     let mut f = File::create("foo.txt")?;
1112    ///     f.set_len(10)?;
1113    ///     Ok(())
1114    /// }
1115    /// ```
1116    ///
1117    /// Note that this method alters the content of the underlying file, even
1118    /// though it takes `&self` rather than `&mut self`.
1119    #[stable(feature = "rust1", since = "1.0.0")]
1120    pub fn set_len(&self, size: u64) -> io::Result<()> {
1121        self.inner.truncate(size)
1122    }
1123
1124    /// Queries metadata about the underlying file.
1125    ///
1126    /// # Examples
1127    ///
1128    /// ```no_run
1129    /// use std::fs::File;
1130    ///
1131    /// fn main() -> std::io::Result<()> {
1132    ///     let mut f = File::open("foo.txt")?;
1133    ///     let metadata = f.metadata()?;
1134    ///     Ok(())
1135    /// }
1136    /// ```
1137    #[stable(feature = "rust1", since = "1.0.0")]
1138    pub fn metadata(&self) -> io::Result<Metadata> {
1139        self.inner.file_attr().map(Metadata)
1140    }
1141
1142    /// Creates a new `File` instance that shares the same underlying file handle
1143    /// as the existing `File` instance. Reads, writes, and seeks will affect
1144    /// both `File` instances simultaneously.
1145    ///
1146    /// # Examples
1147    ///
1148    /// Creates two handles for a file named `foo.txt`:
1149    ///
1150    /// ```no_run
1151    /// use std::fs::File;
1152    ///
1153    /// fn main() -> std::io::Result<()> {
1154    ///     let mut file = File::open("foo.txt")?;
1155    ///     let file_copy = file.try_clone()?;
1156    ///     Ok(())
1157    /// }
1158    /// ```
1159    ///
1160    /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
1161    /// two handles, seek one of them, and read the remaining bytes from the
1162    /// other handle:
1163    ///
1164    /// ```no_run
1165    /// use std::fs::File;
1166    /// use std::io::SeekFrom;
1167    /// use std::io::prelude::*;
1168    ///
1169    /// fn main() -> std::io::Result<()> {
1170    ///     let mut file = File::open("foo.txt")?;
1171    ///     let mut file_copy = file.try_clone()?;
1172    ///
1173    ///     file.seek(SeekFrom::Start(3))?;
1174    ///
1175    ///     let mut contents = vec![];
1176    ///     file_copy.read_to_end(&mut contents)?;
1177    ///     assert_eq!(contents, b"def\n");
1178    ///     Ok(())
1179    /// }
1180    /// ```
1181    #[stable(feature = "file_try_clone", since = "1.9.0")]
1182    pub fn try_clone(&self) -> io::Result<File> {
1183        Ok(File { inner: self.inner.duplicate()? })
1184    }
1185
1186    /// Changes the permissions on the underlying file.
1187    ///
1188    /// # Platform-specific behavior
1189    ///
1190    /// This function currently corresponds to the `fchmod` function on Unix and
1191    /// the `SetFileInformationByHandle` function on Windows. Note that, this
1192    /// [may change in the future][changes].
1193    ///
1194    /// [changes]: io#platform-specific-behavior
1195    ///
1196    /// # Errors
1197    ///
1198    /// This function will return an error if the user lacks permission change
1199    /// attributes on the underlying file. It may also return an error in other
1200    /// os-specific unspecified cases.
1201    ///
1202    /// # Examples
1203    ///
1204    /// ```no_run
1205    /// fn main() -> std::io::Result<()> {
1206    ///     use std::fs::File;
1207    ///
1208    ///     let file = File::open("foo.txt")?;
1209    ///     let mut perms = file.metadata()?.permissions();
1210    ///     perms.set_readonly(true);
1211    ///     file.set_permissions(perms)?;
1212    ///     Ok(())
1213    /// }
1214    /// ```
1215    ///
1216    /// Note that this method alters the permissions of the underlying file,
1217    /// even though it takes `&self` rather than `&mut self`.
1218    #[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
1219    #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
1220    pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
1221        self.inner.set_permissions(perm.0)
1222    }
1223
1224    /// Changes the timestamps of the underlying file.
1225    ///
1226    /// # Platform-specific behavior
1227    ///
1228    /// This function currently corresponds to the `futimens` function on Unix (falling back to
1229    /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
1230    /// [may change in the future][changes].
1231    ///
1232    /// On most platforms, including UNIX and Windows platforms, this function can also change the
1233    /// timestamps of a directory. To get a `File` representing a directory in order to call
1234    /// `set_times`, open the directory with `File::open` without attempting to obtain write
1235    /// permission.
1236    ///
1237    /// [changes]: io#platform-specific-behavior
1238    ///
1239    /// # Errors
1240    ///
1241    /// This function will return an error if the user lacks permission to change timestamps on the
1242    /// underlying file. It may also return an error in other os-specific unspecified cases.
1243    ///
1244    /// This function may return an error if the operating system lacks support to change one or
1245    /// more of the timestamps set in the `FileTimes` structure.
1246    ///
1247    /// # Examples
1248    ///
1249    /// ```no_run
1250    /// fn main() -> std::io::Result<()> {
1251    ///     use std::fs::{self, File, FileTimes};
1252    ///
1253    ///     let src = fs::metadata("src")?;
1254    ///     let dest = File::open("dest")?;
1255    ///     let times = FileTimes::new()
1256    ///         .set_accessed(src.accessed()?)
1257    ///         .set_modified(src.modified()?);
1258    ///     dest.set_times(times)?;
1259    ///     Ok(())
1260    /// }
1261    /// ```
1262    #[stable(feature = "file_set_times", since = "1.75.0")]
1263    #[doc(alias = "futimens")]
1264    #[doc(alias = "futimes")]
1265    #[doc(alias = "SetFileTime")]
1266    #[doc(alias = "filetime")]
1267    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1268        self.inner.set_times(times.0)
1269    }
1270
1271    /// Changes the modification time of the underlying file.
1272    ///
1273    /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
1274    #[stable(feature = "file_set_times", since = "1.75.0")]
1275    #[inline]
1276    pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
1277        self.set_times(FileTimes::new().set_modified(time))
1278    }
1279}
1280
1281// In addition to the `impl`s here, `File` also has `impl`s for
1282// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1283// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1284// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
1285// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
1286
1287impl AsInner<fs_imp::File> for File {
1288    #[inline]
1289    fn as_inner(&self) -> &fs_imp::File {
1290        &self.inner
1291    }
1292}
1293impl FromInner<fs_imp::File> for File {
1294    fn from_inner(f: fs_imp::File) -> File {
1295        File { inner: f }
1296    }
1297}
1298impl IntoInner<fs_imp::File> for File {
1299    fn into_inner(self) -> fs_imp::File {
1300        self.inner
1301    }
1302}
1303
1304#[stable(feature = "rust1", since = "1.0.0")]
1305impl fmt::Debug for File {
1306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307        self.inner.fmt(f)
1308    }
1309}
1310
1311/// Indicates how much extra capacity is needed to read the rest of the file.
1312fn buffer_capacity_required(mut file: &File) -> Option<usize> {
1313    let size = file.metadata().map(|m| m.len()).ok()?;
1314    let pos = file.stream_position().ok()?;
1315    // Don't worry about `usize` overflow because reading will fail regardless
1316    // in that case.
1317    Some(size.saturating_sub(pos) as usize)
1318}
1319
1320#[stable(feature = "rust1", since = "1.0.0")]
1321impl Read for &File {
1322    /// Reads some bytes from the file.
1323    ///
1324    /// See [`Read::read`] docs for more info.
1325    ///
1326    /// # Platform-specific behavior
1327    ///
1328    /// This function currently corresponds to the `read` function on Unix and
1329    /// the `NtReadFile` function on Windows. Note that this [may change in
1330    /// the future][changes].
1331    ///
1332    /// [changes]: io#platform-specific-behavior
1333    #[inline]
1334    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1335        self.inner.read(buf)
1336    }
1337
1338    /// Like `read`, except that it reads into a slice of buffers.
1339    ///
1340    /// See [`Read::read_vectored`] docs for more info.
1341    ///
1342    /// # Platform-specific behavior
1343    ///
1344    /// This function currently corresponds to the `readv` function on Unix and
1345    /// falls back to the `read` implementation on Windows. Note that this
1346    /// [may change in the future][changes].
1347    ///
1348    /// [changes]: io#platform-specific-behavior
1349    #[inline]
1350    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1351        self.inner.read_vectored(bufs)
1352    }
1353
1354    #[inline]
1355    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1356        self.inner.read_buf(cursor)
1357    }
1358
1359    /// Determines if `File` has an efficient `read_vectored` implementation.
1360    ///
1361    /// See [`Read::is_read_vectored`] docs for more info.
1362    ///
1363    /// # Platform-specific behavior
1364    ///
1365    /// This function currently returns `true` on Unix and `false` on Windows.
1366    /// Note that this [may change in the future][changes].
1367    ///
1368    /// [changes]: io#platform-specific-behavior
1369    #[inline]
1370    fn is_read_vectored(&self) -> bool {
1371        self.inner.is_read_vectored()
1372    }
1373
1374    // Reserves space in the buffer based on the file size when available.
1375    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1376        let size = buffer_capacity_required(self);
1377        buf.try_reserve(size.unwrap_or(0))?;
1378        io::default_read_to_end(self, buf, size)
1379    }
1380
1381    // Reserves space in the buffer based on the file size when available.
1382    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1383        let size = buffer_capacity_required(self);
1384        buf.try_reserve(size.unwrap_or(0))?;
1385        io::default_read_to_string(self, buf, size)
1386    }
1387}
1388#[stable(feature = "rust1", since = "1.0.0")]
1389impl Write for &File {
1390    /// Writes some bytes to the file.
1391    ///
1392    /// See [`Write::write`] docs for more info.
1393    ///
1394    /// # Platform-specific behavior
1395    ///
1396    /// This function currently corresponds to the `write` function on Unix and
1397    /// the `NtWriteFile` function on Windows. Note that this [may change in
1398    /// the future][changes].
1399    ///
1400    /// [changes]: io#platform-specific-behavior
1401    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1402        self.inner.write(buf)
1403    }
1404
1405    /// Like `write`, except that it writes into a slice of buffers.
1406    ///
1407    /// See [`Write::write_vectored`] docs for more info.
1408    ///
1409    /// # Platform-specific behavior
1410    ///
1411    /// This function currently corresponds to the `writev` function on Unix
1412    /// and falls back to the `write` implementation on Windows. Note that this
1413    /// [may change in the future][changes].
1414    ///
1415    /// [changes]: io#platform-specific-behavior
1416    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1417        self.inner.write_vectored(bufs)
1418    }
1419
1420    /// Determines if `File` has an efficient `write_vectored` implementation.
1421    ///
1422    /// See [`Write::is_write_vectored`] docs for more info.
1423    ///
1424    /// # Platform-specific behavior
1425    ///
1426    /// This function currently returns `true` on Unix and `false` on Windows.
1427    /// Note that this [may change in the future][changes].
1428    ///
1429    /// [changes]: io#platform-specific-behavior
1430    #[inline]
1431    fn is_write_vectored(&self) -> bool {
1432        self.inner.is_write_vectored()
1433    }
1434
1435    /// Flushes the file, ensuring that all intermediately buffered contents
1436    /// reach their destination.
1437    ///
1438    /// See [`Write::flush`] docs for more info.
1439    ///
1440    /// # Platform-specific behavior
1441    ///
1442    /// Since a `File` structure doesn't contain any buffers, this function is
1443    /// currently a no-op on Unix and Windows. Note that this [may change in
1444    /// the future][changes].
1445    ///
1446    /// [changes]: io#platform-specific-behavior
1447    #[inline]
1448    fn flush(&mut self) -> io::Result<()> {
1449        self.inner.flush()
1450    }
1451}
1452#[stable(feature = "rust1", since = "1.0.0")]
1453impl Seek for &File {
1454    /// Seek to an offset, in bytes in a file.
1455    ///
1456    /// See [`Seek::seek`] docs for more info.
1457    ///
1458    /// # Platform-specific behavior
1459    ///
1460    /// This function currently corresponds to the `lseek64` function on Unix
1461    /// and the `SetFilePointerEx` function on Windows. Note that this [may
1462    /// change in the future][changes].
1463    ///
1464    /// [changes]: io#platform-specific-behavior
1465    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1466        self.inner.seek(pos)
1467    }
1468
1469    /// Returns the length of this file (in bytes).
1470    ///
1471    /// See [`Seek::stream_len`] docs for more info.
1472    ///
1473    /// # Platform-specific behavior
1474    ///
1475    /// This function currently corresponds to the `statx` function on Linux
1476    /// (with fallbacks) and the `GetFileSizeEx` function on Windows. Note that
1477    /// this [may change in the future][changes].
1478    ///
1479    /// [changes]: io#platform-specific-behavior
1480    fn stream_len(&mut self) -> io::Result<u64> {
1481        if let Some(result) = self.inner.size() {
1482            return result;
1483        }
1484        io::stream_len_default(self)
1485    }
1486
1487    fn stream_position(&mut self) -> io::Result<u64> {
1488        self.inner.tell()
1489    }
1490}
1491
1492#[stable(feature = "rust1", since = "1.0.0")]
1493impl Read for File {
1494    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1495        (&*self).read(buf)
1496    }
1497    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1498        (&*self).read_vectored(bufs)
1499    }
1500    fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1501        (&*self).read_buf(cursor)
1502    }
1503    #[inline]
1504    fn is_read_vectored(&self) -> bool {
1505        (&&*self).is_read_vectored()
1506    }
1507    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1508        (&*self).read_to_end(buf)
1509    }
1510    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1511        (&*self).read_to_string(buf)
1512    }
1513}
1514#[stable(feature = "rust1", since = "1.0.0")]
1515impl Write for File {
1516    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1517        (&*self).write(buf)
1518    }
1519    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1520        (&*self).write_vectored(bufs)
1521    }
1522    #[inline]
1523    fn is_write_vectored(&self) -> bool {
1524        (&&*self).is_write_vectored()
1525    }
1526    #[inline]
1527    fn flush(&mut self) -> io::Result<()> {
1528        (&*self).flush()
1529    }
1530}
1531#[stable(feature = "rust1", since = "1.0.0")]
1532impl Seek for File {
1533    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1534        (&*self).seek(pos)
1535    }
1536    fn stream_len(&mut self) -> io::Result<u64> {
1537        (&*self).stream_len()
1538    }
1539    fn stream_position(&mut self) -> io::Result<u64> {
1540        (&*self).stream_position()
1541    }
1542}
1543#[doc(hidden)]
1544#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
1545impl crate::io::IoHandle for File {}
1546
1547impl Dir {
1548    /// Attempts to open a directory at `path` in read-only mode.
1549    ///
1550    /// # Errors
1551    ///
1552    /// This function will return an error if `path` does not point to an existing directory.
1553    /// Other errors may also be returned according to [`OpenOptions::open`].
1554    ///
1555    /// # Examples
1556    ///
1557    /// ```no_run
1558    /// #![feature(dirfd)]
1559    /// use std::{fs::Dir, io};
1560    ///
1561    /// fn main() -> std::io::Result<()> {
1562    ///     let dir = Dir::open("foo")?;
1563    ///     let mut f = dir.open_file("bar.txt")?;
1564    ///     let contents = io::read_to_string(f)?;
1565    ///     assert_eq!(contents, "Hello, world!");
1566    ///     Ok(())
1567    /// }
1568    /// ```
1569    #[unstable(feature = "dirfd", issue = "120426")]
1570    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1571        fs_imp::Dir::open(path.as_ref(), &OpenOptions::new().read(true).0)
1572            .map(|inner| Self { inner })
1573    }
1574
1575    /// Attempts to open a file in read-only mode relative to this directory.
1576    ///
1577    /// # Errors
1578    ///
1579    /// This function will return an error if `path` does not point to an existing file.
1580    /// Other errors may also be returned according to [`OpenOptions::open`].
1581    ///
1582    /// # Examples
1583    ///
1584    /// ```no_run
1585    /// #![feature(dirfd)]
1586    /// use std::{fs::Dir, io};
1587    ///
1588    /// fn main() -> std::io::Result<()> {
1589    ///     let dir = Dir::open("foo")?;
1590    ///     let mut f = dir.open_file("bar.txt")?;
1591    ///     let contents = io::read_to_string(f)?;
1592    ///     assert_eq!(contents, "Hello, world!");
1593    ///     Ok(())
1594    /// }
1595    /// ```
1596    #[unstable(feature = "dirfd", issue = "120426")]
1597    pub fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1598        self.inner
1599            .open_file(path.as_ref(), &OpenOptions::new().read(true).0)
1600            .map(|f| File { inner: f })
1601    }
1602
1603    /// Queries metadata about the underlying directory.
1604    ///
1605    /// # Examples
1606    ///
1607    /// ```no_run
1608    /// #![feature(dirfd)]
1609    /// use std::fs::Dir;
1610    ///
1611    /// fn main() -> std::io::Result<()> {
1612    ///     let dir = Dir::open("foo")?;
1613    ///     let metadata = dir.metadata()?;
1614    ///     Ok(())
1615    /// }
1616    /// ```
1617    #[unstable(feature = "dirfd", issue = "120426")]
1618    pub fn metadata(&self) -> io::Result<Metadata> {
1619        self.inner.metadata().map(Metadata)
1620    }
1621}
1622
1623impl AsInner<fs_imp::Dir> for Dir {
1624    #[inline]
1625    fn as_inner(&self) -> &fs_imp::Dir {
1626        &self.inner
1627    }
1628}
1629impl FromInner<fs_imp::Dir> for Dir {
1630    fn from_inner(f: fs_imp::Dir) -> Dir {
1631        Dir { inner: f }
1632    }
1633}
1634impl IntoInner<fs_imp::Dir> for Dir {
1635    fn into_inner(self) -> fs_imp::Dir {
1636        self.inner
1637    }
1638}
1639
1640#[unstable(feature = "dirfd", issue = "120426")]
1641impl fmt::Debug for Dir {
1642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1643        self.inner.fmt(f)
1644    }
1645}
1646
1647impl OpenOptions {
1648    /// Creates a blank new set of options ready for configuration.
1649    ///
1650    /// All options are initially set to `false`.
1651    ///
1652    /// # Examples
1653    ///
1654    /// ```no_run
1655    /// use std::fs::OpenOptions;
1656    ///
1657    /// let mut options = OpenOptions::new();
1658    /// let file = options.read(true).open("foo.txt");
1659    /// ```
1660    #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
1661    #[stable(feature = "rust1", since = "1.0.0")]
1662    #[must_use]
1663    pub fn new() -> Self {
1664        OpenOptions(fs_imp::OpenOptions::new())
1665    }
1666
1667    /// Sets the option for read access.
1668    ///
1669    /// This option, when true, will indicate that the file should be
1670    /// `read`-able if opened.
1671    ///
1672    /// # Examples
1673    ///
1674    /// ```no_run
1675    /// use std::fs::OpenOptions;
1676    ///
1677    /// let file = OpenOptions::new().read(true).open("foo.txt");
1678    /// ```
1679    #[stable(feature = "rust1", since = "1.0.0")]
1680    pub fn read(&mut self, read: bool) -> &mut Self {
1681        self.0.read(read);
1682        self
1683    }
1684
1685    /// Sets the option for write access.
1686    ///
1687    /// This option, when true, will indicate that the file should be
1688    /// `write`-able if opened.
1689    ///
1690    /// If the file already exists, any write calls on it will overwrite its
1691    /// contents, without truncating it.
1692    ///
1693    /// # Examples
1694    ///
1695    /// ```no_run
1696    /// use std::fs::OpenOptions;
1697    ///
1698    /// let file = OpenOptions::new().write(true).open("foo.txt");
1699    /// ```
1700    #[stable(feature = "rust1", since = "1.0.0")]
1701    pub fn write(&mut self, write: bool) -> &mut Self {
1702        self.0.write(write);
1703        self
1704    }
1705
1706    /// Sets the option for the append mode.
1707    ///
1708    /// This option, when true, means that writes will append to a file instead
1709    /// of overwriting previous contents.
1710    /// Note that setting `.write(true).append(true)` has the same effect as
1711    /// setting only `.append(true)`.
1712    ///
1713    /// Append mode guarantees that writes will be positioned at the current end of file,
1714    /// even when there are other processes or threads appending to the same file. This is
1715    /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
1716    /// has a race between seeking and writing during which another writer can write, with
1717    /// our `write()` overwriting their data.
1718    ///
1719    /// Keep in mind that this does not necessarily guarantee that data appended by
1720    /// different processes or threads does not interleave. The amount of data accepted a
1721    /// single `write()` call depends on the operating system and file system. A
1722    /// successful `write()` is allowed to write only part of the given data, so even if
1723    /// you're careful to provide the whole message in a single call to `write()`, there
1724    /// is no guarantee that it will be written out in full. If you rely on the filesystem
1725    /// accepting the message in a single write, make sure that all data that belongs
1726    /// together is written in one operation. This can be done by concatenating strings
1727    /// before passing them to [`write()`].
1728    ///
1729    /// If a file is opened with both read and append access, beware that after
1730    /// opening, and after every write, the position for reading may be set at the
1731    /// end of the file. So, before writing, save the current position (using
1732    /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
1733    ///
1734    /// ## Note
1735    ///
1736    /// This function doesn't create the file if it doesn't exist. Use the
1737    /// [`OpenOptions::create`] method to do so.
1738    ///
1739    /// [`write()`]: Write::write "io::Write::write"
1740    /// [`flush()`]: Write::flush "io::Write::flush"
1741    /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
1742    /// [seek]: Seek::seek "io::Seek::seek"
1743    /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
1744    /// [End]: SeekFrom::End "io::SeekFrom::End"
1745    ///
1746    /// # Examples
1747    ///
1748    /// ```no_run
1749    /// use std::fs::OpenOptions;
1750    ///
1751    /// let file = OpenOptions::new().append(true).open("foo.txt");
1752    /// ```
1753    #[stable(feature = "rust1", since = "1.0.0")]
1754    pub fn append(&mut self, append: bool) -> &mut Self {
1755        self.0.append(append);
1756        self
1757    }
1758
1759    /// Sets the option for truncating a previous file.
1760    ///
1761    /// If a file is successfully opened with this option set to true, it will truncate
1762    /// the file to 0 length if it already exists.
1763    ///
1764    /// The file must be opened with write access for truncate to work.
1765    ///
1766    /// # Examples
1767    ///
1768    /// ```no_run
1769    /// use std::fs::OpenOptions;
1770    ///
1771    /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
1772    /// ```
1773    #[stable(feature = "rust1", since = "1.0.0")]
1774    pub fn truncate(&mut self, truncate: bool) -> &mut Self {
1775        self.0.truncate(truncate);
1776        self
1777    }
1778
1779    /// Sets the option to create a new file, or open it if it already exists.
1780    ///
1781    /// In order for the file to be created, [`OpenOptions::write`] or
1782    /// [`OpenOptions::append`] access must be used.
1783    ///
1784    /// See also [`std::fs::write()`][self::write] for a simple function to
1785    /// create a file with some given data.
1786    ///
1787    /// # Errors
1788    ///
1789    /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
1790    /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
1791    /// # Examples
1792    ///
1793    /// ```no_run
1794    /// use std::fs::OpenOptions;
1795    ///
1796    /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
1797    /// ```
1798    #[stable(feature = "rust1", since = "1.0.0")]
1799    pub fn create(&mut self, create: bool) -> &mut Self {
1800        self.0.create(create);
1801        self
1802    }
1803
1804    /// Sets the option to create a new file, failing if it already exists.
1805    ///
1806    /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1807    /// way, if the call succeeds, the file returned is guaranteed to be new.
1808    /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
1809    /// or another error based on the situation. See [`OpenOptions::open`] for a
1810    /// non-exhaustive list of likely errors.
1811    ///
1812    /// This option is useful because it is atomic. Otherwise between checking
1813    /// whether a file exists and creating a new one, the file may have been
1814    /// created by another process (a [TOCTOU] race condition / attack).
1815    ///
1816    /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1817    /// ignored.
1818    ///
1819    /// The file must be opened with write or append access in order to create
1820    /// a new file.
1821    ///
1822    /// [`.create()`]: OpenOptions::create
1823    /// [`.truncate()`]: OpenOptions::truncate
1824    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1825    /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
1826    ///
1827    /// # Examples
1828    ///
1829    /// ```no_run
1830    /// use std::fs::OpenOptions;
1831    ///
1832    /// let file = OpenOptions::new().write(true)
1833    ///                              .create_new(true)
1834    ///                              .open("foo.txt");
1835    /// ```
1836    #[stable(feature = "expand_open_options2", since = "1.9.0")]
1837    pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1838        self.0.create_new(create_new);
1839        self
1840    }
1841
1842    /// Opens a file at `path` with the options specified by `self`.
1843    ///
1844    /// # Errors
1845    ///
1846    /// This function will return an error under a number of different
1847    /// circumstances. Some of these error conditions are listed here, together
1848    /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1849    /// part of the compatibility contract of the function.
1850    ///
1851    /// * [`NotFound`]: The specified file does not exist and neither `create`
1852    ///   or `create_new` is set.
1853    /// * [`NotFound`]: One of the directory components of the file path does
1854    ///   not exist.
1855    /// * [`PermissionDenied`]: The user lacks permission to get the specified
1856    ///   access rights for the file.
1857    /// * [`PermissionDenied`]: The user lacks permission to open one of the
1858    ///   directory components of the specified path.
1859    /// * [`AlreadyExists`]: `create_new` was specified and the file already
1860    ///   exists.
1861    /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1862    ///   without write access, create without write or append access,
1863    ///   no access mode set, etc.).
1864    ///
1865    /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1866    /// * One of the directory components of the specified file path
1867    ///   was not, in fact, a directory.
1868    /// * Filesystem-level errors: full disk, write permission
1869    ///   requested on a read-only file system, exceeded disk quota, too many
1870    ///   open files, too long filename, too many symbolic links in the
1871    ///   specified path (Unix-like systems only), etc.
1872    ///
1873    /// # Examples
1874    ///
1875    /// ```no_run
1876    /// use std::fs::OpenOptions;
1877    ///
1878    /// let file = OpenOptions::new().read(true).open("foo.txt");
1879    /// ```
1880    ///
1881    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1882    /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1883    /// [`NotFound`]: io::ErrorKind::NotFound
1884    /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1885    #[stable(feature = "rust1", since = "1.0.0")]
1886    pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1887        self._open(path.as_ref())
1888    }
1889
1890    fn _open(&self, path: &Path) -> io::Result<File> {
1891        fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1892    }
1893}
1894
1895impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1896    #[inline]
1897    fn as_inner(&self) -> &fs_imp::OpenOptions {
1898        &self.0
1899    }
1900}
1901
1902impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1903    #[inline]
1904    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1905        &mut self.0
1906    }
1907}
1908
1909impl Metadata {
1910    /// Returns the file type for this metadata.
1911    ///
1912    /// # Examples
1913    ///
1914    /// ```no_run
1915    /// fn main() -> std::io::Result<()> {
1916    ///     use std::fs;
1917    ///
1918    ///     let metadata = fs::metadata("foo.txt")?;
1919    ///
1920    ///     println!("{:?}", metadata.file_type());
1921    ///     Ok(())
1922    /// }
1923    /// ```
1924    #[must_use]
1925    #[stable(feature = "file_type", since = "1.1.0")]
1926    pub fn file_type(&self) -> FileType {
1927        FileType(self.0.file_type())
1928    }
1929
1930    /// Returns `true` if this metadata is for a directory. The
1931    /// result is mutually exclusive to the result of
1932    /// [`Metadata::is_file`], and will be false for symlink metadata
1933    /// obtained from [`symlink_metadata`].
1934    ///
1935    /// # Examples
1936    ///
1937    /// ```no_run
1938    /// fn main() -> std::io::Result<()> {
1939    ///     use std::fs;
1940    ///
1941    ///     let metadata = fs::metadata("foo.txt")?;
1942    ///
1943    ///     assert!(!metadata.is_dir());
1944    ///     Ok(())
1945    /// }
1946    /// ```
1947    #[must_use]
1948    #[stable(feature = "rust1", since = "1.0.0")]
1949    pub fn is_dir(&self) -> bool {
1950        self.file_type().is_dir()
1951    }
1952
1953    /// Returns `true` if this metadata is for a regular file. The
1954    /// result is mutually exclusive to the result of
1955    /// [`Metadata::is_dir`], and will be false for symlink metadata
1956    /// obtained from [`symlink_metadata`].
1957    ///
1958    /// When the goal is simply to read from (or write to) the source, the most
1959    /// reliable way to test the source can be read (or written to) is to open
1960    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1961    /// a Unix-like system for example. See [`File::open`] or
1962    /// [`OpenOptions::open`] for more information.
1963    ///
1964    /// # Examples
1965    ///
1966    /// ```no_run
1967    /// use std::fs;
1968    ///
1969    /// fn main() -> std::io::Result<()> {
1970    ///     let metadata = fs::metadata("foo.txt")?;
1971    ///
1972    ///     assert!(metadata.is_file());
1973    ///     Ok(())
1974    /// }
1975    /// ```
1976    #[must_use]
1977    #[stable(feature = "rust1", since = "1.0.0")]
1978    pub fn is_file(&self) -> bool {
1979        self.file_type().is_file()
1980    }
1981
1982    /// Returns `true` if this metadata is for a symbolic link.
1983    ///
1984    /// # Examples
1985    ///
1986    #[cfg_attr(unix, doc = "```no_run")]
1987    #[cfg_attr(not(unix), doc = "```ignore")]
1988    /// use std::fs;
1989    /// use std::path::Path;
1990    /// use std::os::unix::fs::symlink;
1991    ///
1992    /// fn main() -> std::io::Result<()> {
1993    ///     let link_path = Path::new("link");
1994    ///     symlink("/origin_does_not_exist/", link_path)?;
1995    ///
1996    ///     let metadata = fs::symlink_metadata(link_path)?;
1997    ///
1998    ///     assert!(metadata.is_symlink());
1999    ///     Ok(())
2000    /// }
2001    /// ```
2002    #[must_use]
2003    #[stable(feature = "is_symlink", since = "1.58.0")]
2004    pub fn is_symlink(&self) -> bool {
2005        self.file_type().is_symlink()
2006    }
2007
2008    /// Returns the size of the file, in bytes, this metadata is for.
2009    ///
2010    /// # Examples
2011    ///
2012    /// ```no_run
2013    /// use std::fs;
2014    ///
2015    /// fn main() -> std::io::Result<()> {
2016    ///     let metadata = fs::metadata("foo.txt")?;
2017    ///
2018    ///     assert_eq!(0, metadata.len());
2019    ///     Ok(())
2020    /// }
2021    /// ```
2022    #[must_use]
2023    #[stable(feature = "rust1", since = "1.0.0")]
2024    pub fn len(&self) -> u64 {
2025        self.0.size()
2026    }
2027
2028    /// Returns the permissions of the file this metadata is for.
2029    ///
2030    /// # Examples
2031    ///
2032    /// ```no_run
2033    /// use std::fs;
2034    ///
2035    /// fn main() -> std::io::Result<()> {
2036    ///     let metadata = fs::metadata("foo.txt")?;
2037    ///
2038    ///     assert!(!metadata.permissions().readonly());
2039    ///     Ok(())
2040    /// }
2041    /// ```
2042    #[must_use]
2043    #[stable(feature = "rust1", since = "1.0.0")]
2044    pub fn permissions(&self) -> Permissions {
2045        Permissions(self.0.perm())
2046    }
2047
2048    /// Returns the last modification time listed in this metadata.
2049    ///
2050    /// The returned value corresponds to the `mtime` field of `stat` on Unix
2051    /// platforms and the `ftLastWriteTime` field on Windows platforms.
2052    ///
2053    /// # Errors
2054    ///
2055    /// This field might not be available on all platforms, and will return an
2056    /// `Err` on platforms where it is not available.
2057    ///
2058    /// # Examples
2059    ///
2060    /// ```no_run
2061    /// use std::fs;
2062    ///
2063    /// fn main() -> std::io::Result<()> {
2064    ///     let metadata = fs::metadata("foo.txt")?;
2065    ///
2066    ///     if let Ok(time) = metadata.modified() {
2067    ///         println!("{time:?}");
2068    ///     } else {
2069    ///         println!("Not supported on this platform");
2070    ///     }
2071    ///     Ok(())
2072    /// }
2073    /// ```
2074    #[doc(alias = "mtime", alias = "ftLastWriteTime")]
2075    #[stable(feature = "fs_time", since = "1.10.0")]
2076    pub fn modified(&self) -> io::Result<SystemTime> {
2077        self.0.modified().map(FromInner::from_inner)
2078    }
2079
2080    /// Returns the last access time of this metadata.
2081    ///
2082    /// The returned value corresponds to the `atime` field of `stat` on Unix
2083    /// platforms and the `ftLastAccessTime` field on Windows platforms.
2084    ///
2085    /// Note that not all platforms will keep this field update in a file's
2086    /// metadata, for example Windows has an option to disable updating this
2087    /// time when files are accessed and Linux similarly has `noatime`.
2088    ///
2089    /// # Errors
2090    ///
2091    /// This field might not be available on all platforms, and will return an
2092    /// `Err` on platforms where it is not available.
2093    ///
2094    /// # Examples
2095    ///
2096    /// ```no_run
2097    /// use std::fs;
2098    ///
2099    /// fn main() -> std::io::Result<()> {
2100    ///     let metadata = fs::metadata("foo.txt")?;
2101    ///
2102    ///     if let Ok(time) = metadata.accessed() {
2103    ///         println!("{time:?}");
2104    ///     } else {
2105    ///         println!("Not supported on this platform");
2106    ///     }
2107    ///     Ok(())
2108    /// }
2109    /// ```
2110    #[doc(alias = "atime", alias = "ftLastAccessTime")]
2111    #[stable(feature = "fs_time", since = "1.10.0")]
2112    pub fn accessed(&self) -> io::Result<SystemTime> {
2113        self.0.accessed().map(FromInner::from_inner)
2114    }
2115
2116    /// Returns the creation time listed in this metadata.
2117    ///
2118    /// The returned value corresponds to the `btime` field of `statx` on
2119    /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
2120    /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
2121    ///
2122    /// # Errors
2123    ///
2124    /// This field might not be available on all platforms, and will return an
2125    /// `Err` on platforms or filesystems where it is not available.
2126    ///
2127    /// # Examples
2128    ///
2129    /// ```no_run
2130    /// use std::fs;
2131    ///
2132    /// fn main() -> std::io::Result<()> {
2133    ///     let metadata = fs::metadata("foo.txt")?;
2134    ///
2135    ///     if let Ok(time) = metadata.created() {
2136    ///         println!("{time:?}");
2137    ///     } else {
2138    ///         println!("Not supported on this platform or filesystem");
2139    ///     }
2140    ///     Ok(())
2141    /// }
2142    /// ```
2143    #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
2144    #[stable(feature = "fs_time", since = "1.10.0")]
2145    pub fn created(&self) -> io::Result<SystemTime> {
2146        self.0.created().map(FromInner::from_inner)
2147    }
2148}
2149
2150#[stable(feature = "std_debug", since = "1.16.0")]
2151impl fmt::Debug for Metadata {
2152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2153        let mut debug = f.debug_struct("Metadata");
2154        debug.field("file_type", &self.file_type());
2155        debug.field("permissions", &self.permissions());
2156        debug.field("len", &self.len());
2157        if let Ok(modified) = self.modified() {
2158            debug.field("modified", &modified);
2159        }
2160        if let Ok(accessed) = self.accessed() {
2161            debug.field("accessed", &accessed);
2162        }
2163        if let Ok(created) = self.created() {
2164            debug.field("created", &created);
2165        }
2166        debug.finish_non_exhaustive()
2167    }
2168}
2169
2170impl IntoInner<fs_imp::FileAttr> for Metadata {
2171    fn into_inner(self) -> fs_imp::FileAttr {
2172        self.0
2173    }
2174}
2175
2176impl AsInner<fs_imp::FileAttr> for Metadata {
2177    #[inline]
2178    fn as_inner(&self) -> &fs_imp::FileAttr {
2179        &self.0
2180    }
2181}
2182
2183impl FromInner<fs_imp::FileAttr> for Metadata {
2184    fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2185        Metadata(attr)
2186    }
2187}
2188
2189impl FileTimes {
2190    /// Creates a new `FileTimes` with no times set.
2191    ///
2192    /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2193    #[stable(feature = "file_set_times", since = "1.75.0")]
2194    pub fn new() -> Self {
2195        Self::default()
2196    }
2197
2198    /// Set the last access time of a file.
2199    #[stable(feature = "file_set_times", since = "1.75.0")]
2200    pub fn set_accessed(mut self, t: SystemTime) -> Self {
2201        self.0.set_accessed(t.into_inner());
2202        self
2203    }
2204
2205    /// Set the last modified time of a file.
2206    #[stable(feature = "file_set_times", since = "1.75.0")]
2207    pub fn set_modified(mut self, t: SystemTime) -> Self {
2208        self.0.set_modified(t.into_inner());
2209        self
2210    }
2211}
2212
2213impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2214    fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2215        &mut self.0
2216    }
2217}
2218
2219impl Permissions {
2220    /// Returns `true` if these permissions describe a readonly (unwritable) file.
2221    ///
2222    /// # Note
2223    ///
2224    /// This function does not take Access Control Lists (ACLs), Unix group
2225    /// membership and other nuances into account.
2226    /// Therefore the return value of this function cannot be relied upon
2227    /// to predict whether attempts to read or write the file will actually succeed.
2228    ///
2229    /// # Windows
2230    ///
2231    /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2232    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2233    /// but the user may still have permission to change this flag. If
2234    /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2235    /// to lack of write permission.
2236    /// The behavior of this attribute for directories depends on the Windows
2237    /// version.
2238    ///
2239    /// # Unix (including macOS)
2240    ///
2241    /// On Unix-based platforms this checks if *any* of the owner, group or others
2242    /// write permission bits are set. It does not consider anything else, including:
2243    ///
2244    /// * Whether the current user is in the file's assigned group.
2245    /// * Permissions granted by ACL.
2246    /// * That `root` user can write to files that do not have any write bits set.
2247    /// * Writable files on a filesystem that is mounted read-only.
2248    ///
2249    /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2250    /// also does not read ACLs.
2251    ///
2252    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2253    ///
2254    /// # Examples
2255    ///
2256    /// ```no_run
2257    /// use std::fs::File;
2258    ///
2259    /// fn main() -> std::io::Result<()> {
2260    ///     let mut f = File::create("foo.txt")?;
2261    ///     let metadata = f.metadata()?;
2262    ///
2263    ///     assert_eq!(false, metadata.permissions().readonly());
2264    ///     Ok(())
2265    /// }
2266    /// ```
2267    #[must_use = "call `set_readonly` to modify the readonly flag"]
2268    #[stable(feature = "rust1", since = "1.0.0")]
2269    pub fn readonly(&self) -> bool {
2270        self.0.readonly()
2271    }
2272
2273    /// Modifies the readonly flag for this set of permissions. If the
2274    /// `readonly` argument is `true`, using the resulting `Permission` will
2275    /// update file permissions to forbid writing. Conversely, if it's `false`,
2276    /// using the resulting `Permission` will update file permissions to allow
2277    /// writing.
2278    ///
2279    /// This operation does **not** modify the files attributes. This only
2280    /// changes the in-memory value of these attributes for this `Permissions`
2281    /// instance. To modify the files attributes use the [`set_permissions`]
2282    /// function which commits these attribute changes to the file.
2283    ///
2284    /// # Note
2285    ///
2286    /// `set_readonly(false)` makes the file *world-writable* on Unix.
2287    /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2288    ///
2289    /// It also does not take Access Control Lists (ACLs) or Unix group
2290    /// membership into account.
2291    ///
2292    /// # Windows
2293    ///
2294    /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2295    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2296    /// but the user may still have permission to change this flag. If
2297    /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2298    /// the user does not have permission to write to the file.
2299    ///
2300    /// In Windows 7 and earlier this attribute prevents deleting empty
2301    /// directories. It does not prevent modifying the directory contents.
2302    /// On later versions of Windows this attribute is ignored for directories.
2303    ///
2304    /// # Unix (including macOS)
2305    ///
2306    /// On Unix-based platforms this sets or clears the write access bit for
2307    /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2308    /// or `chmod a-w <file>` respectively. The latter will grant write access
2309    /// to all users! You can use the [`PermissionsExt`] trait on Unix
2310    /// to avoid this issue.
2311    ///
2312    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2313    ///
2314    /// # Examples
2315    ///
2316    /// ```no_run
2317    /// use std::fs::File;
2318    ///
2319    /// fn main() -> std::io::Result<()> {
2320    ///     let f = File::create("foo.txt")?;
2321    ///     let metadata = f.metadata()?;
2322    ///     let mut permissions = metadata.permissions();
2323    ///
2324    ///     permissions.set_readonly(true);
2325    ///
2326    ///     // filesystem doesn't change, only the in memory state of the
2327    ///     // readonly permission
2328    ///     assert_eq!(false, metadata.permissions().readonly());
2329    ///
2330    ///     // just this particular `permissions`.
2331    ///     assert_eq!(true, permissions.readonly());
2332    ///     Ok(())
2333    /// }
2334    /// ```
2335    #[stable(feature = "rust1", since = "1.0.0")]
2336    pub fn set_readonly(&mut self, readonly: bool) {
2337        self.0.set_readonly(readonly)
2338    }
2339}
2340
2341impl FileType {
2342    /// Tests whether this file type represents a directory. The
2343    /// result is mutually exclusive to the results of
2344    /// [`is_file`] and [`is_symlink`]; only zero or one of these
2345    /// tests may pass.
2346    ///
2347    /// [`is_file`]: FileType::is_file
2348    /// [`is_symlink`]: FileType::is_symlink
2349    ///
2350    /// # Examples
2351    ///
2352    /// ```no_run
2353    /// fn main() -> std::io::Result<()> {
2354    ///     use std::fs;
2355    ///
2356    ///     let metadata = fs::metadata("foo.txt")?;
2357    ///     let file_type = metadata.file_type();
2358    ///
2359    ///     assert_eq!(file_type.is_dir(), false);
2360    ///     Ok(())
2361    /// }
2362    /// ```
2363    #[must_use]
2364    #[stable(feature = "file_type", since = "1.1.0")]
2365    pub fn is_dir(&self) -> bool {
2366        self.0.is_dir()
2367    }
2368
2369    /// Tests whether this file type represents a regular file.
2370    /// The result is mutually exclusive to the results of
2371    /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2372    /// tests may pass.
2373    ///
2374    /// When the goal is simply to read from (or write to) the source, the most
2375    /// reliable way to test the source can be read (or written to) is to open
2376    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2377    /// a Unix-like system for example. See [`File::open`] or
2378    /// [`OpenOptions::open`] for more information.
2379    ///
2380    /// [`is_dir`]: FileType::is_dir
2381    /// [`is_symlink`]: FileType::is_symlink
2382    ///
2383    /// # Examples
2384    ///
2385    /// ```no_run
2386    /// fn main() -> std::io::Result<()> {
2387    ///     use std::fs;
2388    ///
2389    ///     let metadata = fs::metadata("foo.txt")?;
2390    ///     let file_type = metadata.file_type();
2391    ///
2392    ///     assert_eq!(file_type.is_file(), true);
2393    ///     Ok(())
2394    /// }
2395    /// ```
2396    #[must_use]
2397    #[stable(feature = "file_type", since = "1.1.0")]
2398    pub fn is_file(&self) -> bool {
2399        self.0.is_file()
2400    }
2401
2402    /// Tests whether this file type represents a symbolic link.
2403    /// The result is mutually exclusive to the results of
2404    /// [`is_dir`] and [`is_file`]; only zero or one of these
2405    /// tests may pass.
2406    ///
2407    /// The underlying [`Metadata`] struct needs to be retrieved
2408    /// with the [`fs::symlink_metadata`] function and not the
2409    /// [`fs::metadata`] function. The [`fs::metadata`] function
2410    /// follows symbolic links, so [`is_symlink`] would always
2411    /// return `false` for the target file.
2412    ///
2413    /// [`fs::metadata`]: metadata
2414    /// [`fs::symlink_metadata`]: symlink_metadata
2415    /// [`is_dir`]: FileType::is_dir
2416    /// [`is_file`]: FileType::is_file
2417    /// [`is_symlink`]: FileType::is_symlink
2418    ///
2419    /// # Examples
2420    ///
2421    /// ```no_run
2422    /// use std::fs;
2423    ///
2424    /// fn main() -> std::io::Result<()> {
2425    ///     let metadata = fs::symlink_metadata("foo.txt")?;
2426    ///     let file_type = metadata.file_type();
2427    ///
2428    ///     assert_eq!(file_type.is_symlink(), false);
2429    ///     Ok(())
2430    /// }
2431    /// ```
2432    #[must_use]
2433    #[stable(feature = "file_type", since = "1.1.0")]
2434    pub fn is_symlink(&self) -> bool {
2435        self.0.is_symlink()
2436    }
2437}
2438
2439#[stable(feature = "std_debug", since = "1.16.0")]
2440impl fmt::Debug for FileType {
2441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2442        f.debug_struct("FileType")
2443            .field("is_file", &self.is_file())
2444            .field("is_dir", &self.is_dir())
2445            .field("is_symlink", &self.is_symlink())
2446            .finish_non_exhaustive()
2447    }
2448}
2449
2450impl AsInner<fs_imp::FileType> for FileType {
2451    #[inline]
2452    fn as_inner(&self) -> &fs_imp::FileType {
2453        &self.0
2454    }
2455}
2456
2457impl FromInner<fs_imp::FilePermissions> for Permissions {
2458    fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2459        Permissions(f)
2460    }
2461}
2462
2463impl AsInner<fs_imp::FilePermissions> for Permissions {
2464    #[inline]
2465    fn as_inner(&self) -> &fs_imp::FilePermissions {
2466        &self.0
2467    }
2468}
2469
2470#[stable(feature = "rust1", since = "1.0.0")]
2471impl Iterator for ReadDir {
2472    type Item = io::Result<DirEntry>;
2473
2474    fn next(&mut self) -> Option<io::Result<DirEntry>> {
2475        self.0.next().map(|entry| entry.map(DirEntry))
2476    }
2477}
2478
2479impl DirEntry {
2480    /// Returns the full path to the file that this entry represents.
2481    ///
2482    /// The full path is created by joining the original path to `read_dir`
2483    /// with the filename of this entry.
2484    ///
2485    /// # Examples
2486    ///
2487    /// ```no_run
2488    /// use std::fs;
2489    ///
2490    /// fn main() -> std::io::Result<()> {
2491    ///     for entry in fs::read_dir(".")? {
2492    ///         let dir = entry?;
2493    ///         println!("{:?}", dir.path());
2494    ///     }
2495    ///     Ok(())
2496    /// }
2497    /// ```
2498    ///
2499    /// This prints output like:
2500    ///
2501    /// ```text
2502    /// "./whatever.txt"
2503    /// "./foo.html"
2504    /// "./hello_world.rs"
2505    /// ```
2506    ///
2507    /// The exact text, of course, depends on what files you have in `.`.
2508    #[must_use]
2509    #[stable(feature = "rust1", since = "1.0.0")]
2510    pub fn path(&self) -> PathBuf {
2511        self.0.path()
2512    }
2513
2514    /// Returns the metadata for the file that this entry points at.
2515    ///
2516    /// This function will not traverse symlinks if this entry points at a
2517    /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2518    ///
2519    /// [`fs::metadata`]: metadata
2520    /// [`fs::File::metadata`]: File::metadata
2521    ///
2522    /// # Platform-specific behavior
2523    ///
2524    /// On Windows this function is cheap to call (no extra system calls
2525    /// needed), but on Unix platforms this function is the equivalent of
2526    /// calling `symlink_metadata` on the path.
2527    ///
2528    /// # Examples
2529    ///
2530    /// ```
2531    /// use std::fs;
2532    ///
2533    /// if let Ok(entries) = fs::read_dir(".") {
2534    ///     for entry in entries {
2535    ///         if let Ok(entry) = entry {
2536    ///             // Here, `entry` is a `DirEntry`.
2537    ///             if let Ok(metadata) = entry.metadata() {
2538    ///                 // Now let's show our entry's permissions!
2539    ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
2540    ///             } else {
2541    ///                 println!("Couldn't get metadata for {:?}", entry.path());
2542    ///             }
2543    ///         }
2544    ///     }
2545    /// }
2546    /// ```
2547    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2548    pub fn metadata(&self) -> io::Result<Metadata> {
2549        self.0.metadata().map(Metadata)
2550    }
2551
2552    /// Returns the file type for the file that this entry points at.
2553    ///
2554    /// This function will not traverse symlinks if this entry points at a
2555    /// symlink.
2556    ///
2557    /// # Platform-specific behavior
2558    ///
2559    /// On Windows and most Unix platforms this function is free (no extra
2560    /// system calls needed), but some Unix platforms may require the equivalent
2561    /// call to `symlink_metadata` to learn about the target file type.
2562    ///
2563    /// # Examples
2564    ///
2565    /// ```
2566    /// use std::fs;
2567    ///
2568    /// if let Ok(entries) = fs::read_dir(".") {
2569    ///     for entry in entries {
2570    ///         if let Ok(entry) = entry {
2571    ///             // Here, `entry` is a `DirEntry`.
2572    ///             if let Ok(file_type) = entry.file_type() {
2573    ///                 // Now let's show our entry's file type!
2574    ///                 println!("{:?}: {:?}", entry.path(), file_type);
2575    ///             } else {
2576    ///                 println!("Couldn't get file type for {:?}", entry.path());
2577    ///             }
2578    ///         }
2579    ///     }
2580    /// }
2581    /// ```
2582    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2583    pub fn file_type(&self) -> io::Result<FileType> {
2584        self.0.file_type().map(FileType)
2585    }
2586
2587    /// Returns the file name of this directory entry without any
2588    /// leading path component(s).
2589    ///
2590    /// As an example,
2591    /// the output of the function will result in "foo" for all the following paths:
2592    /// - "./foo"
2593    /// - "/the/foo"
2594    /// - "../../foo"
2595    ///
2596    /// # Examples
2597    ///
2598    /// ```
2599    /// use std::fs;
2600    ///
2601    /// if let Ok(entries) = fs::read_dir(".") {
2602    ///     for entry in entries {
2603    ///         if let Ok(entry) = entry {
2604    ///             // Here, `entry` is a `DirEntry`.
2605    ///             println!("{:?}", entry.file_name());
2606    ///         }
2607    ///     }
2608    /// }
2609    /// ```
2610    #[must_use]
2611    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2612    pub fn file_name(&self) -> OsString {
2613        self.0.file_name()
2614    }
2615}
2616
2617#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2618impl fmt::Debug for DirEntry {
2619    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2620        f.debug_tuple("DirEntry").field(&self.path()).finish()
2621    }
2622}
2623
2624impl AsInner<fs_imp::DirEntry> for DirEntry {
2625    #[inline]
2626    fn as_inner(&self) -> &fs_imp::DirEntry {
2627        &self.0
2628    }
2629}
2630
2631/// Removes a file from the filesystem.
2632///
2633/// Note that there is no
2634/// guarantee that the file is immediately deleted (e.g., depending on
2635/// platform, other open file descriptors may prevent immediate removal).
2636///
2637/// # Platform-specific behavior
2638///
2639/// This function currently corresponds to the `unlink` function on Unix.
2640/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2641/// Note that, this [may change in the future][changes].
2642///
2643/// [changes]: io#platform-specific-behavior
2644///
2645/// # Errors
2646///
2647/// This function will return an error in the following situations, but is not
2648/// limited to just these cases:
2649///
2650/// * `path` points to a directory.
2651/// * The file doesn't exist.
2652/// * The user lacks permissions to remove the file.
2653///
2654/// This function will only ever return an error of kind `NotFound` if the given
2655/// path does not exist. Note that the inverse is not true,
2656/// i.e. if a path does not exist, its removal may fail for a number of reasons,
2657/// such as insufficient permissions.
2658///
2659/// # Examples
2660///
2661/// ```no_run
2662/// use std::fs;
2663///
2664/// fn main() -> std::io::Result<()> {
2665///     fs::remove_file("a.txt")?;
2666///     Ok(())
2667/// }
2668/// ```
2669#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
2670#[stable(feature = "rust1", since = "1.0.0")]
2671pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
2672    fs_imp::remove_file(path.as_ref())
2673}
2674
2675/// Given a path, queries the file system to get information about a file,
2676/// directory, etc.
2677///
2678/// This function will traverse symbolic links to query information about the
2679/// destination file.
2680///
2681/// # Platform-specific behavior
2682///
2683/// This function currently corresponds to the `stat` function on Unix
2684/// and the `GetFileInformationByHandle` function on Windows.
2685/// Note that, this [may change in the future][changes].
2686///
2687/// [changes]: io#platform-specific-behavior
2688///
2689/// # Errors
2690///
2691/// This function will return an error in the following situations, but is not
2692/// limited to just these cases:
2693///
2694/// * The user lacks permissions to perform `metadata` call on `path`.
2695/// * `path` does not exist.
2696///
2697/// # Examples
2698///
2699/// ```rust,no_run
2700/// use std::fs;
2701///
2702/// fn main() -> std::io::Result<()> {
2703///     let attr = fs::metadata("/some/file/path.txt")?;
2704///     // inspect attr ...
2705///     Ok(())
2706/// }
2707/// ```
2708#[doc(alias = "stat")]
2709#[stable(feature = "rust1", since = "1.0.0")]
2710pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2711    fs_imp::metadata(path.as_ref()).map(Metadata)
2712}
2713
2714/// Queries the metadata about a file without following symlinks.
2715///
2716/// # Platform-specific behavior
2717///
2718/// This function currently corresponds to the `lstat` function on Unix
2719/// and the `GetFileInformationByHandle` function on Windows.
2720/// Note that, this [may change in the future][changes].
2721///
2722/// [changes]: io#platform-specific-behavior
2723///
2724/// # Errors
2725///
2726/// This function will return an error in the following situations, but is not
2727/// limited to just these cases:
2728///
2729/// * The user lacks permissions to perform `metadata` call on `path`.
2730/// * `path` does not exist.
2731///
2732/// # Examples
2733///
2734/// ```rust,no_run
2735/// use std::fs;
2736///
2737/// fn main() -> std::io::Result<()> {
2738///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
2739///     // inspect attr ...
2740///     Ok(())
2741/// }
2742/// ```
2743#[doc(alias = "lstat")]
2744#[stable(feature = "symlink_metadata", since = "1.1.0")]
2745pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2746    fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
2747}
2748
2749/// Renames a file or directory to a new name, replacing the original file if
2750/// `to` already exists.
2751///
2752/// This will not work if the new name is on a different mount point.
2753///
2754/// # Platform-specific behavior
2755///
2756/// This function currently corresponds to the [rename] function on Unix, and
2757/// `MoveFileExW` with a fallback to `SetFileInformationByHandle` on Windows.
2758/// The exact behavior differs:
2759///
2760/// - If `to` does not exist, `from` can be anything.
2761/// - On Unix, when `from` is a directory and `to` exists, `to` must be an empty directory.
2762/// - On Unix, when `from` is not a directory and `to` exists, `to` may not be a directory.
2763/// - On Windows 10 version 1607 and above, the behavior is the same as Unix if the
2764///   filesystem supports  `FileRenameInfoEx`.
2765/// - Otherwise on Windows, `from` can be anything but `to` must not be a directory.
2766///
2767/// Note that, this [may change in the future][changes].
2768///
2769/// [changes]: io#platform-specific-behavior
2770/// [rename]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/rename.html
2771///
2772/// # Errors
2773///
2774/// This function will return an error in the following situations, but is not
2775/// limited to just these cases:
2776///
2777/// * `from` does not exist.
2778/// * The user lacks permissions to view contents.
2779/// * `from` and `to` are on separate filesystems.
2780///
2781/// # Examples
2782///
2783/// ```no_run
2784/// use std::fs;
2785///
2786/// fn main() -> std::io::Result<()> {
2787///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
2788///     Ok(())
2789/// }
2790/// ```
2791#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
2792#[stable(feature = "rust1", since = "1.0.0")]
2793pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
2794    fs_imp::rename(from.as_ref(), to.as_ref())
2795}
2796
2797/// Copies the contents of one file to another. This function will also
2798/// copy the permission bits of the original file to the destination file.
2799///
2800/// This function will **overwrite** the contents of `to`.
2801///
2802/// Note that if `from` and `to` both point to the same file, then the file
2803/// will likely get truncated by this operation.
2804///
2805/// On success, the total number of bytes copied is returned and it is equal to
2806/// the length of the `to` file as reported by `metadata`.
2807///
2808/// If you want to copy the contents of one file to another and you’re
2809/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
2810///
2811/// # Platform-specific behavior
2812///
2813/// This function currently corresponds to the `open` function in Unix
2814/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
2815/// `O_CLOEXEC` is set for returned file descriptors.
2816///
2817/// On Linux (including Android), this function uses copy_file_range(2),
2818/// sendfile(2), or splice(2) syscalls to move data directly between files
2819/// if possible.
2820///
2821/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
2822/// NTFS streams are copied but only the size of the main stream is returned by
2823/// this function.
2824///
2825/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
2826///
2827/// Note that platform-specific behavior [may change in the future][changes].
2828///
2829/// [changes]: io#platform-specific-behavior
2830///
2831/// # Errors
2832///
2833/// This function will return an error in the following situations, but is not
2834/// limited to just these cases:
2835///
2836/// * `from` is neither a regular file nor a symlink to a regular file.
2837/// * `from` does not exist.
2838/// * The current process does not have the permission rights to read
2839///   `from` or write `to`.
2840/// * The parent directory of `to` doesn't exist.
2841///
2842/// # Examples
2843///
2844/// ```no_run
2845/// use std::fs;
2846///
2847/// fn main() -> std::io::Result<()> {
2848///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
2849///     Ok(())
2850/// }
2851/// ```
2852#[doc(alias = "cp")]
2853#[doc(alias = "CopyFile", alias = "CopyFileEx")]
2854#[doc(alias = "fclonefileat", alias = "fcopyfile")]
2855#[stable(feature = "rust1", since = "1.0.0")]
2856pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
2857    fs_imp::copy(from.as_ref(), to.as_ref())
2858}
2859
2860/// Creates a new hard link on the filesystem.
2861///
2862/// The `link` path will be a link pointing to the `original` path. Note that
2863/// systems often require these two paths to both be located on the same
2864/// filesystem.
2865///
2866/// If `original` names a symbolic link, it is platform-specific whether the
2867/// symbolic link is followed. On platforms where it's possible to not follow
2868/// it, it is not followed, and the created hard link points to the symbolic
2869/// link itself.
2870///
2871/// # Platform-specific behavior
2872///
2873/// This function currently corresponds to the `CreateHardLink` function on Windows.
2874/// On most Unix systems, it corresponds to the `linkat` function with no flags.
2875/// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2876/// On MacOS, it uses the `linkat` function if it is available, but on very old
2877/// systems where `linkat` is not available, `link` is selected at runtime instead.
2878/// Note that, this [may change in the future][changes].
2879///
2880/// [changes]: io#platform-specific-behavior
2881///
2882/// # Errors
2883///
2884/// This function will return an error in the following situations, but is not
2885/// limited to just these cases:
2886///
2887/// * The `original` path is not a file or doesn't exist.
2888/// * The 'link' path already exists.
2889///
2890/// # Examples
2891///
2892/// ```no_run
2893/// use std::fs;
2894///
2895/// fn main() -> std::io::Result<()> {
2896///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2897///     Ok(())
2898/// }
2899/// ```
2900#[doc(alias = "CreateHardLink", alias = "linkat")]
2901#[stable(feature = "rust1", since = "1.0.0")]
2902pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2903    fs_imp::hard_link(original.as_ref(), link.as_ref())
2904}
2905
2906/// Creates a new symbolic link on the filesystem.
2907///
2908/// The `link` path will be a symbolic link pointing to the `original` path.
2909/// On Windows, this will be a file symlink, not a directory symlink;
2910/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2911/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2912/// used instead to make the intent explicit.
2913///
2914/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2915/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2916/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2917///
2918/// # Examples
2919///
2920/// ```no_run
2921/// use std::fs;
2922///
2923/// fn main() -> std::io::Result<()> {
2924///     fs::soft_link("a.txt", "b.txt")?;
2925///     Ok(())
2926/// }
2927/// ```
2928#[stable(feature = "rust1", since = "1.0.0")]
2929#[deprecated(
2930    since = "1.1.0",
2931    note = "replaced with std::os::unix::fs::symlink and \
2932            std::os::windows::fs::{symlink_file, symlink_dir}"
2933)]
2934pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2935    fs_imp::symlink(original.as_ref(), link.as_ref())
2936}
2937
2938/// Reads a symbolic link, returning the file that the link points to.
2939///
2940/// # Platform-specific behavior
2941///
2942/// This function currently corresponds to the `readlink` function on Unix
2943/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2944/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2945/// Note that, this [may change in the future][changes].
2946///
2947/// [changes]: io#platform-specific-behavior
2948///
2949/// # Errors
2950///
2951/// This function will return an error in the following situations, but is not
2952/// limited to just these cases:
2953///
2954/// * `path` is not a symbolic link.
2955/// * `path` does not exist.
2956///
2957/// # Examples
2958///
2959/// ```no_run
2960/// use std::fs;
2961///
2962/// fn main() -> std::io::Result<()> {
2963///     let path = fs::read_link("a.txt")?;
2964///     Ok(())
2965/// }
2966/// ```
2967#[stable(feature = "rust1", since = "1.0.0")]
2968pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2969    fs_imp::read_link(path.as_ref())
2970}
2971
2972/// Returns the canonical, absolute form of a path with all intermediate
2973/// components normalized and symbolic links resolved.
2974///
2975/// # Platform-specific behavior
2976///
2977/// This function currently corresponds to the `realpath` function on Unix
2978/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2979/// Note that this [may change in the future][changes].
2980///
2981/// On Windows, this converts the path to use [extended length path][path]
2982/// syntax, which allows your program to use longer path names, but means you
2983/// can only join backslash-delimited paths to it, and it may be incompatible
2984/// with other applications (if passed to the application on the command-line,
2985/// or written to a file another application may read).
2986///
2987/// [changes]: io#platform-specific-behavior
2988/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2989///
2990/// # Errors
2991///
2992/// This function will return an error in the following situations, but is not
2993/// limited to just these cases:
2994///
2995/// * `path` does not exist.
2996/// * A non-final component in path is not a directory.
2997///
2998/// # Examples
2999///
3000/// ```no_run
3001/// use std::fs;
3002///
3003/// fn main() -> std::io::Result<()> {
3004///     let path = fs::canonicalize("../a/../foo.txt")?;
3005///     Ok(())
3006/// }
3007/// ```
3008#[doc(alias = "realpath")]
3009#[doc(alias = "GetFinalPathNameByHandle")]
3010#[stable(feature = "fs_canonicalize", since = "1.5.0")]
3011pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
3012    fs_imp::canonicalize(path.as_ref())
3013}
3014
3015/// Creates a new, empty directory at the provided path.
3016///
3017/// # Platform-specific behavior
3018///
3019/// This function currently corresponds to the `mkdir` function on Unix
3020/// and the `CreateDirectoryW` function on Windows.
3021/// Note that, this [may change in the future][changes].
3022///
3023/// [changes]: io#platform-specific-behavior
3024///
3025/// **NOTE**: If a parent of the given path doesn't exist, this function will
3026/// return an error. To create a directory and all its missing parents at the
3027/// same time, use the [`create_dir_all`] function.
3028///
3029/// # Errors
3030///
3031/// This function will return an error in the following situations, but is not
3032/// limited to just these cases:
3033///
3034/// * User lacks permissions to create directory at `path`.
3035/// * A parent of the given path doesn't exist. (To create a directory and all
3036///   its missing parents at the same time, use the [`create_dir_all`]
3037///   function.)
3038/// * `path` already exists.
3039///
3040/// # Examples
3041///
3042/// ```no_run
3043/// use std::fs;
3044///
3045/// fn main() -> std::io::Result<()> {
3046///     fs::create_dir("/some/dir")?;
3047///     Ok(())
3048/// }
3049/// ```
3050#[doc(alias = "mkdir", alias = "CreateDirectory")]
3051#[stable(feature = "rust1", since = "1.0.0")]
3052#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
3053pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3054    DirBuilder::new().create(path.as_ref())
3055}
3056
3057/// Recursively create a directory and all of its parent components if they
3058/// are missing.
3059///
3060/// This function is not atomic. If it returns an error, any parent components it was able to create
3061/// will remain.
3062///
3063/// If the empty path is passed to this function, it always succeeds without
3064/// creating any directories.
3065///
3066/// # Platform-specific behavior
3067///
3068/// This function currently corresponds to multiple calls to the `mkdir`
3069/// function on Unix and the `CreateDirectoryW` function on Windows.
3070///
3071/// Note that, this [may change in the future][changes].
3072///
3073/// [changes]: io#platform-specific-behavior
3074///
3075/// # Errors
3076///
3077/// The function will return an error if any directory specified in path does not exist and
3078/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
3079///
3080/// Notable exception is made for situations where any of the directories
3081/// specified in the `path` could not be created as it was being created concurrently.
3082/// Such cases are considered to be successful. That is, calling `create_dir_all`
3083/// concurrently from multiple threads or processes is guaranteed not to fail
3084/// due to a race condition with itself.
3085///
3086/// [`fs::create_dir`]: create_dir
3087///
3088/// # Examples
3089///
3090/// ```no_run
3091/// use std::fs;
3092///
3093/// fn main() -> std::io::Result<()> {
3094///     fs::create_dir_all("/some/dir")?;
3095///     Ok(())
3096/// }
3097/// ```
3098#[stable(feature = "rust1", since = "1.0.0")]
3099pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3100    DirBuilder::new().recursive(true).create(path.as_ref())
3101}
3102
3103/// Removes an empty directory.
3104///
3105/// If you want to remove a directory that is not empty, as well as all
3106/// of its contents recursively, consider using [`remove_dir_all`]
3107/// instead.
3108///
3109/// # Platform-specific behavior
3110///
3111/// This function currently corresponds to the `rmdir` function on Unix
3112/// and the `RemoveDirectory` function on Windows.
3113/// Note that, this [may change in the future][changes].
3114///
3115/// [changes]: io#platform-specific-behavior
3116///
3117/// # Errors
3118///
3119/// This function will return an error in the following situations, but is not
3120/// limited to just these cases:
3121///
3122/// * `path` doesn't exist.
3123/// * `path` isn't a directory.
3124/// * The user lacks permissions to remove the directory at the provided `path`.
3125/// * The directory isn't empty.
3126///
3127/// This function will only ever return an error of kind `NotFound` if the given
3128/// path does not exist. Note that the inverse is not true,
3129/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3130/// such as insufficient permissions.
3131///
3132/// # Examples
3133///
3134/// ```no_run
3135/// use std::fs;
3136///
3137/// fn main() -> std::io::Result<()> {
3138///     fs::remove_dir("/some/dir")?;
3139///     Ok(())
3140/// }
3141/// ```
3142#[doc(alias = "rmdir", alias = "RemoveDirectory")]
3143#[stable(feature = "rust1", since = "1.0.0")]
3144pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3145    fs_imp::remove_dir(path.as_ref())
3146}
3147
3148/// Removes a directory at this path, after removing all its contents. Use
3149/// carefully!
3150///
3151/// This function does **not** follow symbolic links and it will simply remove the
3152/// symbolic link itself.
3153///
3154/// # Platform-specific behavior
3155///
3156/// These implementation details [may change in the future][changes].
3157///
3158/// - "Unix-like": By default, this function currently corresponds to
3159/// `openat`, `fdopendir`, `unlinkat` and `lstat`
3160/// on Unix-family platforms, except where noted otherwise.
3161/// - "Windows": This function currently corresponds to `CreateFileW`,
3162/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
3163///
3164/// ## Time-of-check to time-of-use (TOCTOU) race conditions
3165/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
3166///
3167/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
3168/// However, on the following platforms, this protection is not provided and the function should
3169/// not be used in security-sensitive contexts:
3170/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
3171///   TOCTOU races, Miri will not do so.
3172/// - **QNX**, **Redox OS**, **VxWorks**: This function does not protect against TOCTOU races, as
3173///   the underlying platform does not implement the required platform support to do so.
3174///
3175/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3176/// [changes]: io#platform-specific-behavior
3177///
3178/// # Errors
3179///
3180/// See [`fs::remove_file`] and [`fs::remove_dir`].
3181///
3182/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3183/// paths, *including* the root `path`. Consequently,
3184///
3185/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3186/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3187///
3188/// Consider ignoring the error if validating the removal is not required for your use case.
3189///
3190/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3191/// written into, which typically indicates some contents were removed but not all.
3192/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3193///
3194/// [`fs::remove_file`]: remove_file
3195/// [`fs::remove_dir`]: remove_dir
3196///
3197/// # Examples
3198///
3199/// ```no_run
3200/// use std::fs;
3201///
3202/// fn main() -> std::io::Result<()> {
3203///     fs::remove_dir_all("/some/dir")?;
3204///     Ok(())
3205/// }
3206/// ```
3207#[stable(feature = "rust1", since = "1.0.0")]
3208pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3209    fs_imp::remove_dir_all(path.as_ref())
3210}
3211
3212/// Returns an iterator over the entries within a directory.
3213///
3214/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3215/// New errors may be encountered after an iterator is initially constructed.
3216/// Entries for the current and parent directories (typically `.` and `..`) are
3217/// skipped.
3218///
3219/// The order in which `read_dir` returns entries can change between calls. If reproducible
3220/// ordering is required, the entries should be explicitly sorted.
3221///
3222/// # Platform-specific behavior
3223///
3224/// This function currently corresponds to the `opendir` function on Unix
3225/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3226/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3227/// Note that, this [may change in the future][changes].
3228///
3229/// [changes]: io#platform-specific-behavior
3230///
3231/// The order in which this iterator returns entries is platform and filesystem
3232/// dependent.
3233///
3234/// # Errors
3235///
3236/// This function will return an error in the following situations, but is not
3237/// limited to just these cases:
3238///
3239/// * The provided `path` doesn't exist.
3240/// * The process lacks permissions to view the contents.
3241/// * The `path` points at a non-directory file.
3242///
3243/// # Examples
3244///
3245/// ```
3246/// use std::io;
3247/// use std::fs::{self, DirEntry};
3248/// use std::path::Path;
3249///
3250/// // one possible implementation of walking a directory only visiting files
3251/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3252///     if dir.is_dir() {
3253///         for entry in fs::read_dir(dir)? {
3254///             let entry = entry?;
3255///             let path = entry.path();
3256///             if path.is_dir() {
3257///                 visit_dirs(&path, cb)?;
3258///             } else {
3259///                 cb(&entry);
3260///             }
3261///         }
3262///     }
3263///     Ok(())
3264/// }
3265/// ```
3266///
3267/// ```rust,no_run
3268/// use std::{fs, io};
3269///
3270/// fn main() -> io::Result<()> {
3271///     let mut entries = fs::read_dir(".")?
3272///         .map(|res| res.map(|e| e.path()))
3273///         .collect::<Result<Vec<_>, io::Error>>()?;
3274///
3275///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3276///     // ordering is required the entries should be explicitly sorted.
3277///
3278///     entries.sort();
3279///
3280///     // The entries have now been sorted by their path.
3281///
3282///     Ok(())
3283/// }
3284/// ```
3285#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3286#[stable(feature = "rust1", since = "1.0.0")]
3287pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3288    fs_imp::read_dir(path.as_ref()).map(ReadDir)
3289}
3290
3291/// Changes the permissions found on a file or a directory.
3292///
3293/// # Platform-specific behavior
3294///
3295/// This function currently corresponds to the `chmod` function on Unix
3296/// and the `SetFileAttributes` function on Windows.
3297/// Note that, this [may change in the future][changes].
3298///
3299/// [changes]: io#platform-specific-behavior
3300///
3301/// ## Symlinks
3302/// On UNIX-like systems, this function will update the permission bits
3303/// of the file pointed to by the symlink.
3304///
3305/// Note that this behavior can lead to privilege escalation vulnerabilities,
3306/// where the ability to create a symlink in one directory allows you to
3307/// cause the permissions of another file or directory to be modified.
3308///
3309/// For this reason, using this function with symlinks should be avoided.
3310/// When possible, permissions should be set at creation time instead.
3311///
3312/// # Rationale
3313/// POSIX does not specify an `lchmod` function,
3314/// and symlinks can be followed regardless of what permission bits are set.
3315///
3316/// # Errors
3317///
3318/// This function will return an error in the following situations, but is not
3319/// limited to just these cases:
3320///
3321/// * `path` does not exist.
3322/// * The user lacks the permission to change attributes of the file.
3323///
3324/// # Examples
3325///
3326/// ```no_run
3327/// use std::fs;
3328///
3329/// fn main() -> std::io::Result<()> {
3330///     let mut perms = fs::metadata("foo.txt")?.permissions();
3331///     perms.set_readonly(true);
3332///     fs::set_permissions("foo.txt", perms)?;
3333///     Ok(())
3334/// }
3335/// ```
3336#[doc(alias = "chmod", alias = "SetFileAttributes")]
3337#[stable(feature = "set_permissions", since = "1.1.0")]
3338pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3339    fs_imp::set_permissions(path.as_ref(), perm.0)
3340}
3341
3342/// Set the permissions of a file, unless it is a symlink.
3343///
3344/// Note that the non-final path elements are allowed to be symlinks.
3345///
3346/// # Platform-specific behavior
3347///
3348/// Currently unimplemented on Windows.
3349///
3350/// On Unix platforms, this results in a [`FilesystemLoop`] error if the last element is a symlink.
3351///
3352/// This behavior may change in the future.
3353///
3354/// [`FilesystemLoop`]: crate::io::ErrorKind::FilesystemLoop
3355#[doc(alias = "chmod", alias = "SetFileAttributes")]
3356#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
3357pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3358    fs_imp::set_permissions_nofollow(path.as_ref(), perm)
3359}
3360
3361impl DirBuilder {
3362    /// Creates a new set of options with default mode/security settings for all
3363    /// platforms and also non-recursive.
3364    ///
3365    /// # Examples
3366    ///
3367    /// ```
3368    /// use std::fs::DirBuilder;
3369    ///
3370    /// let builder = DirBuilder::new();
3371    /// ```
3372    #[stable(feature = "dir_builder", since = "1.6.0")]
3373    #[must_use]
3374    pub fn new() -> DirBuilder {
3375        DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3376    }
3377
3378    /// Indicates that directories should be created recursively, creating all
3379    /// parent directories. Parents that do not exist are created with the same
3380    /// security and permissions settings.
3381    ///
3382    /// This option defaults to `false`.
3383    ///
3384    /// # Examples
3385    ///
3386    /// ```
3387    /// use std::fs::DirBuilder;
3388    ///
3389    /// let mut builder = DirBuilder::new();
3390    /// builder.recursive(true);
3391    /// ```
3392    #[stable(feature = "dir_builder", since = "1.6.0")]
3393    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3394        self.recursive = recursive;
3395        self
3396    }
3397
3398    /// Creates the specified directory with the options configured in this
3399    /// builder.
3400    ///
3401    /// It is considered an error if the directory already exists unless
3402    /// recursive mode is enabled.
3403    ///
3404    /// # Examples
3405    ///
3406    /// ```no_run
3407    /// use std::fs::{self, DirBuilder};
3408    ///
3409    /// let path = "/tmp/foo/bar/baz";
3410    /// DirBuilder::new()
3411    ///     .recursive(true)
3412    ///     .create(path).unwrap();
3413    ///
3414    /// assert!(fs::metadata(path).unwrap().is_dir());
3415    /// ```
3416    #[stable(feature = "dir_builder", since = "1.6.0")]
3417    pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3418        self._create(path.as_ref())
3419    }
3420
3421    fn _create(&self, path: &Path) -> io::Result<()> {
3422        if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3423    }
3424
3425    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3426        // if path's parent is None, it is "/" path, which should
3427        // return Ok immediately
3428        if path == Path::new("") || path.parent() == None {
3429            return Ok(());
3430        }
3431
3432        let ancestors = path.ancestors();
3433        let mut uncreated_dirs = 0;
3434
3435        for ancestor in ancestors {
3436            // for relative paths like "foo/bar", the parent of
3437            // "foo" will be "" which there's no need to invoke
3438            // a mkdir syscall on
3439            if ancestor == Path::new("") || ancestor.parent() == None {
3440                break;
3441            }
3442
3443            match self.inner.mkdir(ancestor) {
3444                Ok(()) => break,
3445                Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
3446                // we check if the err is AlreadyExists for two reasons
3447                //    - in case the path exists as a *file*
3448                //    - and to avoid calls to .is_dir() in case of other errs
3449                //      (i.e. PermissionDenied)
3450                Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
3451                Err(e) => return Err(e),
3452            }
3453        }
3454
3455        // collect only the uncreated directories w/o letting the vec resize
3456        let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
3457        uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
3458
3459        for uncreated_dir in uncreated_dirs_vec.iter().rev() {
3460            if let Err(e) = self.inner.mkdir(uncreated_dir) {
3461                if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
3462                    return Err(e);
3463                }
3464            }
3465        }
3466
3467        Ok(())
3468    }
3469}
3470
3471impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3472    #[inline]
3473    fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3474        &mut self.inner
3475    }
3476}
3477
3478/// Returns `Ok(true)` if the path points at an existing entity.
3479///
3480/// This function will traverse symbolic links to query information about the
3481/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3482///
3483/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3484/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3485/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3486/// permission is denied on one of the parent directories.
3487///
3488/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3489/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3490/// where those bugs are not an issue.
3491///
3492/// # Examples
3493///
3494/// ```no_run
3495/// use std::fs;
3496///
3497/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3498/// assert!(fs::exists("/root/secret_file.txt").is_err());
3499/// ```
3500///
3501/// [`Path::exists`]: crate::path::Path::exists
3502/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3503#[stable(feature = "fs_try_exists", since = "1.81.0")]
3504#[inline]
3505pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
3506    fs_imp::exists(path.as_ref())
3507}