Skip to main content

std/
fs.rs

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