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