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, especially the
884 /// [`Other`] kind might change to more specific kinds in the future.
886 /// * [`NotFound`]: The specified file does not exist and neither `create`
887 /// or `create_new` is set.
888 /// * [`NotFound`]: One of the directory components of the file path does
890 /// * [`PermissionDenied`]: The user lacks permission to get the specified
891 /// access rights for the file.
892 /// * [`PermissionDenied`]: The user lacks permission to open one of the
893 /// directory components of the specified path.
894 /// * [`AlreadyExists`]: `create_new` was specified and the file already
896 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
897 /// without write access, no access mode set, etc.).
898 /// * [`Other`]: One of the directory components of the specified file path
899 /// was not, in fact, a directory.
900 /// * [`Other`]: Filesystem-level errors: full disk, write permission
901 /// requested on a read-only file system, exceeded disk quota, too many
902 /// open files, too long filename, too many symbolic links in the
903 /// specified path (Unix-like systems only), etc.
908 /// use std::fs::OpenOptions;
910 /// let file = OpenOptions::new().read(true).open("foo.txt");
913 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
914 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
915 /// [`NotFound`]: io::ErrorKind::NotFound
916 /// [`Other`]: io::ErrorKind::Other
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 `true` if this metadata is for a symbolic link.
1014 #[cfg_attr(unix, doc = "```no_run")]
1015 #[cfg_attr(not(unix), doc = "```ignore")]
1016 /// #![feature(is_symlink)]
1018 /// use std::path::Path;
1019 /// use std::os::unix::fs::symlink;
1021 /// fn main() -> std::io::Result<()> {
1022 /// let link_path = Path::new("link");
1023 /// symlink("/origin_does_not_exists/", link_path)?;
1025 /// let metadata = fs::symlink_metadata(link_path)?;
1027 /// assert!(metadata.is_symlink());
1031 #[unstable(feature = "is_symlink", issue = "85748")]
1032 pub fn is_symlink(&self) -> bool {
1033 self.file_type().is_symlink()
1036 /// Returns the size of the file, in bytes, this metadata is for.
1043 /// fn main() -> std::io::Result<()> {
1044 /// let metadata = fs::metadata("foo.txt")?;
1046 /// assert_eq!(0, metadata.len());
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 pub fn len(&self) -> u64 {
1055 /// Returns the permissions of the file this metadata is for.
1062 /// fn main() -> std::io::Result<()> {
1063 /// let metadata = fs::metadata("foo.txt")?;
1065 /// assert!(!metadata.permissions().readonly());
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 pub fn permissions(&self) -> Permissions {
1071 Permissions(self.0.perm())
1074 /// Returns the last modification time listed in this metadata.
1076 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1077 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1081 /// This field may not be available on all platforms, and will return an
1082 /// `Err` on platforms where it is not available.
1089 /// fn main() -> std::io::Result<()> {
1090 /// let metadata = fs::metadata("foo.txt")?;
1092 /// if let Ok(time) = metadata.modified() {
1093 /// println!("{:?}", time);
1095 /// println!("Not supported on this platform");
1100 #[stable(feature = "fs_time", since = "1.10.0")]
1101 pub fn modified(&self) -> io::Result<SystemTime> {
1102 self.0.modified().map(FromInner::from_inner)
1105 /// Returns the last access time of this metadata.
1107 /// The returned value corresponds to the `atime` field of `stat` on Unix
1108 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1110 /// Note that not all platforms will keep this field update in a file's
1111 /// metadata, for example Windows has an option to disable updating this
1112 /// time when files are accessed and Linux similarly has `noatime`.
1116 /// This field may not be available on all platforms, and will return an
1117 /// `Err` on platforms where it is not available.
1124 /// fn main() -> std::io::Result<()> {
1125 /// let metadata = fs::metadata("foo.txt")?;
1127 /// if let Ok(time) = metadata.accessed() {
1128 /// println!("{:?}", time);
1130 /// println!("Not supported on this platform");
1135 #[stable(feature = "fs_time", since = "1.10.0")]
1136 pub fn accessed(&self) -> io::Result<SystemTime> {
1137 self.0.accessed().map(FromInner::from_inner)
1140 /// Returns the creation time listed in this metadata.
1142 /// The returned value corresponds to the `btime` field of `statx` on
1143 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1144 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1148 /// This field may not be available on all platforms, and will return an
1149 /// `Err` on platforms or filesystems where it is not available.
1156 /// fn main() -> std::io::Result<()> {
1157 /// let metadata = fs::metadata("foo.txt")?;
1159 /// if let Ok(time) = metadata.created() {
1160 /// println!("{:?}", time);
1162 /// println!("Not supported on this platform or filesystem");
1167 #[stable(feature = "fs_time", since = "1.10.0")]
1168 pub fn created(&self) -> io::Result<SystemTime> {
1169 self.0.created().map(FromInner::from_inner)
1173 #[stable(feature = "std_debug", since = "1.16.0")]
1174 impl fmt::Debug for Metadata {
1175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176 f.debug_struct("Metadata")
1177 .field("file_type", &self.file_type())
1178 .field("is_dir", &self.is_dir())
1179 .field("is_file", &self.is_file())
1180 .field("permissions", &self.permissions())
1181 .field("modified", &self.modified())
1182 .field("accessed", &self.accessed())
1183 .field("created", &self.created())
1184 .finish_non_exhaustive()
1188 impl AsInner<fs_imp::FileAttr> for Metadata {
1189 fn as_inner(&self) -> &fs_imp::FileAttr {
1194 impl FromInner<fs_imp::FileAttr> for Metadata {
1195 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1201 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1206 /// use std::fs::File;
1208 /// fn main() -> std::io::Result<()> {
1209 /// let mut f = File::create("foo.txt")?;
1210 /// let metadata = f.metadata()?;
1212 /// assert_eq!(false, metadata.permissions().readonly());
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 pub fn readonly(&self) -> bool {
1221 /// Modifies the readonly flag for this set of permissions. If the
1222 /// `readonly` argument is `true`, using the resulting `Permission` will
1223 /// update file permissions to forbid writing. Conversely, if it's `false`,
1224 /// using the resulting `Permission` will update file permissions to allow
1227 /// This operation does **not** modify the filesystem. To modify the
1228 /// filesystem use the [`set_permissions`] function.
1233 /// use std::fs::File;
1235 /// fn main() -> std::io::Result<()> {
1236 /// let f = File::create("foo.txt")?;
1237 /// let metadata = f.metadata()?;
1238 /// let mut permissions = metadata.permissions();
1240 /// permissions.set_readonly(true);
1242 /// // filesystem doesn't change
1243 /// assert_eq!(false, metadata.permissions().readonly());
1245 /// // just this particular `permissions`.
1246 /// assert_eq!(true, permissions.readonly());
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 pub fn set_readonly(&mut self, readonly: bool) {
1252 self.0.set_readonly(readonly)
1257 /// Tests whether this file type represents a directory. The
1258 /// result is mutually exclusive to the results of
1259 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1262 /// [`is_file`]: FileType::is_file
1263 /// [`is_symlink`]: FileType::is_symlink
1268 /// fn main() -> std::io::Result<()> {
1271 /// let metadata = fs::metadata("foo.txt")?;
1272 /// let file_type = metadata.file_type();
1274 /// assert_eq!(file_type.is_dir(), false);
1278 #[stable(feature = "file_type", since = "1.1.0")]
1279 pub fn is_dir(&self) -> bool {
1283 /// Tests whether this file type represents a regular file.
1284 /// The result is mutually exclusive to the results of
1285 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1288 /// When the goal is simply to read from (or write to) the source, the most
1289 /// reliable way to test the source can be read (or written to) is to open
1290 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1291 /// a Unix-like system for example. See [`File::open`] or
1292 /// [`OpenOptions::open`] for more information.
1294 /// [`is_dir`]: FileType::is_dir
1295 /// [`is_symlink`]: FileType::is_symlink
1300 /// fn main() -> std::io::Result<()> {
1303 /// let metadata = fs::metadata("foo.txt")?;
1304 /// let file_type = metadata.file_type();
1306 /// assert_eq!(file_type.is_file(), true);
1310 #[stable(feature = "file_type", since = "1.1.0")]
1311 pub fn is_file(&self) -> bool {
1315 /// Tests whether this file type represents a symbolic link.
1316 /// The result is mutually exclusive to the results of
1317 /// [`is_dir`] and [`is_file`]; only zero or one of these
1320 /// The underlying [`Metadata`] struct needs to be retrieved
1321 /// with the [`fs::symlink_metadata`] function and not the
1322 /// [`fs::metadata`] function. The [`fs::metadata`] function
1323 /// follows symbolic links, so [`is_symlink`] would always
1324 /// return `false` for the target file.
1326 /// [`fs::metadata`]: metadata
1327 /// [`fs::symlink_metadata`]: symlink_metadata
1328 /// [`is_dir`]: FileType::is_dir
1329 /// [`is_file`]: FileType::is_file
1330 /// [`is_symlink`]: FileType::is_symlink
1337 /// fn main() -> std::io::Result<()> {
1338 /// let metadata = fs::symlink_metadata("foo.txt")?;
1339 /// let file_type = metadata.file_type();
1341 /// assert_eq!(file_type.is_symlink(), false);
1345 #[stable(feature = "file_type", since = "1.1.0")]
1346 pub fn is_symlink(&self) -> bool {
1351 impl AsInner<fs_imp::FileType> for FileType {
1352 fn as_inner(&self) -> &fs_imp::FileType {
1357 impl FromInner<fs_imp::FilePermissions> for Permissions {
1358 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1363 impl AsInner<fs_imp::FilePermissions> for Permissions {
1364 fn as_inner(&self) -> &fs_imp::FilePermissions {
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl Iterator for ReadDir {
1371 type Item = io::Result<DirEntry>;
1373 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1374 self.0.next().map(|entry| entry.map(DirEntry))
1379 /// Returns the full path to the file that this entry represents.
1381 /// The full path is created by joining the original path to `read_dir`
1382 /// with the filename of this entry.
1389 /// fn main() -> std::io::Result<()> {
1390 /// for entry in fs::read_dir(".")? {
1391 /// let dir = entry?;
1392 /// println!("{:?}", dir.path());
1398 /// This prints output like:
1401 /// "./whatever.txt"
1403 /// "./hello_world.rs"
1406 /// The exact text, of course, depends on what files you have in `.`.
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn path(&self) -> PathBuf {
1412 /// Returns the metadata for the file that this entry points at.
1414 /// This function will not traverse symlinks if this entry points at a
1415 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1417 /// [`fs::metadata`]: metadata
1418 /// [`fs::File::metadata`]: File::metadata
1420 /// # Platform-specific behavior
1422 /// On Windows this function is cheap to call (no extra system calls
1423 /// needed), but on Unix platforms this function is the equivalent of
1424 /// calling `symlink_metadata` on the path.
1431 /// if let Ok(entries) = fs::read_dir(".") {
1432 /// for entry in entries {
1433 /// if let Ok(entry) = entry {
1434 /// // Here, `entry` is a `DirEntry`.
1435 /// if let Ok(metadata) = entry.metadata() {
1436 /// // Now let's show our entry's permissions!
1437 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1439 /// println!("Couldn't get metadata for {:?}", entry.path());
1445 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1446 pub fn metadata(&self) -> io::Result<Metadata> {
1447 self.0.metadata().map(Metadata)
1450 /// Returns the file type for the file that this entry points at.
1452 /// This function will not traverse symlinks if this entry points at a
1455 /// # Platform-specific behavior
1457 /// On Windows and most Unix platforms this function is free (no extra
1458 /// system calls needed), but some Unix platforms may require the equivalent
1459 /// call to `symlink_metadata` to learn about the target file type.
1466 /// if let Ok(entries) = fs::read_dir(".") {
1467 /// for entry in entries {
1468 /// if let Ok(entry) = entry {
1469 /// // Here, `entry` is a `DirEntry`.
1470 /// if let Ok(file_type) = entry.file_type() {
1471 /// // Now let's show our entry's file type!
1472 /// println!("{:?}: {:?}", entry.path(), file_type);
1474 /// println!("Couldn't get file type for {:?}", entry.path());
1480 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1481 pub fn file_type(&self) -> io::Result<FileType> {
1482 self.0.file_type().map(FileType)
1485 /// Returns the bare file name of this directory entry without any other
1486 /// leading path component.
1493 /// if let Ok(entries) = fs::read_dir(".") {
1494 /// for entry in entries {
1495 /// if let Ok(entry) = entry {
1496 /// // Here, `entry` is a `DirEntry`.
1497 /// println!("{:?}", entry.file_name());
1502 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1503 pub fn file_name(&self) -> OsString {
1508 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1509 impl fmt::Debug for DirEntry {
1510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1511 f.debug_tuple("DirEntry").field(&self.path()).finish()
1515 impl AsInner<fs_imp::DirEntry> for DirEntry {
1516 fn as_inner(&self) -> &fs_imp::DirEntry {
1521 /// Removes a file from the filesystem.
1523 /// Note that there is no
1524 /// guarantee that the file is immediately deleted (e.g., depending on
1525 /// platform, other open file descriptors may prevent immediate removal).
1527 /// # Platform-specific behavior
1529 /// This function currently corresponds to the `unlink` function on Unix
1530 /// and the `DeleteFile` function on Windows.
1531 /// Note that, this [may change in the future][changes].
1533 /// [changes]: io#platform-specific-behavior
1537 /// This function will return an error in the following situations, but is not
1538 /// limited to just these cases:
1540 /// * `path` points to a directory.
1541 /// * The file doesn't exist.
1542 /// * The user lacks permissions to remove the file.
1549 /// fn main() -> std::io::Result<()> {
1550 /// fs::remove_file("a.txt")?;
1554 #[doc(alias = "delete")]
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1557 fs_imp::unlink(path.as_ref())
1560 /// Given a path, query the file system to get information about a file,
1563 /// This function will traverse symbolic links to query information about the
1564 /// destination file.
1566 /// # Platform-specific behavior
1568 /// This function currently corresponds to the `stat` function on Unix
1569 /// and the `GetFileAttributesEx` function on Windows.
1570 /// Note that, this [may change in the future][changes].
1572 /// [changes]: io#platform-specific-behavior
1576 /// This function will return an error in the following situations, but is not
1577 /// limited to just these cases:
1579 /// * The user lacks permissions to perform `metadata` call on `path`.
1580 /// * `path` does not exist.
1587 /// fn main() -> std::io::Result<()> {
1588 /// let attr = fs::metadata("/some/file/path.txt")?;
1589 /// // inspect attr ...
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1595 fs_imp::stat(path.as_ref()).map(Metadata)
1598 /// Query the metadata about a file without following symlinks.
1600 /// # Platform-specific behavior
1602 /// This function currently corresponds to the `lstat` function on Unix
1603 /// and the `GetFileAttributesEx` function on Windows.
1604 /// Note that, this [may change in the future][changes].
1606 /// [changes]: io#platform-specific-behavior
1610 /// This function will return an error in the following situations, but is not
1611 /// limited to just these cases:
1613 /// * The user lacks permissions to perform `metadata` call on `path`.
1614 /// * `path` does not exist.
1621 /// fn main() -> std::io::Result<()> {
1622 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1623 /// // inspect attr ...
1627 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1628 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1629 fs_imp::lstat(path.as_ref()).map(Metadata)
1632 /// Rename a file or directory to a new name, replacing the original file if
1633 /// `to` already exists.
1635 /// This will not work if the new name is on a different mount point.
1637 /// # Platform-specific behavior
1639 /// This function currently corresponds to the `rename` function on Unix
1640 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1642 /// Because of this, the behavior when both `from` and `to` exist differs. On
1643 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1644 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1645 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1647 /// Note that, this [may change in the future][changes].
1649 /// [changes]: io#platform-specific-behavior
1653 /// This function will return an error in the following situations, but is not
1654 /// limited to just these cases:
1656 /// * `from` does not exist.
1657 /// * The user lacks permissions to view contents.
1658 /// * `from` and `to` are on separate filesystems.
1665 /// fn main() -> std::io::Result<()> {
1666 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1672 fs_imp::rename(from.as_ref(), to.as_ref())
1675 /// Copies the contents of one file to another. This function will also
1676 /// copy the permission bits of the original file to the destination file.
1678 /// This function will **overwrite** the contents of `to`.
1680 /// Note that if `from` and `to` both point to the same file, then the file
1681 /// will likely get truncated by this operation.
1683 /// On success, the total number of bytes copied is returned and it is equal to
1684 /// the length of the `to` file as reported by `metadata`.
1686 /// If you’re wanting to copy the contents of one file to another and you’re
1687 /// working with [`File`]s, see the [`io::copy()`] function.
1689 /// # Platform-specific behavior
1691 /// This function currently corresponds to the `open` function in Unix
1692 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1693 /// `O_CLOEXEC` is set for returned file descriptors.
1694 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1695 /// NTFS streams are copied but only the size of the main stream is returned by
1696 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1698 /// Note that, this [may change in the future][changes].
1700 /// [changes]: io#platform-specific-behavior
1704 /// This function will return an error in the following situations, but is not
1705 /// limited to just these cases:
1707 /// * `from` is neither a regular file nor a symlink to a regular file.
1708 /// * `from` does not exist.
1709 /// * The current process does not have the permission rights to read
1710 /// `from` or write `to`.
1717 /// fn main() -> std::io::Result<()> {
1718 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1724 fs_imp::copy(from.as_ref(), to.as_ref())
1727 /// Creates a new hard link on the filesystem.
1729 /// The `link` path will be a link pointing to the `original` path. Note that
1730 /// systems often require these two paths to both be located on the same
1733 /// If `original` names a symbolic link, it is platform-specific whether the
1734 /// symbolic link is followed. On platforms where it's possible to not follow
1735 /// it, it is not followed, and the created hard link points to the symbolic
1738 /// # Platform-specific behavior
1740 /// This function currently corresponds to the `linkat` function with no flags
1741 /// on Unix and the `CreateHardLink` function on Windows.
1742 /// Note that, this [may change in the future][changes].
1744 /// [changes]: io#platform-specific-behavior
1748 /// This function will return an error in the following situations, but is not
1749 /// limited to just these cases:
1751 /// * The `original` path is not a file or doesn't exist.
1758 /// fn main() -> std::io::Result<()> {
1759 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1765 fs_imp::link(original.as_ref(), link.as_ref())
1768 /// Creates a new symbolic link on the filesystem.
1770 /// The `link` path will be a symbolic link pointing to the `original` path.
1771 /// On Windows, this will be a file symlink, not a directory symlink;
1772 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1773 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1774 /// used instead to make the intent explicit.
1776 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1777 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1778 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1785 /// fn main() -> std::io::Result<()> {
1786 /// fs::soft_link("a.txt", "b.txt")?;
1790 #[stable(feature = "rust1", since = "1.0.0")]
1793 reason = "replaced with std::os::unix::fs::symlink and \
1794 std::os::windows::fs::{symlink_file, symlink_dir}"
1796 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1797 fs_imp::symlink(original.as_ref(), link.as_ref())
1800 /// Reads a symbolic link, returning the file that the link points to.
1802 /// # Platform-specific behavior
1804 /// This function currently corresponds to the `readlink` function on Unix
1805 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1806 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1807 /// Note that, this [may change in the future][changes].
1809 /// [changes]: io#platform-specific-behavior
1813 /// This function will return an error in the following situations, but is not
1814 /// limited to just these cases:
1816 /// * `path` is not a symbolic link.
1817 /// * `path` does not exist.
1824 /// fn main() -> std::io::Result<()> {
1825 /// let path = fs::read_link("a.txt")?;
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1831 fs_imp::readlink(path.as_ref())
1834 /// Returns the canonical, absolute form of a path with all intermediate
1835 /// components normalized and symbolic links resolved.
1837 /// # Platform-specific behavior
1839 /// This function currently corresponds to the `realpath` function on Unix
1840 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1841 /// Note that, this [may change in the future][changes].
1843 /// On Windows, this converts the path to use [extended length path][path]
1844 /// syntax, which allows your program to use longer path names, but means you
1845 /// can only join backslash-delimited paths to it, and it may be incompatible
1846 /// with other applications (if passed to the application on the command-line,
1847 /// or written to a file another application may read).
1849 /// [changes]: io#platform-specific-behavior
1850 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1854 /// This function will return an error in the following situations, but is not
1855 /// limited to just these cases:
1857 /// * `path` does not exist.
1858 /// * A non-final component in path is not a directory.
1865 /// fn main() -> std::io::Result<()> {
1866 /// let path = fs::canonicalize("../a/../foo.txt")?;
1870 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1871 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1872 fs_imp::canonicalize(path.as_ref())
1875 /// Creates a new, empty directory at the provided path
1877 /// # Platform-specific behavior
1879 /// This function currently corresponds to the `mkdir` function on Unix
1880 /// and the `CreateDirectory` function on Windows.
1881 /// Note that, this [may change in the future][changes].
1883 /// [changes]: io#platform-specific-behavior
1885 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1886 /// return an error. To create a directory and all its missing parents at the
1887 /// same time, use the [`create_dir_all`] function.
1891 /// This function will return an error in the following situations, but is not
1892 /// limited to just these cases:
1894 /// * User lacks permissions to create directory at `path`.
1895 /// * A parent of the given path doesn't exist. (To create a directory and all
1896 /// its missing parents at the same time, use the [`create_dir_all`]
1898 /// * `path` already exists.
1905 /// fn main() -> std::io::Result<()> {
1906 /// fs::create_dir("/some/dir")?;
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1912 DirBuilder::new().create(path.as_ref())
1915 /// Recursively create a directory and all of its parent components if they
1918 /// # Platform-specific behavior
1920 /// This function currently corresponds to the `mkdir` function on Unix
1921 /// and the `CreateDirectory` function on Windows.
1922 /// Note that, this [may change in the future][changes].
1924 /// [changes]: io#platform-specific-behavior
1928 /// This function will return an error in the following situations, but is not
1929 /// limited to just these cases:
1931 /// * If any directory in the path specified by `path`
1932 /// does not already exist and it could not be created otherwise. The specific
1933 /// error conditions for when a directory is being created (after it is
1934 /// determined to not exist) are outlined by [`fs::create_dir`].
1936 /// Notable exception is made for situations where any of the directories
1937 /// specified in the `path` could not be created as it was being created concurrently.
1938 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1939 /// concurrently from multiple threads or processes is guaranteed not to fail
1940 /// due to a race condition with itself.
1942 /// [`fs::create_dir`]: create_dir
1949 /// fn main() -> std::io::Result<()> {
1950 /// fs::create_dir_all("/some/dir")?;
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1956 DirBuilder::new().recursive(true).create(path.as_ref())
1959 /// Removes an empty directory.
1961 /// # Platform-specific behavior
1963 /// This function currently corresponds to the `rmdir` function on Unix
1964 /// and the `RemoveDirectory` function on Windows.
1965 /// Note that, this [may change in the future][changes].
1967 /// [changes]: io#platform-specific-behavior
1971 /// This function will return an error in the following situations, but is not
1972 /// limited to just these cases:
1974 /// * `path` doesn't exist.
1975 /// * `path` isn't a directory.
1976 /// * The user lacks permissions to remove the directory at the provided `path`.
1977 /// * The directory isn't empty.
1984 /// fn main() -> std::io::Result<()> {
1985 /// fs::remove_dir("/some/dir")?;
1989 #[doc(alias = "delete")]
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1992 fs_imp::rmdir(path.as_ref())
1995 /// Removes a directory at this path, after removing all its contents. Use
1998 /// This function does **not** follow symbolic links and it will simply remove the
1999 /// symbolic link itself.
2001 /// # Platform-specific behavior
2003 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2004 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2006 /// Note that, this [may change in the future][changes].
2008 /// [changes]: io#platform-specific-behavior
2012 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2014 /// [`fs::remove_file`]: remove_file
2015 /// [`fs::remove_dir`]: remove_dir
2022 /// fn main() -> std::io::Result<()> {
2023 /// fs::remove_dir_all("/some/dir")?;
2027 #[doc(alias = "delete")]
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2030 fs_imp::remove_dir_all(path.as_ref())
2033 /// Returns an iterator over the entries within a directory.
2035 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2036 /// New errors may be encountered after an iterator is initially constructed.
2038 /// # Platform-specific behavior
2040 /// This function currently corresponds to the `opendir` function on Unix
2041 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2042 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2043 /// Note that, this [may change in the future][changes].
2045 /// [changes]: io#platform-specific-behavior
2047 /// The order in which this iterator returns entries is platform and filesystem
2052 /// This function will return an error in the following situations, but is not
2053 /// limited to just these cases:
2055 /// * The provided `path` doesn't exist.
2056 /// * The process lacks permissions to view the contents.
2057 /// * The `path` points at a non-directory file.
2063 /// use std::fs::{self, DirEntry};
2064 /// use std::path::Path;
2066 /// // one possible implementation of walking a directory only visiting files
2067 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2068 /// if dir.is_dir() {
2069 /// for entry in fs::read_dir(dir)? {
2070 /// let entry = entry?;
2071 /// let path = entry.path();
2072 /// if path.is_dir() {
2073 /// visit_dirs(&path, cb)?;
2084 /// use std::{fs, io};
2086 /// fn main() -> io::Result<()> {
2087 /// let mut entries = fs::read_dir(".")?
2088 /// .map(|res| res.map(|e| e.path()))
2089 /// .collect::<Result<Vec<_>, io::Error>>()?;
2091 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2092 /// // ordering is required the entries should be explicitly sorted.
2096 /// // The entries have now been sorted by their path.
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2103 fs_imp::readdir(path.as_ref()).map(ReadDir)
2106 /// Changes the permissions found on a file or a directory.
2108 /// # Platform-specific behavior
2110 /// This function currently corresponds to the `chmod` function on Unix
2111 /// and the `SetFileAttributes` function on Windows.
2112 /// Note that, this [may change in the future][changes].
2114 /// [changes]: io#platform-specific-behavior
2118 /// This function will return an error in the following situations, but is not
2119 /// limited to just these cases:
2121 /// * `path` does not exist.
2122 /// * The user lacks the permission to change attributes of the file.
2129 /// fn main() -> std::io::Result<()> {
2130 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2131 /// perms.set_readonly(true);
2132 /// fs::set_permissions("foo.txt", perms)?;
2136 #[stable(feature = "set_permissions", since = "1.1.0")]
2137 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2138 fs_imp::set_perm(path.as_ref(), perm.0)
2142 /// Creates a new set of options with default mode/security settings for all
2143 /// platforms and also non-recursive.
2148 /// use std::fs::DirBuilder;
2150 /// let builder = DirBuilder::new();
2152 #[stable(feature = "dir_builder", since = "1.6.0")]
2153 pub fn new() -> DirBuilder {
2154 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2157 /// Indicates that directories should be created recursively, creating all
2158 /// parent directories. Parents that do not exist are created with the same
2159 /// security and permissions settings.
2161 /// This option defaults to `false`.
2166 /// use std::fs::DirBuilder;
2168 /// let mut builder = DirBuilder::new();
2169 /// builder.recursive(true);
2171 #[stable(feature = "dir_builder", since = "1.6.0")]
2172 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2173 self.recursive = recursive;
2177 /// Creates the specified directory with the options configured in this
2180 /// It is considered an error if the directory already exists unless
2181 /// recursive mode is enabled.
2186 /// use std::fs::{self, DirBuilder};
2188 /// let path = "/tmp/foo/bar/baz";
2189 /// DirBuilder::new()
2190 /// .recursive(true)
2191 /// .create(path).unwrap();
2193 /// assert!(fs::metadata(path).unwrap().is_dir());
2195 #[stable(feature = "dir_builder", since = "1.6.0")]
2196 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2197 self._create(path.as_ref())
2200 fn _create(&self, path: &Path) -> io::Result<()> {
2201 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2204 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2205 if path == Path::new("") {
2209 match self.inner.mkdir(path) {
2210 Ok(()) => return Ok(()),
2211 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2212 Err(_) if path.is_dir() => return Ok(()),
2213 Err(e) => return Err(e),
2215 match path.parent() {
2216 Some(p) => self.create_dir_all(p)?,
2218 return Err(io::Error::new_const(
2219 io::ErrorKind::Other,
2220 &"failed to create whole tree",
2224 match self.inner.mkdir(path) {
2226 Err(_) if path.is_dir() => Ok(()),
2232 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2233 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2238 /// Returns `Ok(true)` if the path points at an existing entity.
2240 /// This function will traverse symbolic links to query information about the
2241 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2243 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2244 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2245 /// denied on some of the parent directories.)
2250 /// #![feature(path_try_exists)]
2253 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2254 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2256 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2258 #[unstable(feature = "path_try_exists", issue = "83186")]
2260 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2261 fs_imp::try_exists(path.as_ref())