Skip to main content

std/
fs.rs

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