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, Initializer, IoSlice, IoSliceMut, Read, 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 /// [`BufReader<R>`]: io::BufReader
89 /// [`sync_all`]: File::sync_all
90 #[stable(feature = "rust1", since = "1.0.0")]
95 /// Metadata information about a file.
97 /// This structure is returned from the [`metadata`] or
98 /// [`symlink_metadata`] function or method and represents known
99 /// metadata about a file such as its permissions, size, modification
101 #[stable(feature = "rust1", since = "1.0.0")]
103 pub struct Metadata(fs_imp::FileAttr);
105 /// Iterator over the entries in a directory.
107 /// This iterator is returned from the [`read_dir`] function of this module and
108 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
109 /// information like the entry's path and possibly other metadata can be
112 /// The order in which this iterator returns entries is platform and filesystem
117 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
118 /// IO error during iteration.
119 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct ReadDir(fs_imp::ReadDir);
123 /// Entries returned by the [`ReadDir`] iterator.
125 /// An instance of `DirEntry` represents an entry inside of a directory on the
126 /// filesystem. Each entry can be inspected via methods to learn about the full
127 /// path or possibly other metadata through per-platform extension traits.
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct DirEntry(fs_imp::DirEntry);
131 /// Options and flags which can be used to configure how a file is opened.
133 /// This builder exposes the ability to configure how a [`File`] is opened and
134 /// what operations are permitted on the open file. The [`File::open`] and
135 /// [`File::create`] methods are aliases for commonly used options using this
138 /// Generally speaking, when using `OpenOptions`, you'll first call
139 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
140 /// call [`OpenOptions::open`], passing the path of the file you're trying to
141 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
142 /// can further operate on.
146 /// Opening a file to read:
149 /// use std::fs::OpenOptions;
151 /// let file = OpenOptions::new().read(true).open("foo.txt");
154 /// Opening a file for both reading and writing, as well as creating it if it
158 /// use std::fs::OpenOptions;
160 /// let file = OpenOptions::new()
164 /// .open("foo.txt");
166 #[derive(Clone, Debug)]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct OpenOptions(fs_imp::OpenOptions);
170 /// Representation of the various permissions on a file.
172 /// This module only currently provides one bit of information,
173 /// [`Permissions::readonly`], which is exposed on all currently supported
174 /// platforms. Unix-specific functionality, such as mode bits, is available
175 /// through the [`PermissionsExt`] trait.
177 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
178 #[derive(Clone, PartialEq, Eq, Debug)]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct Permissions(fs_imp::FilePermissions);
182 /// A structure representing a type of file with accessors for each file type.
183 /// It is returned by [`Metadata::file_type`] method.
184 #[stable(feature = "file_type", since = "1.1.0")]
185 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
186 pub struct FileType(fs_imp::FileType);
188 /// A builder used to create directories in various manners.
190 /// This builder also supports platform-specific options.
191 #[stable(feature = "dir_builder", since = "1.6.0")]
193 pub struct DirBuilder {
194 inner: fs_imp::DirBuilder,
198 /// Indicates how large a buffer to pre-allocate before reading the entire file.
199 fn initial_buffer_size(file: &File) -> usize {
200 // Allocate one extra byte so the buffer doesn't need to grow before the
201 // final `read` call at the end of the file. Don't worry about `usize`
202 // overflow because reading will fail regardless in that case.
203 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
206 /// Read the entire contents of a file into a bytes vector.
208 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
209 /// with fewer imports and without an intermediate variable. It pre-allocates a
210 /// buffer based on the file size when available, so it is generally faster than
211 /// reading into a vector created with [`Vec::new()`].
213 /// [`read_to_end`]: Read::read_to_end
217 /// This function will return an error if `path` does not already exist.
218 /// Other errors may also be returned according to [`OpenOptions::open`].
220 /// It will also return an error if it encounters while reading an error
221 /// of a kind other than [`io::ErrorKind::Interrupted`].
227 /// use std::net::SocketAddr;
229 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
230 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
234 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
235 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
236 fn inner(path: &Path) -> io::Result<Vec<u8>> {
237 let mut file = File::open(path)?;
238 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
239 file.read_to_end(&mut bytes)?;
245 /// Read the entire contents of a file into a string.
247 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
248 /// with fewer imports and without an intermediate variable. It pre-allocates a
249 /// buffer based on the file size when available, so it is generally faster than
250 /// reading into a string created with [`String::new()`].
252 /// [`read_to_string`]: Read::read_to_string
256 /// This function will return an error if `path` does not already exist.
257 /// Other errors may also be returned according to [`OpenOptions::open`].
259 /// It will also return an error if it encounters while reading an error
260 /// of a kind other than [`io::ErrorKind::Interrupted`],
261 /// or if the contents of the file are not valid UTF-8.
267 /// use std::net::SocketAddr;
268 /// use std::error::Error;
270 /// fn main() -> Result<(), Box<dyn Error>> {
271 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
275 #[stable(feature = "fs_read_write", since = "1.26.0")]
276 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
277 fn inner(path: &Path) -> io::Result<String> {
278 let mut file = File::open(path)?;
279 let mut string = String::with_capacity(initial_buffer_size(&file));
280 file.read_to_string(&mut string)?;
286 /// Write a slice as the entire contents of a file.
288 /// This function will create a file if it does not exist,
289 /// and will entirely replace its contents if it does.
291 /// This is a convenience function for using [`File::create`] and [`write_all`]
292 /// with fewer imports.
294 /// [`write_all`]: Write::write_all
301 /// fn main() -> std::io::Result<()> {
302 /// fs::write("foo.txt", b"Lorem ipsum")?;
303 /// fs::write("bar.txt", "dolor sit")?;
307 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
308 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
309 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
310 File::create(path)?.write_all(contents)
312 inner(path.as_ref(), contents.as_ref())
316 /// Attempts to open a file in read-only mode.
318 /// See the [`OpenOptions::open`] method for more details.
322 /// This function will return an error if `path` does not already exist.
323 /// Other errors may also be returned according to [`OpenOptions::open`].
328 /// use std::fs::File;
330 /// fn main() -> std::io::Result<()> {
331 /// let mut f = File::open("foo.txt")?;
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
337 OpenOptions::new().read(true).open(path.as_ref())
340 /// Opens a file in write-only mode.
342 /// This function will create a file if it does not exist,
343 /// and will truncate it if it does.
345 /// See the [`OpenOptions::open`] function for more details.
350 /// use std::fs::File;
352 /// fn main() -> std::io::Result<()> {
353 /// let mut f = File::create("foo.txt")?;
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
359 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
362 /// Returns a new OpenOptions object.
364 /// This function returns a new OpenOptions object that you can use to
365 /// open or create a file with specific options if `open()` or `create()`
366 /// are not appropriate.
368 /// It is equivalent to `OpenOptions::new()` but allows you to write more
369 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
370 /// you can write `File::with_options().read(true).open("foo.txt")`. This
371 /// also avoids the need to import `OpenOptions`.
373 /// See the [`OpenOptions::new`] function for more details.
378 /// #![feature(with_options)]
379 /// use std::fs::File;
381 /// fn main() -> std::io::Result<()> {
382 /// let mut f = File::with_options().read(true).open("foo.txt")?;
386 #[unstable(feature = "with_options", issue = "65439")]
387 pub fn with_options() -> OpenOptions {
391 /// Attempts to sync all OS-internal metadata to disk.
393 /// This function will attempt to ensure that all in-memory data reaches the
394 /// filesystem before returning.
396 /// This can be used to handle errors that would otherwise only be caught
397 /// when the `File` is closed. Dropping a file will ignore errors in
398 /// synchronizing this in-memory data.
403 /// use std::fs::File;
404 /// use std::io::prelude::*;
406 /// fn main() -> std::io::Result<()> {
407 /// let mut f = File::create("foo.txt")?;
408 /// f.write_all(b"Hello, world!")?;
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn sync_all(&self) -> io::Result<()> {
419 /// This function is similar to [`sync_all`], except that it may not
420 /// synchronize file metadata to the filesystem.
422 /// This is intended for use cases that must synchronize content, but don't
423 /// need the metadata on disk. The goal of this method is to reduce disk
426 /// Note that some platforms may simply implement this in terms of
429 /// [`sync_all`]: File::sync_all
434 /// use std::fs::File;
435 /// use std::io::prelude::*;
437 /// fn main() -> std::io::Result<()> {
438 /// let mut f = File::create("foo.txt")?;
439 /// f.write_all(b"Hello, world!")?;
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn sync_data(&self) -> io::Result<()> {
447 self.inner.datasync()
450 /// Truncates or extends the underlying file, updating the size of
451 /// this file to become `size`.
453 /// If the `size` is less than the current file's size, then the file will
454 /// be shrunk. If it is greater than the current file's size, then the file
455 /// will be extended to `size` and have all of the intermediate data filled
458 /// The file's cursor isn't changed. In particular, if the cursor was at the
459 /// end and the file is shrunk using this operation, the cursor will now be
464 /// This function will return an error if the file is not opened for writing.
465 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
466 /// length would cause an overflow due to the implementation specifics.
471 /// use std::fs::File;
473 /// fn main() -> std::io::Result<()> {
474 /// let mut f = File::create("foo.txt")?;
480 /// Note that this method alters the content of the underlying file, even
481 /// though it takes `&self` rather than `&mut self`.
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn set_len(&self, size: u64) -> io::Result<()> {
484 self.inner.truncate(size)
487 /// Queries metadata about the underlying file.
492 /// use std::fs::File;
494 /// fn main() -> std::io::Result<()> {
495 /// let mut f = File::open("foo.txt")?;
496 /// let metadata = f.metadata()?;
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn metadata(&self) -> io::Result<Metadata> {
502 self.inner.file_attr().map(Metadata)
505 /// Creates a new `File` instance that shares the same underlying file handle
506 /// as the existing `File` instance. Reads, writes, and seeks will affect
507 /// both `File` instances simultaneously.
511 /// Creates two handles for a file named `foo.txt`:
514 /// use std::fs::File;
516 /// fn main() -> std::io::Result<()> {
517 /// let mut file = File::open("foo.txt")?;
518 /// let file_copy = file.try_clone()?;
523 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
524 /// two handles, seek one of them, and read the remaining bytes from the
528 /// use std::fs::File;
529 /// use std::io::SeekFrom;
530 /// use std::io::prelude::*;
532 /// fn main() -> std::io::Result<()> {
533 /// let mut file = File::open("foo.txt")?;
534 /// let mut file_copy = file.try_clone()?;
536 /// file.seek(SeekFrom::Start(3))?;
538 /// let mut contents = vec![];
539 /// file_copy.read_to_end(&mut contents)?;
540 /// assert_eq!(contents, b"def\n");
544 #[stable(feature = "file_try_clone", since = "1.9.0")]
545 pub fn try_clone(&self) -> io::Result<File> {
546 Ok(File { inner: self.inner.duplicate()? })
549 /// Changes the permissions on the underlying file.
551 /// # Platform-specific behavior
553 /// This function currently corresponds to the `fchmod` function on Unix and
554 /// the `SetFileInformationByHandle` function on Windows. Note that, this
555 /// [may change in the future][changes].
557 /// [changes]: io#platform-specific-behavior
561 /// This function will return an error if the user lacks permission change
562 /// attributes on the underlying file. It may also return an error in other
563 /// os-specific unspecified cases.
568 /// fn main() -> std::io::Result<()> {
569 /// use std::fs::File;
571 /// let file = File::open("foo.txt")?;
572 /// let mut perms = file.metadata()?.permissions();
573 /// perms.set_readonly(true);
574 /// file.set_permissions(perms)?;
579 /// Note that this method alters the permissions of the underlying file,
580 /// even though it takes `&self` rather than `&mut self`.
581 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
582 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
583 self.inner.set_permissions(perm.0)
587 impl AsInner<fs_imp::File> for File {
588 fn as_inner(&self) -> &fs_imp::File {
592 impl FromInner<fs_imp::File> for File {
593 fn from_inner(f: fs_imp::File) -> File {
597 impl IntoInner<fs_imp::File> for File {
598 fn into_inner(self) -> fs_imp::File {
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl fmt::Debug for File {
605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610 #[stable(feature = "rust1", since = "1.0.0")]
612 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
616 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
617 self.inner.read_vectored(bufs)
621 fn is_read_vectored(&self) -> bool {
622 self.inner.is_read_vectored()
626 unsafe fn initializer(&self) -> Initializer {
627 // SAFETY: Read is guaranteed to work on uninitialized memory
628 unsafe { Initializer::nop() }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Write for File {
633 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
634 self.inner.write(buf)
637 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
638 self.inner.write_vectored(bufs)
642 fn is_write_vectored(&self) -> bool {
643 self.inner.is_write_vectored()
646 fn flush(&mut self) -> io::Result<()> {
650 #[stable(feature = "rust1", since = "1.0.0")]
652 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl Read for &File {
658 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
662 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
663 self.inner.read_vectored(bufs)
667 fn is_read_vectored(&self) -> bool {
668 self.inner.is_read_vectored()
672 unsafe fn initializer(&self) -> Initializer {
673 // SAFETY: Read is guaranteed to work on uninitialized memory
674 unsafe { Initializer::nop() }
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Write for &File {
679 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
680 self.inner.write(buf)
683 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
684 self.inner.write_vectored(bufs)
688 fn is_write_vectored(&self) -> bool {
689 self.inner.is_write_vectored()
692 fn flush(&mut self) -> io::Result<()> {
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl Seek for &File {
698 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
704 /// Creates a blank new set of options ready for configuration.
706 /// All options are initially set to `false`.
711 /// use std::fs::OpenOptions;
713 /// let mut options = OpenOptions::new();
714 /// let file = options.read(true).open("foo.txt");
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn new() -> Self {
718 OpenOptions(fs_imp::OpenOptions::new())
721 /// Sets the option for read access.
723 /// This option, when true, will indicate that the file should be
724 /// `read`-able if opened.
729 /// use std::fs::OpenOptions;
731 /// let file = OpenOptions::new().read(true).open("foo.txt");
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn read(&mut self, read: bool) -> &mut Self {
739 /// Sets the option for write access.
741 /// This option, when true, will indicate that the file should be
742 /// `write`-able if opened.
744 /// If the file already exists, any write calls on it will overwrite its
745 /// contents, without truncating it.
750 /// use std::fs::OpenOptions;
752 /// let file = OpenOptions::new().write(true).open("foo.txt");
754 #[stable(feature = "rust1", since = "1.0.0")]
755 pub fn write(&mut self, write: bool) -> &mut Self {
760 /// Sets the option for the append mode.
762 /// This option, when true, means that writes will append to a file instead
763 /// of overwriting previous contents.
764 /// Note that setting `.write(true).append(true)` has the same effect as
765 /// setting only `.append(true)`.
767 /// For most filesystems, the operating system guarantees that all writes are
768 /// atomic: no writes get mangled because another process writes at the same
771 /// One maybe obvious note when using append-mode: make sure that all data
772 /// that belongs together is written to the file in one operation. This
773 /// can be done by concatenating strings before passing them to [`write()`],
774 /// or using a buffered writer (with a buffer of adequate size),
775 /// and calling [`flush()`] when the message is complete.
777 /// If a file is opened with both read and append access, beware that after
778 /// opening, and after every write, the position for reading may be set at the
779 /// end of the file. So, before writing, save the current position (using
780 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
784 /// This function doesn't create the file if it doesn't exist. Use the
785 /// [`OpenOptions::create`] method to do so.
787 /// [`write()`]: Write::write
788 /// [`flush()`]: Write::flush
789 /// [`seek`]: Seek::seek
790 /// [`Current`]: SeekFrom::Current
795 /// use std::fs::OpenOptions;
797 /// let file = OpenOptions::new().append(true).open("foo.txt");
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn append(&mut self, append: bool) -> &mut Self {
801 self.0.append(append);
805 /// Sets the option for truncating a previous file.
807 /// If a file is successfully opened with this option set it will truncate
808 /// the file to 0 length if it already exists.
810 /// The file must be opened with write access for truncate to work.
815 /// use std::fs::OpenOptions;
817 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
821 self.0.truncate(truncate);
825 /// Sets the option to create a new file, or open it if it already exists.
827 /// In order for the file to be created, [`OpenOptions::write`] or
828 /// [`OpenOptions::append`] access must be used.
833 /// use std::fs::OpenOptions;
835 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn create(&mut self, create: bool) -> &mut Self {
839 self.0.create(create);
843 /// Sets the option to create a new file, failing if it already exists.
845 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
846 /// way, if the call succeeds, the file returned is guaranteed to be new.
848 /// This option is useful because it is atomic. Otherwise between checking
849 /// whether a file exists and creating a new one, the file may have been
850 /// created by another process (a TOCTOU race condition / attack).
852 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
855 /// The file must be opened with write or append access in order to create
858 /// [`.create()`]: OpenOptions::create
859 /// [`.truncate()`]: OpenOptions::truncate
864 /// use std::fs::OpenOptions;
866 /// let file = OpenOptions::new().write(true)
867 /// .create_new(true)
868 /// .open("foo.txt");
870 #[stable(feature = "expand_open_options2", since = "1.9.0")]
871 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
872 self.0.create_new(create_new);
876 /// Opens a file at `path` with the options specified by `self`.
880 /// This function will return an error under a number of different
881 /// circumstances. Some of these error conditions are listed here, together
882 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
883 /// part of the compatibility contract of the function.
885 /// * [`NotFound`]: The specified file does not exist and neither `create`
886 /// or `create_new` is set.
887 /// * [`NotFound`]: One of the directory components of the file path does
889 /// * [`PermissionDenied`]: The user lacks permission to get the specified
890 /// access rights for the file.
891 /// * [`PermissionDenied`]: The user lacks permission to open one of the
892 /// directory components of the specified path.
893 /// * [`AlreadyExists`]: `create_new` was specified and the file already
895 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
896 /// without write access, no access mode set, etc.).
898 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
899 /// * One of the directory components of the specified file path
900 /// was not, in fact, a directory.
901 /// * Filesystem-level errors: full disk, write permission
902 /// requested on a read-only file system, exceeded disk quota, too many
903 /// open files, too long filename, too many symbolic links in the
904 /// specified path (Unix-like systems only), etc.
909 /// use std::fs::OpenOptions;
911 /// let file = OpenOptions::new().read(true).open("foo.txt");
914 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
915 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
916 /// [`NotFound`]: io::ErrorKind::NotFound
917 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
920 self._open(path.as_ref())
923 fn _open(&self, path: &Path) -> io::Result<File> {
924 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
928 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
929 fn as_inner(&self) -> &fs_imp::OpenOptions {
934 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
935 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
941 /// Returns the file type for this metadata.
946 /// fn main() -> std::io::Result<()> {
949 /// let metadata = fs::metadata("foo.txt")?;
951 /// println!("{:?}", metadata.file_type());
955 #[stable(feature = "file_type", since = "1.1.0")]
956 pub fn file_type(&self) -> FileType {
957 FileType(self.0.file_type())
960 /// Returns `true` if this metadata is for a directory. The
961 /// result is mutually exclusive to the result of
962 /// [`Metadata::is_file`], and will be false for symlink metadata
963 /// obtained from [`symlink_metadata`].
968 /// fn main() -> std::io::Result<()> {
971 /// let metadata = fs::metadata("foo.txt")?;
973 /// assert!(!metadata.is_dir());
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn is_dir(&self) -> bool {
979 self.file_type().is_dir()
982 /// Returns `true` if this metadata is for a regular file. The
983 /// result is mutually exclusive to the result of
984 /// [`Metadata::is_dir`], and will be false for symlink metadata
985 /// obtained from [`symlink_metadata`].
987 /// When the goal is simply to read from (or write to) the source, the most
988 /// reliable way to test the source can be read (or written to) is to open
989 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
990 /// a Unix-like system for example. See [`File::open`] or
991 /// [`OpenOptions::open`] for more information.
998 /// fn main() -> std::io::Result<()> {
999 /// let metadata = fs::metadata("foo.txt")?;
1001 /// assert!(metadata.is_file());
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn is_file(&self) -> bool {
1007 self.file_type().is_file()
1010 /// Returns the size of the file, in bytes, this metadata is for.
1017 /// fn main() -> std::io::Result<()> {
1018 /// let metadata = fs::metadata("foo.txt")?;
1020 /// assert_eq!(0, metadata.len());
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub fn len(&self) -> u64 {
1029 /// Returns the permissions of the file this metadata is for.
1036 /// fn main() -> std::io::Result<()> {
1037 /// let metadata = fs::metadata("foo.txt")?;
1039 /// assert!(!metadata.permissions().readonly());
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 pub fn permissions(&self) -> Permissions {
1045 Permissions(self.0.perm())
1048 /// Returns the last modification time listed in this metadata.
1050 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1051 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1055 /// This field may not be available on all platforms, and will return an
1056 /// `Err` on platforms where it is not available.
1063 /// fn main() -> std::io::Result<()> {
1064 /// let metadata = fs::metadata("foo.txt")?;
1066 /// if let Ok(time) = metadata.modified() {
1067 /// println!("{:?}", time);
1069 /// println!("Not supported on this platform");
1074 #[stable(feature = "fs_time", since = "1.10.0")]
1075 pub fn modified(&self) -> io::Result<SystemTime> {
1076 self.0.modified().map(FromInner::from_inner)
1079 /// Returns the last access time of this metadata.
1081 /// The returned value corresponds to the `atime` field of `stat` on Unix
1082 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1084 /// Note that not all platforms will keep this field update in a file's
1085 /// metadata, for example Windows has an option to disable updating this
1086 /// time when files are accessed and Linux similarly has `noatime`.
1090 /// This field may not be available on all platforms, and will return an
1091 /// `Err` on platforms where it is not available.
1098 /// fn main() -> std::io::Result<()> {
1099 /// let metadata = fs::metadata("foo.txt")?;
1101 /// if let Ok(time) = metadata.accessed() {
1102 /// println!("{:?}", time);
1104 /// println!("Not supported on this platform");
1109 #[stable(feature = "fs_time", since = "1.10.0")]
1110 pub fn accessed(&self) -> io::Result<SystemTime> {
1111 self.0.accessed().map(FromInner::from_inner)
1114 /// Returns the creation time listed in this metadata.
1116 /// The returned value corresponds to the `btime` field of `statx` on
1117 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1118 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1122 /// This field may not be available on all platforms, and will return an
1123 /// `Err` on platforms or filesystems where it is not available.
1130 /// fn main() -> std::io::Result<()> {
1131 /// let metadata = fs::metadata("foo.txt")?;
1133 /// if let Ok(time) = metadata.created() {
1134 /// println!("{:?}", time);
1136 /// println!("Not supported on this platform or filesystem");
1141 #[stable(feature = "fs_time", since = "1.10.0")]
1142 pub fn created(&self) -> io::Result<SystemTime> {
1143 self.0.created().map(FromInner::from_inner)
1147 #[stable(feature = "std_debug", since = "1.16.0")]
1148 impl fmt::Debug for Metadata {
1149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150 f.debug_struct("Metadata")
1151 .field("file_type", &self.file_type())
1152 .field("is_dir", &self.is_dir())
1153 .field("is_file", &self.is_file())
1154 .field("permissions", &self.permissions())
1155 .field("modified", &self.modified())
1156 .field("accessed", &self.accessed())
1157 .field("created", &self.created())
1158 .finish_non_exhaustive()
1162 impl AsInner<fs_imp::FileAttr> for Metadata {
1163 fn as_inner(&self) -> &fs_imp::FileAttr {
1168 impl FromInner<fs_imp::FileAttr> for Metadata {
1169 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1175 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1180 /// use std::fs::File;
1182 /// fn main() -> std::io::Result<()> {
1183 /// let mut f = File::create("foo.txt")?;
1184 /// let metadata = f.metadata()?;
1186 /// assert_eq!(false, metadata.permissions().readonly());
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub fn readonly(&self) -> bool {
1195 /// Modifies the readonly flag for this set of permissions. If the
1196 /// `readonly` argument is `true`, using the resulting `Permission` will
1197 /// update file permissions to forbid writing. Conversely, if it's `false`,
1198 /// using the resulting `Permission` will update file permissions to allow
1201 /// This operation does **not** modify the filesystem. To modify the
1202 /// filesystem use the [`set_permissions`] function.
1207 /// use std::fs::File;
1209 /// fn main() -> std::io::Result<()> {
1210 /// let f = File::create("foo.txt")?;
1211 /// let metadata = f.metadata()?;
1212 /// let mut permissions = metadata.permissions();
1214 /// permissions.set_readonly(true);
1216 /// // filesystem doesn't change
1217 /// assert_eq!(false, metadata.permissions().readonly());
1219 /// // just this particular `permissions`.
1220 /// assert_eq!(true, permissions.readonly());
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub fn set_readonly(&mut self, readonly: bool) {
1226 self.0.set_readonly(readonly)
1231 /// Tests whether this file type represents a directory. The
1232 /// result is mutually exclusive to the results of
1233 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1236 /// [`is_file`]: FileType::is_file
1237 /// [`is_symlink`]: FileType::is_symlink
1242 /// fn main() -> std::io::Result<()> {
1245 /// let metadata = fs::metadata("foo.txt")?;
1246 /// let file_type = metadata.file_type();
1248 /// assert_eq!(file_type.is_dir(), false);
1252 #[stable(feature = "file_type", since = "1.1.0")]
1253 pub fn is_dir(&self) -> bool {
1257 /// Tests whether this file type represents a regular file.
1258 /// The result is mutually exclusive to the results of
1259 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1262 /// When the goal is simply to read from (or write to) the source, the most
1263 /// reliable way to test the source can be read (or written to) is to open
1264 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1265 /// a Unix-like system for example. See [`File::open`] or
1266 /// [`OpenOptions::open`] for more information.
1268 /// [`is_dir`]: FileType::is_dir
1269 /// [`is_symlink`]: FileType::is_symlink
1274 /// fn main() -> std::io::Result<()> {
1277 /// let metadata = fs::metadata("foo.txt")?;
1278 /// let file_type = metadata.file_type();
1280 /// assert_eq!(file_type.is_file(), true);
1284 #[stable(feature = "file_type", since = "1.1.0")]
1285 pub fn is_file(&self) -> bool {
1289 /// Tests whether this file type represents a symbolic link.
1290 /// The result is mutually exclusive to the results of
1291 /// [`is_dir`] and [`is_file`]; only zero or one of these
1294 /// The underlying [`Metadata`] struct needs to be retrieved
1295 /// with the [`fs::symlink_metadata`] function and not the
1296 /// [`fs::metadata`] function. The [`fs::metadata`] function
1297 /// follows symbolic links, so [`is_symlink`] would always
1298 /// return `false` for the target file.
1300 /// [`fs::metadata`]: metadata
1301 /// [`fs::symlink_metadata`]: symlink_metadata
1302 /// [`is_dir`]: FileType::is_dir
1303 /// [`is_file`]: FileType::is_file
1304 /// [`is_symlink`]: FileType::is_symlink
1311 /// fn main() -> std::io::Result<()> {
1312 /// let metadata = fs::symlink_metadata("foo.txt")?;
1313 /// let file_type = metadata.file_type();
1315 /// assert_eq!(file_type.is_symlink(), false);
1319 #[stable(feature = "file_type", since = "1.1.0")]
1320 pub fn is_symlink(&self) -> bool {
1325 impl AsInner<fs_imp::FileType> for FileType {
1326 fn as_inner(&self) -> &fs_imp::FileType {
1331 impl FromInner<fs_imp::FilePermissions> for Permissions {
1332 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1337 impl AsInner<fs_imp::FilePermissions> for Permissions {
1338 fn as_inner(&self) -> &fs_imp::FilePermissions {
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl Iterator for ReadDir {
1345 type Item = io::Result<DirEntry>;
1347 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1348 self.0.next().map(|entry| entry.map(DirEntry))
1353 /// Returns the full path to the file that this entry represents.
1355 /// The full path is created by joining the original path to `read_dir`
1356 /// with the filename of this entry.
1363 /// fn main() -> std::io::Result<()> {
1364 /// for entry in fs::read_dir(".")? {
1365 /// let dir = entry?;
1366 /// println!("{:?}", dir.path());
1372 /// This prints output like:
1375 /// "./whatever.txt"
1377 /// "./hello_world.rs"
1380 /// The exact text, of course, depends on what files you have in `.`.
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn path(&self) -> PathBuf {
1386 /// Returns the metadata for the file that this entry points at.
1388 /// This function will not traverse symlinks if this entry points at a
1389 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1391 /// [`fs::metadata`]: metadata
1392 /// [`fs::File::metadata`]: File::metadata
1394 /// # Platform-specific behavior
1396 /// On Windows this function is cheap to call (no extra system calls
1397 /// needed), but on Unix platforms this function is the equivalent of
1398 /// calling `symlink_metadata` on the path.
1405 /// if let Ok(entries) = fs::read_dir(".") {
1406 /// for entry in entries {
1407 /// if let Ok(entry) = entry {
1408 /// // Here, `entry` is a `DirEntry`.
1409 /// if let Ok(metadata) = entry.metadata() {
1410 /// // Now let's show our entry's permissions!
1411 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1413 /// println!("Couldn't get metadata for {:?}", entry.path());
1419 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1420 pub fn metadata(&self) -> io::Result<Metadata> {
1421 self.0.metadata().map(Metadata)
1424 /// Returns the file type for the file that this entry points at.
1426 /// This function will not traverse symlinks if this entry points at a
1429 /// # Platform-specific behavior
1431 /// On Windows and most Unix platforms this function is free (no extra
1432 /// system calls needed), but some Unix platforms may require the equivalent
1433 /// call to `symlink_metadata` to learn about the target file type.
1440 /// if let Ok(entries) = fs::read_dir(".") {
1441 /// for entry in entries {
1442 /// if let Ok(entry) = entry {
1443 /// // Here, `entry` is a `DirEntry`.
1444 /// if let Ok(file_type) = entry.file_type() {
1445 /// // Now let's show our entry's file type!
1446 /// println!("{:?}: {:?}", entry.path(), file_type);
1448 /// println!("Couldn't get file type for {:?}", entry.path());
1454 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1455 pub fn file_type(&self) -> io::Result<FileType> {
1456 self.0.file_type().map(FileType)
1459 /// Returns the bare file name of this directory entry without any other
1460 /// leading path component.
1467 /// if let Ok(entries) = fs::read_dir(".") {
1468 /// for entry in entries {
1469 /// if let Ok(entry) = entry {
1470 /// // Here, `entry` is a `DirEntry`.
1471 /// println!("{:?}", entry.file_name());
1476 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1477 pub fn file_name(&self) -> OsString {
1482 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1483 impl fmt::Debug for DirEntry {
1484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1485 f.debug_tuple("DirEntry").field(&self.path()).finish()
1489 impl AsInner<fs_imp::DirEntry> for DirEntry {
1490 fn as_inner(&self) -> &fs_imp::DirEntry {
1495 /// Removes a file from the filesystem.
1497 /// Note that there is no
1498 /// guarantee that the file is immediately deleted (e.g., depending on
1499 /// platform, other open file descriptors may prevent immediate removal).
1501 /// # Platform-specific behavior
1503 /// This function currently corresponds to the `unlink` function on Unix
1504 /// and the `DeleteFile` function on Windows.
1505 /// Note that, this [may change in the future][changes].
1507 /// [changes]: io#platform-specific-behavior
1511 /// This function will return an error in the following situations, but is not
1512 /// limited to just these cases:
1514 /// * `path` points to a directory.
1515 /// * The file doesn't exist.
1516 /// * The user lacks permissions to remove the file.
1523 /// fn main() -> std::io::Result<()> {
1524 /// fs::remove_file("a.txt")?;
1528 #[doc(alias = "delete")]
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1531 fs_imp::unlink(path.as_ref())
1534 /// Given a path, query the file system to get information about a file,
1537 /// This function will traverse symbolic links to query information about the
1538 /// destination file.
1540 /// # Platform-specific behavior
1542 /// This function currently corresponds to the `stat` function on Unix
1543 /// and the `GetFileAttributesEx` function on Windows.
1544 /// Note that, this [may change in the future][changes].
1546 /// [changes]: io#platform-specific-behavior
1550 /// This function will return an error in the following situations, but is not
1551 /// limited to just these cases:
1553 /// * The user lacks permissions to perform `metadata` call on `path`.
1554 /// * `path` does not exist.
1561 /// fn main() -> std::io::Result<()> {
1562 /// let attr = fs::metadata("/some/file/path.txt")?;
1563 /// // inspect attr ...
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1569 fs_imp::stat(path.as_ref()).map(Metadata)
1572 /// Query the metadata about a file without following symlinks.
1574 /// # Platform-specific behavior
1576 /// This function currently corresponds to the `lstat` function on Unix
1577 /// and the `GetFileAttributesEx` function on Windows.
1578 /// Note that, this [may change in the future][changes].
1580 /// [changes]: io#platform-specific-behavior
1584 /// This function will return an error in the following situations, but is not
1585 /// limited to just these cases:
1587 /// * The user lacks permissions to perform `metadata` call on `path`.
1588 /// * `path` does not exist.
1595 /// fn main() -> std::io::Result<()> {
1596 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1597 /// // inspect attr ...
1601 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1602 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1603 fs_imp::lstat(path.as_ref()).map(Metadata)
1606 /// Rename a file or directory to a new name, replacing the original file if
1607 /// `to` already exists.
1609 /// This will not work if the new name is on a different mount point.
1611 /// # Platform-specific behavior
1613 /// This function currently corresponds to the `rename` function on Unix
1614 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1616 /// Because of this, the behavior when both `from` and `to` exist differs. On
1617 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1618 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1619 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1621 /// Note that, this [may change in the future][changes].
1623 /// [changes]: io#platform-specific-behavior
1627 /// This function will return an error in the following situations, but is not
1628 /// limited to just these cases:
1630 /// * `from` does not exist.
1631 /// * The user lacks permissions to view contents.
1632 /// * `from` and `to` are on separate filesystems.
1639 /// fn main() -> std::io::Result<()> {
1640 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1646 fs_imp::rename(from.as_ref(), to.as_ref())
1649 /// Copies the contents of one file to another. This function will also
1650 /// copy the permission bits of the original file to the destination file.
1652 /// This function will **overwrite** the contents of `to`.
1654 /// Note that if `from` and `to` both point to the same file, then the file
1655 /// will likely get truncated by this operation.
1657 /// On success, the total number of bytes copied is returned and it is equal to
1658 /// the length of the `to` file as reported by `metadata`.
1660 /// If you’re wanting to copy the contents of one file to another and you’re
1661 /// working with [`File`]s, see the [`io::copy()`] function.
1663 /// # Platform-specific behavior
1665 /// This function currently corresponds to the `open` function in Unix
1666 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1667 /// `O_CLOEXEC` is set for returned file descriptors.
1668 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1669 /// NTFS streams are copied but only the size of the main stream is returned by
1670 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1672 /// Note that, this [may change in the future][changes].
1674 /// [changes]: io#platform-specific-behavior
1678 /// This function will return an error in the following situations, but is not
1679 /// limited to just these cases:
1681 /// * `from` is neither a regular file nor a symlink to a regular file.
1682 /// * `from` does not exist.
1683 /// * The current process does not have the permission rights to read
1684 /// `from` or write `to`.
1691 /// fn main() -> std::io::Result<()> {
1692 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1698 fs_imp::copy(from.as_ref(), to.as_ref())
1701 /// Creates a new hard link on the filesystem.
1703 /// The `link` path will be a link pointing to the `original` path. Note that
1704 /// systems often require these two paths to both be located on the same
1707 /// If `original` names a symbolic link, it is platform-specific whether the
1708 /// symbolic link is followed. On platforms where it's possible to not follow
1709 /// it, it is not followed, and the created hard link points to the symbolic
1712 /// # Platform-specific behavior
1714 /// This function currently corresponds to the `linkat` function with no flags
1715 /// on Unix and the `CreateHardLink` function on Windows.
1716 /// Note that, this [may change in the future][changes].
1718 /// [changes]: io#platform-specific-behavior
1722 /// This function will return an error in the following situations, but is not
1723 /// limited to just these cases:
1725 /// * The `original` path is not a file or doesn't exist.
1732 /// fn main() -> std::io::Result<()> {
1733 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1739 fs_imp::link(original.as_ref(), link.as_ref())
1742 /// Creates a new symbolic link on the filesystem.
1744 /// The `link` path will be a symbolic link pointing to the `original` path.
1745 /// On Windows, this will be a file symlink, not a directory symlink;
1746 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1747 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1748 /// used instead to make the intent explicit.
1750 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1751 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1752 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1759 /// fn main() -> std::io::Result<()> {
1760 /// fs::soft_link("a.txt", "b.txt")?;
1764 #[stable(feature = "rust1", since = "1.0.0")]
1767 reason = "replaced with std::os::unix::fs::symlink and \
1768 std::os::windows::fs::{symlink_file, symlink_dir}"
1770 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1771 fs_imp::symlink(original.as_ref(), link.as_ref())
1774 /// Reads a symbolic link, returning the file that the link points to.
1776 /// # Platform-specific behavior
1778 /// This function currently corresponds to the `readlink` function on Unix
1779 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1780 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1781 /// Note that, this [may change in the future][changes].
1783 /// [changes]: io#platform-specific-behavior
1787 /// This function will return an error in the following situations, but is not
1788 /// limited to just these cases:
1790 /// * `path` is not a symbolic link.
1791 /// * `path` does not exist.
1798 /// fn main() -> std::io::Result<()> {
1799 /// let path = fs::read_link("a.txt")?;
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1805 fs_imp::readlink(path.as_ref())
1808 /// Returns the canonical, absolute form of a path with all intermediate
1809 /// components normalized and symbolic links resolved.
1811 /// # Platform-specific behavior
1813 /// This function currently corresponds to the `realpath` function on Unix
1814 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1815 /// Note that, this [may change in the future][changes].
1817 /// On Windows, this converts the path to use [extended length path][path]
1818 /// syntax, which allows your program to use longer path names, but means you
1819 /// can only join backslash-delimited paths to it, and it may be incompatible
1820 /// with other applications (if passed to the application on the command-line,
1821 /// or written to a file another application may read).
1823 /// [changes]: io#platform-specific-behavior
1824 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1828 /// This function will return an error in the following situations, but is not
1829 /// limited to just these cases:
1831 /// * `path` does not exist.
1832 /// * A non-final component in path is not a directory.
1839 /// fn main() -> std::io::Result<()> {
1840 /// let path = fs::canonicalize("../a/../foo.txt")?;
1844 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1845 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1846 fs_imp::canonicalize(path.as_ref())
1849 /// Creates a new, empty directory at the provided path
1851 /// # Platform-specific behavior
1853 /// This function currently corresponds to the `mkdir` function on Unix
1854 /// and the `CreateDirectory` function on Windows.
1855 /// Note that, this [may change in the future][changes].
1857 /// [changes]: io#platform-specific-behavior
1859 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1860 /// return an error. To create a directory and all its missing parents at the
1861 /// same time, use the [`create_dir_all`] function.
1865 /// This function will return an error in the following situations, but is not
1866 /// limited to just these cases:
1868 /// * User lacks permissions to create directory at `path`.
1869 /// * A parent of the given path doesn't exist. (To create a directory and all
1870 /// its missing parents at the same time, use the [`create_dir_all`]
1872 /// * `path` already exists.
1879 /// fn main() -> std::io::Result<()> {
1880 /// fs::create_dir("/some/dir")?;
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1886 DirBuilder::new().create(path.as_ref())
1889 /// Recursively create a directory and all of its parent components if they
1892 /// # Platform-specific behavior
1894 /// This function currently corresponds to the `mkdir` function on Unix
1895 /// and the `CreateDirectory` function on Windows.
1896 /// Note that, this [may change in the future][changes].
1898 /// [changes]: io#platform-specific-behavior
1902 /// This function will return an error in the following situations, but is not
1903 /// limited to just these cases:
1905 /// * If any directory in the path specified by `path`
1906 /// does not already exist and it could not be created otherwise. The specific
1907 /// error conditions for when a directory is being created (after it is
1908 /// determined to not exist) are outlined by [`fs::create_dir`].
1910 /// Notable exception is made for situations where any of the directories
1911 /// specified in the `path` could not be created as it was being created concurrently.
1912 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1913 /// concurrently from multiple threads or processes is guaranteed not to fail
1914 /// due to a race condition with itself.
1916 /// [`fs::create_dir`]: create_dir
1923 /// fn main() -> std::io::Result<()> {
1924 /// fs::create_dir_all("/some/dir")?;
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1930 DirBuilder::new().recursive(true).create(path.as_ref())
1933 /// Removes an empty directory.
1935 /// # Platform-specific behavior
1937 /// This function currently corresponds to the `rmdir` function on Unix
1938 /// and the `RemoveDirectory` function on Windows.
1939 /// Note that, this [may change in the future][changes].
1941 /// [changes]: io#platform-specific-behavior
1945 /// This function will return an error in the following situations, but is not
1946 /// limited to just these cases:
1948 /// * `path` doesn't exist.
1949 /// * `path` isn't a directory.
1950 /// * The user lacks permissions to remove the directory at the provided `path`.
1951 /// * The directory isn't empty.
1958 /// fn main() -> std::io::Result<()> {
1959 /// fs::remove_dir("/some/dir")?;
1963 #[doc(alias = "delete")]
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1966 fs_imp::rmdir(path.as_ref())
1969 /// Removes a directory at this path, after removing all its contents. Use
1972 /// This function does **not** follow symbolic links and it will simply remove the
1973 /// symbolic link itself.
1975 /// # Platform-specific behavior
1977 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1978 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1980 /// Note that, this [may change in the future][changes].
1982 /// [changes]: io#platform-specific-behavior
1986 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1988 /// [`fs::remove_file`]: remove_file
1989 /// [`fs::remove_dir`]: remove_dir
1996 /// fn main() -> std::io::Result<()> {
1997 /// fs::remove_dir_all("/some/dir")?;
2001 #[doc(alias = "delete")]
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2004 fs_imp::remove_dir_all(path.as_ref())
2007 /// Returns an iterator over the entries within a directory.
2009 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2010 /// New errors may be encountered after an iterator is initially constructed.
2012 /// # Platform-specific behavior
2014 /// This function currently corresponds to the `opendir` function on Unix
2015 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2016 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2017 /// Note that, this [may change in the future][changes].
2019 /// [changes]: io#platform-specific-behavior
2021 /// The order in which this iterator returns entries is platform and filesystem
2026 /// This function will return an error in the following situations, but is not
2027 /// limited to just these cases:
2029 /// * The provided `path` doesn't exist.
2030 /// * The process lacks permissions to view the contents.
2031 /// * The `path` points at a non-directory file.
2037 /// use std::fs::{self, DirEntry};
2038 /// use std::path::Path;
2040 /// // one possible implementation of walking a directory only visiting files
2041 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2042 /// if dir.is_dir() {
2043 /// for entry in fs::read_dir(dir)? {
2044 /// let entry = entry?;
2045 /// let path = entry.path();
2046 /// if path.is_dir() {
2047 /// visit_dirs(&path, cb)?;
2058 /// use std::{fs, io};
2060 /// fn main() -> io::Result<()> {
2061 /// let mut entries = fs::read_dir(".")?
2062 /// .map(|res| res.map(|e| e.path()))
2063 /// .collect::<Result<Vec<_>, io::Error>>()?;
2065 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2066 /// // ordering is required the entries should be explicitly sorted.
2070 /// // The entries have now been sorted by their path.
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2077 fs_imp::readdir(path.as_ref()).map(ReadDir)
2080 /// Changes the permissions found on a file or a directory.
2082 /// # Platform-specific behavior
2084 /// This function currently corresponds to the `chmod` function on Unix
2085 /// and the `SetFileAttributes` function on Windows.
2086 /// Note that, this [may change in the future][changes].
2088 /// [changes]: io#platform-specific-behavior
2092 /// This function will return an error in the following situations, but is not
2093 /// limited to just these cases:
2095 /// * `path` does not exist.
2096 /// * The user lacks the permission to change attributes of the file.
2103 /// fn main() -> std::io::Result<()> {
2104 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2105 /// perms.set_readonly(true);
2106 /// fs::set_permissions("foo.txt", perms)?;
2110 #[stable(feature = "set_permissions", since = "1.1.0")]
2111 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2112 fs_imp::set_perm(path.as_ref(), perm.0)
2116 /// Creates a new set of options with default mode/security settings for all
2117 /// platforms and also non-recursive.
2122 /// use std::fs::DirBuilder;
2124 /// let builder = DirBuilder::new();
2126 #[stable(feature = "dir_builder", since = "1.6.0")]
2127 pub fn new() -> DirBuilder {
2128 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2131 /// Indicates that directories should be created recursively, creating all
2132 /// parent directories. Parents that do not exist are created with the same
2133 /// security and permissions settings.
2135 /// This option defaults to `false`.
2140 /// use std::fs::DirBuilder;
2142 /// let mut builder = DirBuilder::new();
2143 /// builder.recursive(true);
2145 #[stable(feature = "dir_builder", since = "1.6.0")]
2146 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2147 self.recursive = recursive;
2151 /// Creates the specified directory with the options configured in this
2154 /// It is considered an error if the directory already exists unless
2155 /// recursive mode is enabled.
2160 /// use std::fs::{self, DirBuilder};
2162 /// let path = "/tmp/foo/bar/baz";
2163 /// DirBuilder::new()
2164 /// .recursive(true)
2165 /// .create(path).unwrap();
2167 /// assert!(fs::metadata(path).unwrap().is_dir());
2169 #[stable(feature = "dir_builder", since = "1.6.0")]
2170 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2171 self._create(path.as_ref())
2174 fn _create(&self, path: &Path) -> io::Result<()> {
2175 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2178 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2179 if path == Path::new("") {
2183 match self.inner.mkdir(path) {
2184 Ok(()) => return Ok(()),
2185 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2186 Err(_) if path.is_dir() => return Ok(()),
2187 Err(e) => return Err(e),
2189 match path.parent() {
2190 Some(p) => self.create_dir_all(p)?,
2192 return Err(io::Error::new_const(
2193 io::ErrorKind::Uncategorized,
2194 &"failed to create whole tree",
2198 match self.inner.mkdir(path) {
2200 Err(_) if path.is_dir() => Ok(()),
2206 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2207 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2212 /// Returns `Ok(true)` if the path points at an existing entity.
2214 /// This function will traverse symbolic links to query information about the
2215 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2217 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2218 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2219 /// denied on some of the parent directories.)
2224 /// #![feature(path_try_exists)]
2227 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2228 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2230 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2232 #[unstable(feature = "path_try_exists", issue = "83186")]
2234 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2235 fs_imp::try_exists(path.as_ref())