1 //! Filesystem manipulation operations.
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`.
8 #![stable(feature = "rust1", since = "1.0.0")]
9 #![deny(unsafe_op_in_unsafe_fn)]
11 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
14 use crate::ffi::OsString;
16 use crate::io::{self, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write};
17 use crate::path::{Path, PathBuf};
18 use crate::sys::fs as fs_imp;
19 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
20 use crate::time::SystemTime;
22 /// A reference to an open file on the filesystem.
24 /// An instance of a `File` can be read and/or written depending on what options
25 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
26 /// that the file contains internally.
28 /// Files are automatically closed when they go out of scope. Errors detected
29 /// on closing are ignored by the implementation of `Drop`. Use the method
30 /// [`sync_all`] if these errors must be manually handled.
34 /// Creates a new file and write bytes to it (you can also use [`write()`]):
37 /// use std::fs::File;
38 /// use std::io::prelude::*;
40 /// fn main() -> std::io::Result<()> {
41 /// let mut file = File::create("foo.txt")?;
42 /// file.write_all(b"Hello, world!")?;
47 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
50 /// use std::fs::File;
51 /// use std::io::prelude::*;
53 /// fn main() -> std::io::Result<()> {
54 /// let mut file = File::open("foo.txt")?;
55 /// let mut contents = String::new();
56 /// file.read_to_string(&mut contents)?;
57 /// assert_eq!(contents, "Hello, world!");
62 /// It can be more efficient to read the contents of a file with a buffered
63 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
66 /// use std::fs::File;
67 /// use std::io::BufReader;
68 /// use std::io::prelude::*;
70 /// fn main() -> std::io::Result<()> {
71 /// let file = File::open("foo.txt")?;
72 /// let mut buf_reader = BufReader::new(file);
73 /// let mut contents = String::new();
74 /// buf_reader.read_to_string(&mut contents)?;
75 /// assert_eq!(contents, "Hello, world!");
80 /// Note that, although read and write methods require a `&mut File`, because
81 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
82 /// still modify the file, either through methods that take `&File` or by
83 /// retrieving the underlying OS object and modifying the file that way.
84 /// Additionally, many operating systems allow concurrent modification of files
85 /// by different processes. Avoid assuming that holding a `&File` means that the
86 /// file will not change.
88 /// # Platform-specific behavior
90 /// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
91 /// perform synchronous I/O operations. Therefore the underlying file must not
92 /// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
94 /// [`BufReader<R>`]: io::BufReader
95 /// [`sync_all`]: File::sync_all
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
102 /// Metadata information about a file.
104 /// This structure is returned from the [`metadata`] or
105 /// [`symlink_metadata`] function or method and represents known
106 /// metadata about a file such as its permissions, size, modification
108 #[stable(feature = "rust1", since = "1.0.0")]
110 pub struct Metadata(fs_imp::FileAttr);
112 /// Iterator over the entries in a directory.
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
119 /// The order in which this iterator returns entries is platform and filesystem
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
126 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct ReadDir(fs_imp::ReadDir);
130 /// Entries returned by the [`ReadDir`] iterator.
132 /// An instance of `DirEntry` represents an entry inside of a directory on the
133 /// filesystem. Each entry can be inspected via methods to learn about the full
134 /// path or possibly other metadata through per-platform extension traits.
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub struct DirEntry(fs_imp::DirEntry);
138 /// Options and flags which can be used to configure how a file is opened.
140 /// This builder exposes the ability to configure how a [`File`] is opened and
141 /// what operations are permitted on the open file. The [`File::open`] and
142 /// [`File::create`] methods are aliases for commonly used options using this
145 /// Generally speaking, when using `OpenOptions`, you'll first call
146 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
147 /// call [`OpenOptions::open`], passing the path of the file you're trying to
148 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
149 /// can further operate on.
153 /// Opening a file to read:
156 /// use std::fs::OpenOptions;
158 /// let file = OpenOptions::new().read(true).open("foo.txt");
161 /// Opening a file for both reading and writing, as well as creating it if it
165 /// use std::fs::OpenOptions;
167 /// let file = OpenOptions::new()
171 /// .open("foo.txt");
173 #[derive(Clone, Debug)]
174 #[stable(feature = "rust1", since = "1.0.0")]
175 pub struct OpenOptions(fs_imp::OpenOptions);
177 /// Representation of the various permissions on a file.
179 /// This module only currently provides one bit of information,
180 /// [`Permissions::readonly`], which is exposed on all currently supported
181 /// platforms. Unix-specific functionality, such as mode bits, is available
182 /// through the [`PermissionsExt`] trait.
184 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
185 #[derive(Clone, PartialEq, Eq, Debug)]
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub struct Permissions(fs_imp::FilePermissions);
189 /// A structure representing a type of file with accessors for each file type.
190 /// It is returned by [`Metadata::file_type`] method.
191 #[stable(feature = "file_type", since = "1.1.0")]
192 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
193 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
194 pub struct FileType(fs_imp::FileType);
196 /// A builder used to create directories in various manners.
198 /// This builder also supports platform-specific options.
199 #[stable(feature = "dir_builder", since = "1.6.0")]
200 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
202 pub struct DirBuilder {
203 inner: fs_imp::DirBuilder,
207 /// Read the entire contents of a file into a bytes vector.
209 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
210 /// with fewer imports and without an intermediate variable.
212 /// [`read_to_end`]: Read::read_to_end
216 /// This function will return an error if `path` does not already exist.
217 /// Other errors may also be returned according to [`OpenOptions::open`].
219 /// It will also return an error if it encounters while reading an error
220 /// of a kind other than [`io::ErrorKind::Interrupted`].
226 /// use std::net::SocketAddr;
228 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
229 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
233 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
234 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
235 fn inner(path: &Path) -> io::Result<Vec<u8>> {
236 let mut file = File::open(path)?;
237 let mut bytes = Vec::new();
238 file.read_to_end(&mut bytes)?;
244 /// Read the entire contents of a file into a string.
246 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
247 /// with fewer imports and without an intermediate variable.
249 /// [`read_to_string`]: Read::read_to_string
253 /// This function will return an error if `path` does not already exist.
254 /// Other errors may also be returned according to [`OpenOptions::open`].
256 /// It will also return an error if it encounters while reading an error
257 /// of a kind other than [`io::ErrorKind::Interrupted`],
258 /// or if the contents of the file are not valid UTF-8.
264 /// use std::net::SocketAddr;
265 /// use std::error::Error;
267 /// fn main() -> Result<(), Box<dyn Error>> {
268 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
272 #[stable(feature = "fs_read_write", since = "1.26.0")]
273 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
274 fn inner(path: &Path) -> io::Result<String> {
275 let mut file = File::open(path)?;
276 let mut string = String::new();
277 file.read_to_string(&mut string)?;
283 /// Write a slice as the entire contents of a file.
285 /// This function will create a file if it does not exist,
286 /// and will entirely replace its contents if it does.
288 /// This is a convenience function for using [`File::create`] and [`write_all`]
289 /// with fewer imports.
291 /// [`write_all`]: Write::write_all
298 /// fn main() -> std::io::Result<()> {
299 /// fs::write("foo.txt", b"Lorem ipsum")?;
300 /// fs::write("bar.txt", "dolor sit")?;
304 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
305 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
306 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
307 File::create(path)?.write_all(contents)
309 inner(path.as_ref(), contents.as_ref())
313 /// Attempts to open a file in read-only mode.
315 /// See the [`OpenOptions::open`] method for more details.
319 /// This function will return an error if `path` does not already exist.
320 /// Other errors may also be returned according to [`OpenOptions::open`].
325 /// use std::fs::File;
327 /// fn main() -> std::io::Result<()> {
328 /// let mut f = File::open("foo.txt")?;
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
334 OpenOptions::new().read(true).open(path.as_ref())
337 /// Opens a file in write-only mode.
339 /// This function will create a file if it does not exist,
340 /// and will truncate it if it does.
342 /// See the [`OpenOptions::open`] function for more details.
347 /// use std::fs::File;
349 /// fn main() -> std::io::Result<()> {
350 /// let mut f = File::create("foo.txt")?;
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
356 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
359 /// Returns a new OpenOptions object.
361 /// This function returns a new OpenOptions object that you can use to
362 /// open or create a file with specific options if `open()` or `create()`
363 /// are not appropriate.
365 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
366 /// readable code. Instead of
367 /// `OpenOptions::new().append(true).open("example.log")`,
368 /// you can write `File::options().append(true).open("example.log")`. This
369 /// also avoids the need to import `OpenOptions`.
371 /// See the [`OpenOptions::new`] function for more details.
376 /// use std::fs::File;
378 /// fn main() -> std::io::Result<()> {
379 /// let mut f = File::options().append(true).open("example.log")?;
384 #[stable(feature = "with_options", since = "1.58.0")]
385 pub fn options() -> OpenOptions {
389 /// Attempts to sync all OS-internal metadata to disk.
391 /// This function will attempt to ensure that all in-memory data reaches the
392 /// filesystem before returning.
394 /// This can be used to handle errors that would otherwise only be caught
395 /// when the `File` is closed. Dropping a file will ignore errors in
396 /// synchronizing this in-memory data.
401 /// use std::fs::File;
402 /// use std::io::prelude::*;
404 /// fn main() -> std::io::Result<()> {
405 /// let mut f = File::create("foo.txt")?;
406 /// f.write_all(b"Hello, world!")?;
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn sync_all(&self) -> io::Result<()> {
417 /// This function is similar to [`sync_all`], except that it might not
418 /// synchronize file metadata to the filesystem.
420 /// This is intended for use cases that must synchronize content, but don't
421 /// need the metadata on disk. The goal of this method is to reduce disk
424 /// Note that some platforms may simply implement this in terms of
427 /// [`sync_all`]: File::sync_all
432 /// use std::fs::File;
433 /// use std::io::prelude::*;
435 /// fn main() -> std::io::Result<()> {
436 /// let mut f = File::create("foo.txt")?;
437 /// f.write_all(b"Hello, world!")?;
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn sync_data(&self) -> io::Result<()> {
445 self.inner.datasync()
448 /// Truncates or extends the underlying file, updating the size of
449 /// this file to become `size`.
451 /// If the `size` is less than the current file's size, then the file will
452 /// be shrunk. If it is greater than the current file's size, then the file
453 /// will be extended to `size` and have all of the intermediate data filled
456 /// The file's cursor isn't changed. In particular, if the cursor was at the
457 /// end and the file is shrunk using this operation, the cursor will now be
462 /// This function will return an error if the file is not opened for writing.
463 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
464 /// length would cause an overflow due to the implementation specifics.
469 /// use std::fs::File;
471 /// fn main() -> std::io::Result<()> {
472 /// let mut f = File::create("foo.txt")?;
478 /// Note that this method alters the content of the underlying file, even
479 /// though it takes `&self` rather than `&mut self`.
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn set_len(&self, size: u64) -> io::Result<()> {
482 self.inner.truncate(size)
485 /// Queries metadata about the underlying file.
490 /// use std::fs::File;
492 /// fn main() -> std::io::Result<()> {
493 /// let mut f = File::open("foo.txt")?;
494 /// let metadata = f.metadata()?;
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn metadata(&self) -> io::Result<Metadata> {
500 self.inner.file_attr().map(Metadata)
503 /// Creates a new `File` instance that shares the same underlying file handle
504 /// as the existing `File` instance. Reads, writes, and seeks will affect
505 /// both `File` instances simultaneously.
509 /// Creates two handles for a file named `foo.txt`:
512 /// use std::fs::File;
514 /// fn main() -> std::io::Result<()> {
515 /// let mut file = File::open("foo.txt")?;
516 /// let file_copy = file.try_clone()?;
521 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
522 /// two handles, seek one of them, and read the remaining bytes from the
526 /// use std::fs::File;
527 /// use std::io::SeekFrom;
528 /// use std::io::prelude::*;
530 /// fn main() -> std::io::Result<()> {
531 /// let mut file = File::open("foo.txt")?;
532 /// let mut file_copy = file.try_clone()?;
534 /// file.seek(SeekFrom::Start(3))?;
536 /// let mut contents = vec![];
537 /// file_copy.read_to_end(&mut contents)?;
538 /// assert_eq!(contents, b"def\n");
542 #[stable(feature = "file_try_clone", since = "1.9.0")]
543 pub fn try_clone(&self) -> io::Result<File> {
544 Ok(File { inner: self.inner.duplicate()? })
547 /// Changes the permissions on the underlying file.
549 /// # Platform-specific behavior
551 /// This function currently corresponds to the `fchmod` function on Unix and
552 /// the `SetFileInformationByHandle` function on Windows. Note that, this
553 /// [may change in the future][changes].
555 /// [changes]: io#platform-specific-behavior
559 /// This function will return an error if the user lacks permission change
560 /// attributes on the underlying file. It may also return an error in other
561 /// os-specific unspecified cases.
566 /// fn main() -> std::io::Result<()> {
567 /// use std::fs::File;
569 /// let file = File::open("foo.txt")?;
570 /// let mut perms = file.metadata()?.permissions();
571 /// perms.set_readonly(true);
572 /// file.set_permissions(perms)?;
577 /// Note that this method alters the permissions of the underlying file,
578 /// even though it takes `&self` rather than `&mut self`.
579 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
580 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
581 self.inner.set_permissions(perm.0)
585 // In addition to the `impl`s here, `File` also has `impl`s for
586 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
587 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
588 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
589 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
591 impl AsInner<fs_imp::File> for File {
592 fn as_inner(&self) -> &fs_imp::File {
596 impl FromInner<fs_imp::File> for File {
597 fn from_inner(f: fs_imp::File) -> File {
601 impl IntoInner<fs_imp::File> for File {
602 fn into_inner(self) -> fs_imp::File {
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl fmt::Debug for File {
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 /// Indicates how much extra capacity is needed to read the rest of the file.
615 fn buffer_capacity_required(mut file: &File) -> usize {
616 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
617 let pos = file.stream_position().unwrap_or(0);
618 // Don't worry about `usize` overflow because reading will fail regardless
620 size.saturating_sub(pos) as usize
623 #[stable(feature = "rust1", since = "1.0.0")]
625 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
629 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
630 self.inner.read_vectored(bufs)
633 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
634 self.inner.read_buf(buf)
638 fn is_read_vectored(&self) -> bool {
639 self.inner.is_read_vectored()
642 // Reserves space in the buffer based on the file size when available.
643 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
644 buf.reserve(buffer_capacity_required(self));
645 io::default_read_to_end(self, buf)
648 // Reserves space in the buffer based on the file size when available.
649 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
650 buf.reserve(buffer_capacity_required(self));
651 io::default_read_to_string(self, buf)
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Write for File {
656 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
657 self.inner.write(buf)
660 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
661 self.inner.write_vectored(bufs)
665 fn is_write_vectored(&self) -> bool {
666 self.inner.is_write_vectored()
669 fn flush(&mut self) -> io::Result<()> {
673 #[stable(feature = "rust1", since = "1.0.0")]
675 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl Read for &File {
681 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
685 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
686 self.inner.read_buf(buf)
689 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
690 self.inner.read_vectored(bufs)
694 fn is_read_vectored(&self) -> bool {
695 self.inner.is_read_vectored()
698 // Reserves space in the buffer based on the file size when available.
699 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
700 buf.reserve(buffer_capacity_required(self));
701 io::default_read_to_end(self, buf)
704 // Reserves space in the buffer based on the file size when available.
705 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
706 buf.reserve(buffer_capacity_required(self));
707 io::default_read_to_string(self, buf)
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl Write for &File {
712 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
713 self.inner.write(buf)
716 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
717 self.inner.write_vectored(bufs)
721 fn is_write_vectored(&self) -> bool {
722 self.inner.is_write_vectored()
725 fn flush(&mut self) -> io::Result<()> {
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl Seek for &File {
731 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
737 /// Creates a blank new set of options ready for configuration.
739 /// All options are initially set to `false`.
744 /// use std::fs::OpenOptions;
746 /// let mut options = OpenOptions::new();
747 /// let file = options.read(true).open("foo.txt");
749 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn new() -> Self {
752 OpenOptions(fs_imp::OpenOptions::new())
755 /// Sets the option for read access.
757 /// This option, when true, will indicate that the file should be
758 /// `read`-able if opened.
763 /// use std::fs::OpenOptions;
765 /// let file = OpenOptions::new().read(true).open("foo.txt");
767 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn read(&mut self, read: bool) -> &mut Self {
773 /// Sets the option for write access.
775 /// This option, when true, will indicate that the file should be
776 /// `write`-able if opened.
778 /// If the file already exists, any write calls on it will overwrite its
779 /// contents, without truncating it.
784 /// use std::fs::OpenOptions;
786 /// let file = OpenOptions::new().write(true).open("foo.txt");
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn write(&mut self, write: bool) -> &mut Self {
794 /// Sets the option for the append mode.
796 /// This option, when true, means that writes will append to a file instead
797 /// of overwriting previous contents.
798 /// Note that setting `.write(true).append(true)` has the same effect as
799 /// setting only `.append(true)`.
801 /// For most filesystems, the operating system guarantees that all writes are
802 /// atomic: no writes get mangled because another process writes at the same
805 /// One maybe obvious note when using append-mode: make sure that all data
806 /// that belongs together is written to the file in one operation. This
807 /// can be done by concatenating strings before passing them to [`write()`],
808 /// or using a buffered writer (with a buffer of adequate size),
809 /// and calling [`flush()`] when the message is complete.
811 /// If a file is opened with both read and append access, beware that after
812 /// opening, and after every write, the position for reading may be set at the
813 /// end of the file. So, before writing, save the current position (using
814 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
818 /// This function doesn't create the file if it doesn't exist. Use the
819 /// [`OpenOptions::create`] method to do so.
821 /// [`write()`]: Write::write "io::Write::write"
822 /// [`flush()`]: Write::flush "io::Write::flush"
823 /// [seek]: Seek::seek "io::Seek::seek"
824 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
829 /// use std::fs::OpenOptions;
831 /// let file = OpenOptions::new().append(true).open("foo.txt");
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn append(&mut self, append: bool) -> &mut Self {
835 self.0.append(append);
839 /// Sets the option for truncating a previous file.
841 /// If a file is successfully opened with this option set it will truncate
842 /// the file to 0 length if it already exists.
844 /// The file must be opened with write access for truncate to work.
849 /// use std::fs::OpenOptions;
851 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
853 #[stable(feature = "rust1", since = "1.0.0")]
854 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
855 self.0.truncate(truncate);
859 /// Sets the option to create a new file, or open it if it already exists.
861 /// In order for the file to be created, [`OpenOptions::write`] or
862 /// [`OpenOptions::append`] access must be used.
867 /// use std::fs::OpenOptions;
869 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
871 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn create(&mut self, create: bool) -> &mut Self {
873 self.0.create(create);
877 /// Sets the option to create a new file, failing if it already exists.
879 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
880 /// way, if the call succeeds, the file returned is guaranteed to be new.
882 /// This option is useful because it is atomic. Otherwise between checking
883 /// whether a file exists and creating a new one, the file may have been
884 /// created by another process (a TOCTOU race condition / attack).
886 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
889 /// The file must be opened with write or append access in order to create
892 /// [`.create()`]: OpenOptions::create
893 /// [`.truncate()`]: OpenOptions::truncate
898 /// use std::fs::OpenOptions;
900 /// let file = OpenOptions::new().write(true)
901 /// .create_new(true)
902 /// .open("foo.txt");
904 #[stable(feature = "expand_open_options2", since = "1.9.0")]
905 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
906 self.0.create_new(create_new);
910 /// Opens a file at `path` with the options specified by `self`.
914 /// This function will return an error under a number of different
915 /// circumstances. Some of these error conditions are listed here, together
916 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
917 /// part of the compatibility contract of the function.
919 /// * [`NotFound`]: The specified file does not exist and neither `create`
920 /// or `create_new` is set.
921 /// * [`NotFound`]: One of the directory components of the file path does
923 /// * [`PermissionDenied`]: The user lacks permission to get the specified
924 /// access rights for the file.
925 /// * [`PermissionDenied`]: The user lacks permission to open one of the
926 /// directory components of the specified path.
927 /// * [`AlreadyExists`]: `create_new` was specified and the file already
929 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
930 /// without write access, no access mode set, etc.).
932 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
933 /// * One of the directory components of the specified file path
934 /// was not, in fact, a directory.
935 /// * Filesystem-level errors: full disk, write permission
936 /// requested on a read-only file system, exceeded disk quota, too many
937 /// open files, too long filename, too many symbolic links in the
938 /// specified path (Unix-like systems only), etc.
943 /// use std::fs::OpenOptions;
945 /// let file = OpenOptions::new().read(true).open("foo.txt");
948 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
949 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
950 /// [`NotFound`]: io::ErrorKind::NotFound
951 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
952 #[stable(feature = "rust1", since = "1.0.0")]
953 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
954 self._open(path.as_ref())
957 fn _open(&self, path: &Path) -> io::Result<File> {
958 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
962 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
963 fn as_inner(&self) -> &fs_imp::OpenOptions {
968 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
969 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
975 /// Returns the file type for this metadata.
980 /// fn main() -> std::io::Result<()> {
983 /// let metadata = fs::metadata("foo.txt")?;
985 /// println!("{:?}", metadata.file_type());
990 #[stable(feature = "file_type", since = "1.1.0")]
991 pub fn file_type(&self) -> FileType {
992 FileType(self.0.file_type())
995 /// Returns `true` if this metadata is for a directory. The
996 /// result is mutually exclusive to the result of
997 /// [`Metadata::is_file`], and will be false for symlink metadata
998 /// obtained from [`symlink_metadata`].
1003 /// fn main() -> std::io::Result<()> {
1006 /// let metadata = fs::metadata("foo.txt")?;
1008 /// assert!(!metadata.is_dir());
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn is_dir(&self) -> bool {
1015 self.file_type().is_dir()
1018 /// Returns `true` if this metadata is for a regular file. The
1019 /// result is mutually exclusive to the result of
1020 /// [`Metadata::is_dir`], and will be false for symlink metadata
1021 /// obtained from [`symlink_metadata`].
1023 /// When the goal is simply to read from (or write to) the source, the most
1024 /// reliable way to test the source can be read (or written to) is to open
1025 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1026 /// a Unix-like system for example. See [`File::open`] or
1027 /// [`OpenOptions::open`] for more information.
1034 /// fn main() -> std::io::Result<()> {
1035 /// let metadata = fs::metadata("foo.txt")?;
1037 /// assert!(metadata.is_file());
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn is_file(&self) -> bool {
1044 self.file_type().is_file()
1047 /// Returns `true` if this metadata is for a symbolic link.
1051 #[cfg_attr(unix, doc = "```no_run")]
1052 #[cfg_attr(not(unix), doc = "```ignore")]
1054 /// use std::path::Path;
1055 /// use std::os::unix::fs::symlink;
1057 /// fn main() -> std::io::Result<()> {
1058 /// let link_path = Path::new("link");
1059 /// symlink("/origin_does_not_exist/", link_path)?;
1061 /// let metadata = fs::symlink_metadata(link_path)?;
1063 /// assert!(metadata.is_symlink());
1068 #[stable(feature = "is_symlink", since = "1.58.0")]
1069 pub fn is_symlink(&self) -> bool {
1070 self.file_type().is_symlink()
1073 /// Returns the size of the file, in bytes, this metadata is for.
1080 /// fn main() -> std::io::Result<()> {
1081 /// let metadata = fs::metadata("foo.txt")?;
1083 /// assert_eq!(0, metadata.len());
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn len(&self) -> u64 {
1093 /// Returns the permissions of the file this metadata is for.
1100 /// fn main() -> std::io::Result<()> {
1101 /// let metadata = fs::metadata("foo.txt")?;
1103 /// assert!(!metadata.permissions().readonly());
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 pub fn permissions(&self) -> Permissions {
1110 Permissions(self.0.perm())
1113 /// Returns the last modification time listed in this metadata.
1115 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1116 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1120 /// This field might not be available on all platforms, and will return an
1121 /// `Err` on platforms where it is not available.
1128 /// fn main() -> std::io::Result<()> {
1129 /// let metadata = fs::metadata("foo.txt")?;
1131 /// if let Ok(time) = metadata.modified() {
1132 /// println!("{time:?}");
1134 /// println!("Not supported on this platform");
1139 #[stable(feature = "fs_time", since = "1.10.0")]
1140 pub fn modified(&self) -> io::Result<SystemTime> {
1141 self.0.modified().map(FromInner::from_inner)
1144 /// Returns the last access time of this metadata.
1146 /// The returned value corresponds to the `atime` field of `stat` on Unix
1147 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1149 /// Note that not all platforms will keep this field update in a file's
1150 /// metadata, for example Windows has an option to disable updating this
1151 /// time when files are accessed and Linux similarly has `noatime`.
1155 /// This field might not be available on all platforms, and will return an
1156 /// `Err` on platforms where it is not available.
1163 /// fn main() -> std::io::Result<()> {
1164 /// let metadata = fs::metadata("foo.txt")?;
1166 /// if let Ok(time) = metadata.accessed() {
1167 /// println!("{time:?}");
1169 /// println!("Not supported on this platform");
1174 #[stable(feature = "fs_time", since = "1.10.0")]
1175 pub fn accessed(&self) -> io::Result<SystemTime> {
1176 self.0.accessed().map(FromInner::from_inner)
1179 /// Returns the creation time listed in this metadata.
1181 /// The returned value corresponds to the `btime` field of `statx` on
1182 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1183 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1187 /// This field might not be available on all platforms, and will return an
1188 /// `Err` on platforms or filesystems where it is not available.
1195 /// fn main() -> std::io::Result<()> {
1196 /// let metadata = fs::metadata("foo.txt")?;
1198 /// if let Ok(time) = metadata.created() {
1199 /// println!("{time:?}");
1201 /// println!("Not supported on this platform or filesystem");
1206 #[stable(feature = "fs_time", since = "1.10.0")]
1207 pub fn created(&self) -> io::Result<SystemTime> {
1208 self.0.created().map(FromInner::from_inner)
1212 #[stable(feature = "std_debug", since = "1.16.0")]
1213 impl fmt::Debug for Metadata {
1214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 f.debug_struct("Metadata")
1216 .field("file_type", &self.file_type())
1217 .field("is_dir", &self.is_dir())
1218 .field("is_file", &self.is_file())
1219 .field("permissions", &self.permissions())
1220 .field("modified", &self.modified())
1221 .field("accessed", &self.accessed())
1222 .field("created", &self.created())
1223 .finish_non_exhaustive()
1227 impl AsInner<fs_imp::FileAttr> for Metadata {
1228 fn as_inner(&self) -> &fs_imp::FileAttr {
1233 impl FromInner<fs_imp::FileAttr> for Metadata {
1234 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1240 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1245 /// use std::fs::File;
1247 /// fn main() -> std::io::Result<()> {
1248 /// let mut f = File::create("foo.txt")?;
1249 /// let metadata = f.metadata()?;
1251 /// assert_eq!(false, metadata.permissions().readonly());
1255 #[must_use = "call `set_readonly` to modify the readonly flag"]
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 pub fn readonly(&self) -> bool {
1261 /// Modifies the readonly flag for this set of permissions. If the
1262 /// `readonly` argument is `true`, using the resulting `Permission` will
1263 /// update file permissions to forbid writing. Conversely, if it's `false`,
1264 /// using the resulting `Permission` will update file permissions to allow
1267 /// This operation does **not** modify the filesystem. To modify the
1268 /// filesystem use the [`set_permissions`] function.
1273 /// use std::fs::File;
1275 /// fn main() -> std::io::Result<()> {
1276 /// let f = File::create("foo.txt")?;
1277 /// let metadata = f.metadata()?;
1278 /// let mut permissions = metadata.permissions();
1280 /// permissions.set_readonly(true);
1282 /// // filesystem doesn't change
1283 /// assert_eq!(false, metadata.permissions().readonly());
1285 /// // just this particular `permissions`.
1286 /// assert_eq!(true, permissions.readonly());
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub fn set_readonly(&mut self, readonly: bool) {
1292 self.0.set_readonly(readonly)
1297 /// Tests whether this file type represents a directory. The
1298 /// result is mutually exclusive to the results of
1299 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1302 /// [`is_file`]: FileType::is_file
1303 /// [`is_symlink`]: FileType::is_symlink
1308 /// fn main() -> std::io::Result<()> {
1311 /// let metadata = fs::metadata("foo.txt")?;
1312 /// let file_type = metadata.file_type();
1314 /// assert_eq!(file_type.is_dir(), false);
1319 #[stable(feature = "file_type", since = "1.1.0")]
1320 pub fn is_dir(&self) -> bool {
1324 /// Tests whether this file type represents a regular file.
1325 /// The result is mutually exclusive to the results of
1326 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1329 /// When the goal is simply to read from (or write to) the source, the most
1330 /// reliable way to test the source can be read (or written to) is to open
1331 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1332 /// a Unix-like system for example. See [`File::open`] or
1333 /// [`OpenOptions::open`] for more information.
1335 /// [`is_dir`]: FileType::is_dir
1336 /// [`is_symlink`]: FileType::is_symlink
1341 /// fn main() -> std::io::Result<()> {
1344 /// let metadata = fs::metadata("foo.txt")?;
1345 /// let file_type = metadata.file_type();
1347 /// assert_eq!(file_type.is_file(), true);
1352 #[stable(feature = "file_type", since = "1.1.0")]
1353 pub fn is_file(&self) -> bool {
1357 /// Tests whether this file type represents a symbolic link.
1358 /// The result is mutually exclusive to the results of
1359 /// [`is_dir`] and [`is_file`]; only zero or one of these
1362 /// The underlying [`Metadata`] struct needs to be retrieved
1363 /// with the [`fs::symlink_metadata`] function and not the
1364 /// [`fs::metadata`] function. The [`fs::metadata`] function
1365 /// follows symbolic links, so [`is_symlink`] would always
1366 /// return `false` for the target file.
1368 /// [`fs::metadata`]: metadata
1369 /// [`fs::symlink_metadata`]: symlink_metadata
1370 /// [`is_dir`]: FileType::is_dir
1371 /// [`is_file`]: FileType::is_file
1372 /// [`is_symlink`]: FileType::is_symlink
1379 /// fn main() -> std::io::Result<()> {
1380 /// let metadata = fs::symlink_metadata("foo.txt")?;
1381 /// let file_type = metadata.file_type();
1383 /// assert_eq!(file_type.is_symlink(), false);
1388 #[stable(feature = "file_type", since = "1.1.0")]
1389 pub fn is_symlink(&self) -> bool {
1394 impl AsInner<fs_imp::FileType> for FileType {
1395 fn as_inner(&self) -> &fs_imp::FileType {
1400 impl FromInner<fs_imp::FilePermissions> for Permissions {
1401 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1406 impl AsInner<fs_imp::FilePermissions> for Permissions {
1407 fn as_inner(&self) -> &fs_imp::FilePermissions {
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl Iterator for ReadDir {
1414 type Item = io::Result<DirEntry>;
1416 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1417 self.0.next().map(|entry| entry.map(DirEntry))
1422 /// Returns the full path to the file that this entry represents.
1424 /// The full path is created by joining the original path to `read_dir`
1425 /// with the filename of this entry.
1432 /// fn main() -> std::io::Result<()> {
1433 /// for entry in fs::read_dir(".")? {
1434 /// let dir = entry?;
1435 /// println!("{:?}", dir.path());
1441 /// This prints output like:
1444 /// "./whatever.txt"
1446 /// "./hello_world.rs"
1449 /// The exact text, of course, depends on what files you have in `.`.
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 pub fn path(&self) -> PathBuf {
1456 /// Returns the metadata for the file that this entry points at.
1458 /// This function will not traverse symlinks if this entry points at a
1459 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1461 /// [`fs::metadata`]: metadata
1462 /// [`fs::File::metadata`]: File::metadata
1464 /// # Platform-specific behavior
1466 /// On Windows this function is cheap to call (no extra system calls
1467 /// needed), but on Unix platforms this function is the equivalent of
1468 /// calling `symlink_metadata` on the path.
1475 /// if let Ok(entries) = fs::read_dir(".") {
1476 /// for entry in entries {
1477 /// if let Ok(entry) = entry {
1478 /// // Here, `entry` is a `DirEntry`.
1479 /// if let Ok(metadata) = entry.metadata() {
1480 /// // Now let's show our entry's permissions!
1481 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1483 /// println!("Couldn't get metadata for {:?}", entry.path());
1489 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1490 pub fn metadata(&self) -> io::Result<Metadata> {
1491 self.0.metadata().map(Metadata)
1494 /// Returns the file type for the file that this entry points at.
1496 /// This function will not traverse symlinks if this entry points at a
1499 /// # Platform-specific behavior
1501 /// On Windows and most Unix platforms this function is free (no extra
1502 /// system calls needed), but some Unix platforms may require the equivalent
1503 /// call to `symlink_metadata` to learn about the target file type.
1510 /// if let Ok(entries) = fs::read_dir(".") {
1511 /// for entry in entries {
1512 /// if let Ok(entry) = entry {
1513 /// // Here, `entry` is a `DirEntry`.
1514 /// if let Ok(file_type) = entry.file_type() {
1515 /// // Now let's show our entry's file type!
1516 /// println!("{:?}: {:?}", entry.path(), file_type);
1518 /// println!("Couldn't get file type for {:?}", entry.path());
1524 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1525 pub fn file_type(&self) -> io::Result<FileType> {
1526 self.0.file_type().map(FileType)
1529 /// Returns the bare file name of this directory entry without any other
1530 /// leading path component.
1537 /// if let Ok(entries) = fs::read_dir(".") {
1538 /// for entry in entries {
1539 /// if let Ok(entry) = entry {
1540 /// // Here, `entry` is a `DirEntry`.
1541 /// println!("{:?}", entry.file_name());
1547 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1548 pub fn file_name(&self) -> OsString {
1553 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1554 impl fmt::Debug for DirEntry {
1555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1556 f.debug_tuple("DirEntry").field(&self.path()).finish()
1560 impl AsInner<fs_imp::DirEntry> for DirEntry {
1561 fn as_inner(&self) -> &fs_imp::DirEntry {
1566 /// Removes a file from the filesystem.
1568 /// Note that there is no
1569 /// guarantee that the file is immediately deleted (e.g., depending on
1570 /// platform, other open file descriptors may prevent immediate removal).
1572 /// # Platform-specific behavior
1574 /// This function currently corresponds to the `unlink` function on Unix
1575 /// and the `DeleteFile` function on Windows.
1576 /// Note that, this [may change in the future][changes].
1578 /// [changes]: io#platform-specific-behavior
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1585 /// * `path` points to a directory.
1586 /// * The file doesn't exist.
1587 /// * The user lacks permissions to remove the file.
1594 /// fn main() -> std::io::Result<()> {
1595 /// fs::remove_file("a.txt")?;
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1601 fs_imp::unlink(path.as_ref())
1604 /// Given a path, query the file system to get information about a file,
1607 /// This function will traverse symbolic links to query information about the
1608 /// destination file.
1610 /// # Platform-specific behavior
1612 /// This function currently corresponds to the `stat` function on Unix
1613 /// and the `GetFileAttributesEx` function on Windows.
1614 /// Note that, this [may change in the future][changes].
1616 /// [changes]: io#platform-specific-behavior
1620 /// This function will return an error in the following situations, but is not
1621 /// limited to just these cases:
1623 /// * The user lacks permissions to perform `metadata` call on `path`.
1624 /// * `path` does not exist.
1631 /// fn main() -> std::io::Result<()> {
1632 /// let attr = fs::metadata("/some/file/path.txt")?;
1633 /// // inspect attr ...
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1639 fs_imp::stat(path.as_ref()).map(Metadata)
1642 /// Query the metadata about a file without following symlinks.
1644 /// # Platform-specific behavior
1646 /// This function currently corresponds to the `lstat` function on Unix
1647 /// and the `GetFileAttributesEx` function on Windows.
1648 /// Note that, this [may change in the future][changes].
1650 /// [changes]: io#platform-specific-behavior
1654 /// This function will return an error in the following situations, but is not
1655 /// limited to just these cases:
1657 /// * The user lacks permissions to perform `metadata` call on `path`.
1658 /// * `path` does not exist.
1665 /// fn main() -> std::io::Result<()> {
1666 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1667 /// // inspect attr ...
1671 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1672 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1673 fs_imp::lstat(path.as_ref()).map(Metadata)
1676 /// Rename a file or directory to a new name, replacing the original file if
1677 /// `to` already exists.
1679 /// This will not work if the new name is on a different mount point.
1681 /// # Platform-specific behavior
1683 /// This function currently corresponds to the `rename` function on Unix
1684 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1686 /// Because of this, the behavior when both `from` and `to` exist differs. On
1687 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1688 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1689 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1691 /// Note that, this [may change in the future][changes].
1693 /// [changes]: io#platform-specific-behavior
1697 /// This function will return an error in the following situations, but is not
1698 /// limited to just these cases:
1700 /// * `from` does not exist.
1701 /// * The user lacks permissions to view contents.
1702 /// * `from` and `to` are on separate filesystems.
1709 /// fn main() -> std::io::Result<()> {
1710 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1716 fs_imp::rename(from.as_ref(), to.as_ref())
1719 /// Copies the contents of one file to another. This function will also
1720 /// copy the permission bits of the original file to the destination file.
1722 /// This function will **overwrite** the contents of `to`.
1724 /// Note that if `from` and `to` both point to the same file, then the file
1725 /// will likely get truncated by this operation.
1727 /// On success, the total number of bytes copied is returned and it is equal to
1728 /// the length of the `to` file as reported by `metadata`.
1730 /// If you’re wanting to copy the contents of one file to another and you’re
1731 /// working with [`File`]s, see the [`io::copy()`] function.
1733 /// # Platform-specific behavior
1735 /// This function currently corresponds to the `open` function in Unix
1736 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1737 /// `O_CLOEXEC` is set for returned file descriptors.
1739 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1740 /// and falls back to reading and writing if that is not possible.
1742 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1743 /// NTFS streams are copied but only the size of the main stream is returned by
1746 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1748 /// Note that platform-specific behavior [may change in the future][changes].
1750 /// [changes]: io#platform-specific-behavior
1754 /// This function will return an error in the following situations, but is not
1755 /// limited to just these cases:
1757 /// * `from` is neither a regular file nor a symlink to a regular file.
1758 /// * `from` does not exist.
1759 /// * The current process does not have the permission rights to read
1760 /// `from` or write `to`.
1767 /// fn main() -> std::io::Result<()> {
1768 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1774 fs_imp::copy(from.as_ref(), to.as_ref())
1777 /// Creates a new hard link on the filesystem.
1779 /// The `link` path will be a link pointing to the `original` path. Note that
1780 /// systems often require these two paths to both be located on the same
1783 /// If `original` names a symbolic link, it is platform-specific whether the
1784 /// symbolic link is followed. On platforms where it's possible to not follow
1785 /// it, it is not followed, and the created hard link points to the symbolic
1788 /// # Platform-specific behavior
1790 /// This function currently corresponds the `CreateHardLink` function on Windows.
1791 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1792 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1793 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1794 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1795 /// Note that, this [may change in the future][changes].
1797 /// [changes]: io#platform-specific-behavior
1801 /// This function will return an error in the following situations, but is not
1802 /// limited to just these cases:
1804 /// * The `original` path is not a file or doesn't exist.
1811 /// fn main() -> std::io::Result<()> {
1812 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1818 fs_imp::link(original.as_ref(), link.as_ref())
1821 /// Creates a new symbolic link on the filesystem.
1823 /// The `link` path will be a symbolic link pointing to the `original` path.
1824 /// On Windows, this will be a file symlink, not a directory symlink;
1825 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1826 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1827 /// used instead to make the intent explicit.
1829 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1830 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1831 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1838 /// fn main() -> std::io::Result<()> {
1839 /// fs::soft_link("a.txt", "b.txt")?;
1843 #[stable(feature = "rust1", since = "1.0.0")]
1846 reason = "replaced with std::os::unix::fs::symlink and \
1847 std::os::windows::fs::{symlink_file, symlink_dir}"
1849 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1850 fs_imp::symlink(original.as_ref(), link.as_ref())
1853 /// Reads a symbolic link, returning the file that the link points to.
1855 /// # Platform-specific behavior
1857 /// This function currently corresponds to the `readlink` function on Unix
1858 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1859 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1860 /// Note that, this [may change in the future][changes].
1862 /// [changes]: io#platform-specific-behavior
1866 /// This function will return an error in the following situations, but is not
1867 /// limited to just these cases:
1869 /// * `path` is not a symbolic link.
1870 /// * `path` does not exist.
1877 /// fn main() -> std::io::Result<()> {
1878 /// let path = fs::read_link("a.txt")?;
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1884 fs_imp::readlink(path.as_ref())
1887 /// Returns the canonical, absolute form of a path with all intermediate
1888 /// components normalized and symbolic links resolved.
1890 /// # Platform-specific behavior
1892 /// This function currently corresponds to the `realpath` function on Unix
1893 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1894 /// Note that, this [may change in the future][changes].
1896 /// On Windows, this converts the path to use [extended length path][path]
1897 /// syntax, which allows your program to use longer path names, but means you
1898 /// can only join backslash-delimited paths to it, and it may be incompatible
1899 /// with other applications (if passed to the application on the command-line,
1900 /// or written to a file another application may read).
1902 /// [changes]: io#platform-specific-behavior
1903 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1907 /// This function will return an error in the following situations, but is not
1908 /// limited to just these cases:
1910 /// * `path` does not exist.
1911 /// * A non-final component in path is not a directory.
1918 /// fn main() -> std::io::Result<()> {
1919 /// let path = fs::canonicalize("../a/../foo.txt")?;
1923 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1924 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1925 fs_imp::canonicalize(path.as_ref())
1928 /// Creates a new, empty directory at the provided path
1930 /// # Platform-specific behavior
1932 /// This function currently corresponds to the `mkdir` function on Unix
1933 /// and the `CreateDirectory` function on Windows.
1934 /// Note that, this [may change in the future][changes].
1936 /// [changes]: io#platform-specific-behavior
1938 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1939 /// return an error. To create a directory and all its missing parents at the
1940 /// same time, use the [`create_dir_all`] function.
1944 /// This function will return an error in the following situations, but is not
1945 /// limited to just these cases:
1947 /// * User lacks permissions to create directory at `path`.
1948 /// * A parent of the given path doesn't exist. (To create a directory and all
1949 /// its missing parents at the same time, use the [`create_dir_all`]
1951 /// * `path` already exists.
1958 /// fn main() -> std::io::Result<()> {
1959 /// fs::create_dir("/some/dir")?;
1963 #[doc(alias = "mkdir")]
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1966 DirBuilder::new().create(path.as_ref())
1969 /// Recursively create a directory and all of its parent components if they
1972 /// # Platform-specific behavior
1974 /// This function currently corresponds to the `mkdir` function on Unix
1975 /// and the `CreateDirectory` function on Windows.
1976 /// Note that, this [may change in the future][changes].
1978 /// [changes]: io#platform-specific-behavior
1982 /// This function will return an error in the following situations, but is not
1983 /// limited to just these cases:
1985 /// * If any directory in the path specified by `path`
1986 /// does not already exist and it could not be created otherwise. The specific
1987 /// error conditions for when a directory is being created (after it is
1988 /// determined to not exist) are outlined by [`fs::create_dir`].
1990 /// Notable exception is made for situations where any of the directories
1991 /// specified in the `path` could not be created as it was being created concurrently.
1992 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1993 /// concurrently from multiple threads or processes is guaranteed not to fail
1994 /// due to a race condition with itself.
1996 /// [`fs::create_dir`]: create_dir
2003 /// fn main() -> std::io::Result<()> {
2004 /// fs::create_dir_all("/some/dir")?;
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2010 DirBuilder::new().recursive(true).create(path.as_ref())
2013 /// Removes an empty directory.
2015 /// # Platform-specific behavior
2017 /// This function currently corresponds to the `rmdir` function on Unix
2018 /// and the `RemoveDirectory` function on Windows.
2019 /// Note that, this [may change in the future][changes].
2021 /// [changes]: io#platform-specific-behavior
2025 /// This function will return an error in the following situations, but is not
2026 /// limited to just these cases:
2028 /// * `path` doesn't exist.
2029 /// * `path` isn't a directory.
2030 /// * The user lacks permissions to remove the directory at the provided `path`.
2031 /// * The directory isn't empty.
2038 /// fn main() -> std::io::Result<()> {
2039 /// fs::remove_dir("/some/dir")?;
2043 #[doc(alias = "rmdir")]
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2046 fs_imp::rmdir(path.as_ref())
2049 /// Removes a directory at this path, after removing all its contents. Use
2052 /// This function does **not** follow symbolic links and it will simply remove the
2053 /// symbolic link itself.
2055 /// # Platform-specific behavior
2057 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2058 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2059 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2060 /// Windows. Note that, this [may change in the future][changes].
2062 /// [changes]: io#platform-specific-behavior
2064 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2065 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2066 /// should not be used in security-sensitive code on those platforms. All other platforms are
2071 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2073 /// [`fs::remove_file`]: remove_file
2074 /// [`fs::remove_dir`]: remove_dir
2081 /// fn main() -> std::io::Result<()> {
2082 /// fs::remove_dir_all("/some/dir")?;
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2088 fs_imp::remove_dir_all(path.as_ref())
2091 /// Returns an iterator over the entries within a directory.
2093 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2094 /// New errors may be encountered after an iterator is initially constructed.
2095 /// Entries for the current and parent directories (typically `.` and `..`) are
2098 /// # Platform-specific behavior
2100 /// This function currently corresponds to the `opendir` function on Unix
2101 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2102 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2103 /// Note that, this [may change in the future][changes].
2105 /// [changes]: io#platform-specific-behavior
2107 /// The order in which this iterator returns entries is platform and filesystem
2112 /// This function will return an error in the following situations, but is not
2113 /// limited to just these cases:
2115 /// * The provided `path` doesn't exist.
2116 /// * The process lacks permissions to view the contents.
2117 /// * The `path` points at a non-directory file.
2123 /// use std::fs::{self, DirEntry};
2124 /// use std::path::Path;
2126 /// // one possible implementation of walking a directory only visiting files
2127 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2128 /// if dir.is_dir() {
2129 /// for entry in fs::read_dir(dir)? {
2130 /// let entry = entry?;
2131 /// let path = entry.path();
2132 /// if path.is_dir() {
2133 /// visit_dirs(&path, cb)?;
2144 /// use std::{fs, io};
2146 /// fn main() -> io::Result<()> {
2147 /// let mut entries = fs::read_dir(".")?
2148 /// .map(|res| res.map(|e| e.path()))
2149 /// .collect::<Result<Vec<_>, io::Error>>()?;
2151 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2152 /// // ordering is required the entries should be explicitly sorted.
2156 /// // The entries have now been sorted by their path.
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2163 fs_imp::readdir(path.as_ref()).map(ReadDir)
2166 /// Changes the permissions found on a file or a directory.
2168 /// # Platform-specific behavior
2170 /// This function currently corresponds to the `chmod` function on Unix
2171 /// and the `SetFileAttributes` function on Windows.
2172 /// Note that, this [may change in the future][changes].
2174 /// [changes]: io#platform-specific-behavior
2178 /// This function will return an error in the following situations, but is not
2179 /// limited to just these cases:
2181 /// * `path` does not exist.
2182 /// * The user lacks the permission to change attributes of the file.
2189 /// fn main() -> std::io::Result<()> {
2190 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2191 /// perms.set_readonly(true);
2192 /// fs::set_permissions("foo.txt", perms)?;
2196 #[stable(feature = "set_permissions", since = "1.1.0")]
2197 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2198 fs_imp::set_perm(path.as_ref(), perm.0)
2202 /// Creates a new set of options with default mode/security settings for all
2203 /// platforms and also non-recursive.
2208 /// use std::fs::DirBuilder;
2210 /// let builder = DirBuilder::new();
2212 #[stable(feature = "dir_builder", since = "1.6.0")]
2214 pub fn new() -> DirBuilder {
2215 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2218 /// Indicates that directories should be created recursively, creating all
2219 /// parent directories. Parents that do not exist are created with the same
2220 /// security and permissions settings.
2222 /// This option defaults to `false`.
2227 /// use std::fs::DirBuilder;
2229 /// let mut builder = DirBuilder::new();
2230 /// builder.recursive(true);
2232 #[stable(feature = "dir_builder", since = "1.6.0")]
2233 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2234 self.recursive = recursive;
2238 /// Creates the specified directory with the options configured in this
2241 /// It is considered an error if the directory already exists unless
2242 /// recursive mode is enabled.
2247 /// use std::fs::{self, DirBuilder};
2249 /// let path = "/tmp/foo/bar/baz";
2250 /// DirBuilder::new()
2251 /// .recursive(true)
2252 /// .create(path).unwrap();
2254 /// assert!(fs::metadata(path).unwrap().is_dir());
2256 #[stable(feature = "dir_builder", since = "1.6.0")]
2257 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2258 self._create(path.as_ref())
2261 fn _create(&self, path: &Path) -> io::Result<()> {
2262 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2265 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2266 if path == Path::new("") {
2270 match self.inner.mkdir(path) {
2271 Ok(()) => return Ok(()),
2272 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2273 Err(_) if path.is_dir() => return Ok(()),
2274 Err(e) => return Err(e),
2276 match path.parent() {
2277 Some(p) => self.create_dir_all(p)?,
2279 return Err(io::const_io_error!(
2280 io::ErrorKind::Uncategorized,
2281 "failed to create whole tree",
2285 match self.inner.mkdir(path) {
2287 Err(_) if path.is_dir() => Ok(()),
2293 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2294 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2299 /// Returns `Ok(true)` if the path points at an existing entity.
2301 /// This function will traverse symbolic links to query information about the
2302 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2304 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2305 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2306 /// denied on some of the parent directories.)
2311 /// #![feature(path_try_exists)]
2314 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2315 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2318 /// [`Path::exists`]: crate::path::Path::exists
2319 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2321 #[unstable(feature = "path_try_exists", issue = "83186")]
2323 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2324 fs_imp::try_exists(path.as_ref())