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