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