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")]
91 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
96 /// Metadata information about a file.
98 /// This structure is returned from the [`metadata`] or
99 /// [`symlink_metadata`] function or method and represents known
100 /// metadata about a file such as its permissions, size, modification
102 #[stable(feature = "rust1", since = "1.0.0")]
104 pub struct Metadata(fs_imp::FileAttr);
106 /// Iterator over the entries in a directory.
108 /// This iterator is returned from the [`read_dir`] function of this module and
109 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
110 /// information like the entry's path and possibly other metadata can be
113 /// The order in which this iterator returns entries is platform and filesystem
118 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
119 /// IO error during iteration.
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub struct ReadDir(fs_imp::ReadDir);
124 /// Entries returned by the [`ReadDir`] iterator.
126 /// An instance of `DirEntry` represents an entry inside of a directory on the
127 /// filesystem. Each entry can be inspected via methods to learn about the full
128 /// path or possibly other metadata through per-platform extension traits.
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub struct DirEntry(fs_imp::DirEntry);
132 /// Options and flags which can be used to configure how a file is opened.
134 /// This builder exposes the ability to configure how a [`File`] is opened and
135 /// what operations are permitted on the open file. The [`File::open`] and
136 /// [`File::create`] methods are aliases for commonly used options using this
139 /// Generally speaking, when using `OpenOptions`, you'll first call
140 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
141 /// call [`OpenOptions::open`], passing the path of the file you're trying to
142 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
143 /// can further operate on.
147 /// Opening a file to read:
150 /// use std::fs::OpenOptions;
152 /// let file = OpenOptions::new().read(true).open("foo.txt");
155 /// Opening a file for both reading and writing, as well as creating it if it
159 /// use std::fs::OpenOptions;
161 /// let file = OpenOptions::new()
165 /// .open("foo.txt");
167 #[derive(Clone, Debug)]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub struct OpenOptions(fs_imp::OpenOptions);
171 /// Representation of the various permissions on a file.
173 /// This module only currently provides one bit of information,
174 /// [`Permissions::readonly`], which is exposed on all currently supported
175 /// platforms. Unix-specific functionality, such as mode bits, is available
176 /// through the [`PermissionsExt`] trait.
178 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
179 #[derive(Clone, PartialEq, Eq, Debug)]
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub struct Permissions(fs_imp::FilePermissions);
183 /// A structure representing a type of file with accessors for each file type.
184 /// It is returned by [`Metadata::file_type`] method.
185 #[stable(feature = "file_type", since = "1.1.0")]
186 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
187 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
188 pub struct FileType(fs_imp::FileType);
190 /// A builder used to create directories in various manners.
192 /// This builder also supports platform-specific options.
193 #[stable(feature = "dir_builder", since = "1.6.0")]
194 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
196 pub struct DirBuilder {
197 inner: fs_imp::DirBuilder,
201 /// Indicates how large a buffer to pre-allocate before reading the entire file.
202 fn initial_buffer_size(file: &File) -> usize {
203 // Allocate one extra byte so the buffer doesn't need to grow before the
204 // final `read` call at the end of the file. Don't worry about `usize`
205 // overflow because reading will fail regardless in that case.
206 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
209 /// Read the entire contents of a file into a bytes vector.
211 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
212 /// with fewer imports and without an intermediate variable. It pre-allocates a
213 /// buffer based on the file size when available, so it is generally faster than
214 /// reading into a vector created with [`Vec::new()`].
216 /// [`read_to_end`]: Read::read_to_end
220 /// This function will return an error if `path` does not already exist.
221 /// Other errors may also be returned according to [`OpenOptions::open`].
223 /// It will also return an error if it encounters while reading an error
224 /// of a kind other than [`io::ErrorKind::Interrupted`].
230 /// use std::net::SocketAddr;
232 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
233 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
237 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
238 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
239 fn inner(path: &Path) -> io::Result<Vec<u8>> {
240 let mut file = File::open(path)?;
241 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
242 file.read_to_end(&mut bytes)?;
248 /// Read the entire contents of a file into a string.
250 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
251 /// with fewer imports and without an intermediate variable. It pre-allocates a
252 /// buffer based on the file size when available, so it is generally faster than
253 /// reading into a string created with [`String::new()`].
255 /// [`read_to_string`]: Read::read_to_string
259 /// This function will return an error if `path` does not already exist.
260 /// Other errors may also be returned according to [`OpenOptions::open`].
262 /// It will also return an error if it encounters while reading an error
263 /// of a kind other than [`io::ErrorKind::Interrupted`],
264 /// or if the contents of the file are not valid UTF-8.
270 /// use std::net::SocketAddr;
271 /// use std::error::Error;
273 /// fn main() -> Result<(), Box<dyn Error>> {
274 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
278 #[stable(feature = "fs_read_write", since = "1.26.0")]
279 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
280 fn inner(path: &Path) -> io::Result<String> {
281 let mut file = File::open(path)?;
282 let mut string = String::with_capacity(initial_buffer_size(&file));
283 file.read_to_string(&mut string)?;
289 /// Write a slice as the entire contents of a file.
291 /// This function will create a file if it does not exist,
292 /// and will entirely replace its contents if it does.
294 /// This is a convenience function for using [`File::create`] and [`write_all`]
295 /// with fewer imports.
297 /// [`write_all`]: Write::write_all
304 /// fn main() -> std::io::Result<()> {
305 /// fs::write("foo.txt", b"Lorem ipsum")?;
306 /// fs::write("bar.txt", "dolor sit")?;
310 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
311 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
312 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
313 File::create(path)?.write_all(contents)
315 inner(path.as_ref(), contents.as_ref())
319 /// Attempts to open a file in read-only mode.
321 /// See the [`OpenOptions::open`] method for more details.
325 /// This function will return an error if `path` does not already exist.
326 /// Other errors may also be returned according to [`OpenOptions::open`].
331 /// use std::fs::File;
333 /// fn main() -> std::io::Result<()> {
334 /// let mut f = File::open("foo.txt")?;
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
340 OpenOptions::new().read(true).open(path.as_ref())
343 /// Opens a file in write-only mode.
345 /// This function will create a file if it does not exist,
346 /// and will truncate it if it does.
348 /// See the [`OpenOptions::open`] function for more details.
353 /// use std::fs::File;
355 /// fn main() -> std::io::Result<()> {
356 /// let mut f = File::create("foo.txt")?;
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
362 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
365 /// Returns a new OpenOptions object.
367 /// This function returns a new OpenOptions object that you can use to
368 /// open or create a file with specific options if `open()` or `create()`
369 /// are not appropriate.
371 /// It is equivalent to `OpenOptions::new()` but allows you to write more
372 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
373 /// you can write `File::with_options().read(true).open("foo.txt")`. This
374 /// also avoids the need to import `OpenOptions`.
376 /// See the [`OpenOptions::new`] function for more details.
381 /// #![feature(with_options)]
382 /// use std::fs::File;
384 /// fn main() -> std::io::Result<()> {
385 /// let mut f = File::with_options().read(true).open("foo.txt")?;
389 #[unstable(feature = "with_options", issue = "65439")]
390 pub fn with_options() -> OpenOptions {
394 /// Attempts to sync all OS-internal metadata to disk.
396 /// This function will attempt to ensure that all in-memory data reaches the
397 /// filesystem before returning.
399 /// This can be used to handle errors that would otherwise only be caught
400 /// when the `File` is closed. Dropping a file will ignore errors in
401 /// synchronizing this in-memory data.
406 /// use std::fs::File;
407 /// use std::io::prelude::*;
409 /// fn main() -> std::io::Result<()> {
410 /// let mut f = File::create("foo.txt")?;
411 /// f.write_all(b"Hello, world!")?;
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn sync_all(&self) -> io::Result<()> {
422 /// This function is similar to [`sync_all`], except that it may not
423 /// synchronize file metadata to the filesystem.
425 /// This is intended for use cases that must synchronize content, but don't
426 /// need the metadata on disk. The goal of this method is to reduce disk
429 /// Note that some platforms may simply implement this in terms of
432 /// [`sync_all`]: File::sync_all
437 /// use std::fs::File;
438 /// use std::io::prelude::*;
440 /// fn main() -> std::io::Result<()> {
441 /// let mut f = File::create("foo.txt")?;
442 /// f.write_all(b"Hello, world!")?;
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn sync_data(&self) -> io::Result<()> {
450 self.inner.datasync()
453 /// Truncates or extends the underlying file, updating the size of
454 /// this file to become `size`.
456 /// If the `size` is less than the current file's size, then the file will
457 /// be shrunk. If it is greater than the current file's size, then the file
458 /// will be extended to `size` and have all of the intermediate data filled
461 /// The file's cursor isn't changed. In particular, if the cursor was at the
462 /// end and the file is shrunk using this operation, the cursor will now be
467 /// This function will return an error if the file is not opened for writing.
468 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
469 /// length would cause an overflow due to the implementation specifics.
474 /// use std::fs::File;
476 /// fn main() -> std::io::Result<()> {
477 /// let mut f = File::create("foo.txt")?;
483 /// Note that this method alters the content of the underlying file, even
484 /// though it takes `&self` rather than `&mut self`.
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn set_len(&self, size: u64) -> io::Result<()> {
487 self.inner.truncate(size)
490 /// Queries metadata about the underlying file.
495 /// use std::fs::File;
497 /// fn main() -> std::io::Result<()> {
498 /// let mut f = File::open("foo.txt")?;
499 /// let metadata = f.metadata()?;
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn metadata(&self) -> io::Result<Metadata> {
505 self.inner.file_attr().map(Metadata)
508 /// Creates a new `File` instance that shares the same underlying file handle
509 /// as the existing `File` instance. Reads, writes, and seeks will affect
510 /// both `File` instances simultaneously.
514 /// Creates two handles for a file named `foo.txt`:
517 /// use std::fs::File;
519 /// fn main() -> std::io::Result<()> {
520 /// let mut file = File::open("foo.txt")?;
521 /// let file_copy = file.try_clone()?;
526 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
527 /// two handles, seek one of them, and read the remaining bytes from the
531 /// use std::fs::File;
532 /// use std::io::SeekFrom;
533 /// use std::io::prelude::*;
535 /// fn main() -> std::io::Result<()> {
536 /// let mut file = File::open("foo.txt")?;
537 /// let mut file_copy = file.try_clone()?;
539 /// file.seek(SeekFrom::Start(3))?;
541 /// let mut contents = vec![];
542 /// file_copy.read_to_end(&mut contents)?;
543 /// assert_eq!(contents, b"def\n");
547 #[stable(feature = "file_try_clone", since = "1.9.0")]
548 pub fn try_clone(&self) -> io::Result<File> {
549 Ok(File { inner: self.inner.duplicate()? })
552 /// Changes the permissions on the underlying file.
554 /// # Platform-specific behavior
556 /// This function currently corresponds to the `fchmod` function on Unix and
557 /// the `SetFileInformationByHandle` function on Windows. Note that, this
558 /// [may change in the future][changes].
560 /// [changes]: io#platform-specific-behavior
564 /// This function will return an error if the user lacks permission change
565 /// attributes on the underlying file. It may also return an error in other
566 /// os-specific unspecified cases.
571 /// fn main() -> std::io::Result<()> {
572 /// use std::fs::File;
574 /// let file = File::open("foo.txt")?;
575 /// let mut perms = file.metadata()?.permissions();
576 /// perms.set_readonly(true);
577 /// file.set_permissions(perms)?;
582 /// Note that this method alters the permissions of the underlying file,
583 /// even though it takes `&self` rather than `&mut self`.
584 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
585 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
586 self.inner.set_permissions(perm.0)
590 impl AsInner<fs_imp::File> for File {
591 fn as_inner(&self) -> &fs_imp::File {
595 impl FromInner<fs_imp::File> for File {
596 fn from_inner(f: fs_imp::File) -> File {
600 impl IntoInner<fs_imp::File> for File {
601 fn into_inner(self) -> fs_imp::File {
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl fmt::Debug for File {
608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 #[stable(feature = "rust1", since = "1.0.0")]
615 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
619 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
620 self.inner.read_vectored(bufs)
624 fn is_read_vectored(&self) -> bool {
625 self.inner.is_read_vectored()
629 unsafe fn initializer(&self) -> Initializer {
630 // SAFETY: Read is guaranteed to work on uninitialized memory
631 unsafe { Initializer::nop() }
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl Write for File {
636 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
637 self.inner.write(buf)
640 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
641 self.inner.write_vectored(bufs)
645 fn is_write_vectored(&self) -> bool {
646 self.inner.is_write_vectored()
649 fn flush(&mut self) -> io::Result<()> {
653 #[stable(feature = "rust1", since = "1.0.0")]
655 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
659 #[stable(feature = "rust1", since = "1.0.0")]
660 impl Read for &File {
661 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
665 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
666 self.inner.read_vectored(bufs)
670 fn is_read_vectored(&self) -> bool {
671 self.inner.is_read_vectored()
675 unsafe fn initializer(&self) -> Initializer {
676 // SAFETY: Read is guaranteed to work on uninitialized memory
677 unsafe { Initializer::nop() }
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl Write for &File {
682 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
683 self.inner.write(buf)
686 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
687 self.inner.write_vectored(bufs)
691 fn is_write_vectored(&self) -> bool {
692 self.inner.is_write_vectored()
695 fn flush(&mut self) -> io::Result<()> {
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl Seek for &File {
701 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
707 /// Creates a blank new set of options ready for configuration.
709 /// All options are initially set to `false`.
714 /// use std::fs::OpenOptions;
716 /// let mut options = OpenOptions::new();
717 /// let file = options.read(true).open("foo.txt");
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn new() -> Self {
721 OpenOptions(fs_imp::OpenOptions::new())
724 /// Sets the option for read access.
726 /// This option, when true, will indicate that the file should be
727 /// `read`-able if opened.
732 /// use std::fs::OpenOptions;
734 /// let file = OpenOptions::new().read(true).open("foo.txt");
736 #[stable(feature = "rust1", since = "1.0.0")]
737 pub fn read(&mut self, read: bool) -> &mut Self {
742 /// Sets the option for write access.
744 /// This option, when true, will indicate that the file should be
745 /// `write`-able if opened.
747 /// If the file already exists, any write calls on it will overwrite its
748 /// contents, without truncating it.
753 /// use std::fs::OpenOptions;
755 /// let file = OpenOptions::new().write(true).open("foo.txt");
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn write(&mut self, write: bool) -> &mut Self {
763 /// Sets the option for the append mode.
765 /// This option, when true, means that writes will append to a file instead
766 /// of overwriting previous contents.
767 /// Note that setting `.write(true).append(true)` has the same effect as
768 /// setting only `.append(true)`.
770 /// For most filesystems, the operating system guarantees that all writes are
771 /// atomic: no writes get mangled because another process writes at the same
774 /// One maybe obvious note when using append-mode: make sure that all data
775 /// that belongs together is written to the file in one operation. This
776 /// can be done by concatenating strings before passing them to [`write()`],
777 /// or using a buffered writer (with a buffer of adequate size),
778 /// and calling [`flush()`] when the message is complete.
780 /// If a file is opened with both read and append access, beware that after
781 /// opening, and after every write, the position for reading may be set at the
782 /// end of the file. So, before writing, save the current position (using
783 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
787 /// This function doesn't create the file if it doesn't exist. Use the
788 /// [`OpenOptions::create`] method to do so.
790 /// [`write()`]: Write::write
791 /// [`flush()`]: Write::flush
792 /// [`seek`]: Seek::seek
793 /// [`Current`]: SeekFrom::Current
798 /// use std::fs::OpenOptions;
800 /// let file = OpenOptions::new().append(true).open("foo.txt");
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn append(&mut self, append: bool) -> &mut Self {
804 self.0.append(append);
808 /// Sets the option for truncating a previous file.
810 /// If a file is successfully opened with this option set it will truncate
811 /// the file to 0 length if it already exists.
813 /// The file must be opened with write access for truncate to work.
818 /// use std::fs::OpenOptions;
820 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
822 #[stable(feature = "rust1", since = "1.0.0")]
823 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
824 self.0.truncate(truncate);
828 /// Sets the option to create a new file, or open it if it already exists.
830 /// In order for the file to be created, [`OpenOptions::write`] or
831 /// [`OpenOptions::append`] access must be used.
836 /// use std::fs::OpenOptions;
838 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
840 #[stable(feature = "rust1", since = "1.0.0")]
841 pub fn create(&mut self, create: bool) -> &mut Self {
842 self.0.create(create);
846 /// Sets the option to create a new file, failing if it already exists.
848 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
849 /// way, if the call succeeds, the file returned is guaranteed to be new.
851 /// This option is useful because it is atomic. Otherwise between checking
852 /// whether a file exists and creating a new one, the file may have been
853 /// created by another process (a TOCTOU race condition / attack).
855 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
858 /// The file must be opened with write or append access in order to create
861 /// [`.create()`]: OpenOptions::create
862 /// [`.truncate()`]: OpenOptions::truncate
867 /// use std::fs::OpenOptions;
869 /// let file = OpenOptions::new().write(true)
870 /// .create_new(true)
871 /// .open("foo.txt");
873 #[stable(feature = "expand_open_options2", since = "1.9.0")]
874 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
875 self.0.create_new(create_new);
879 /// Opens a file at `path` with the options specified by `self`.
883 /// This function will return an error under a number of different
884 /// circumstances. Some of these error conditions are listed here, together
885 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
886 /// part of the compatibility contract of the function.
888 /// * [`NotFound`]: The specified file does not exist and neither `create`
889 /// or `create_new` is set.
890 /// * [`NotFound`]: One of the directory components of the file path does
892 /// * [`PermissionDenied`]: The user lacks permission to get the specified
893 /// access rights for the file.
894 /// * [`PermissionDenied`]: The user lacks permission to open one of the
895 /// directory components of the specified path.
896 /// * [`AlreadyExists`]: `create_new` was specified and the file already
898 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
899 /// without write access, no access mode set, etc.).
901 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
902 /// * One of the directory components of the specified file path
903 /// was not, in fact, a directory.
904 /// * Filesystem-level errors: full disk, write permission
905 /// requested on a read-only file system, exceeded disk quota, too many
906 /// open files, too long filename, too many symbolic links in the
907 /// specified path (Unix-like systems only), etc.
912 /// use std::fs::OpenOptions;
914 /// let file = OpenOptions::new().read(true).open("foo.txt");
917 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
918 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
919 /// [`NotFound`]: io::ErrorKind::NotFound
920 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
921 #[stable(feature = "rust1", since = "1.0.0")]
922 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
923 self._open(path.as_ref())
926 fn _open(&self, path: &Path) -> io::Result<File> {
927 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
931 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
932 fn as_inner(&self) -> &fs_imp::OpenOptions {
937 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
938 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
944 /// Returns the file type for this metadata.
949 /// fn main() -> std::io::Result<()> {
952 /// let metadata = fs::metadata("foo.txt")?;
954 /// println!("{:?}", metadata.file_type());
958 #[stable(feature = "file_type", since = "1.1.0")]
959 pub fn file_type(&self) -> FileType {
960 FileType(self.0.file_type())
963 /// Returns `true` if this metadata is for a directory. The
964 /// result is mutually exclusive to the result of
965 /// [`Metadata::is_file`], and will be false for symlink metadata
966 /// obtained from [`symlink_metadata`].
971 /// fn main() -> std::io::Result<()> {
974 /// let metadata = fs::metadata("foo.txt")?;
976 /// assert!(!metadata.is_dir());
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn is_dir(&self) -> bool {
982 self.file_type().is_dir()
985 /// Returns `true` if this metadata is for a regular file. The
986 /// result is mutually exclusive to the result of
987 /// [`Metadata::is_dir`], and will be false for symlink metadata
988 /// obtained from [`symlink_metadata`].
990 /// When the goal is simply to read from (or write to) the source, the most
991 /// reliable way to test the source can be read (or written to) is to open
992 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
993 /// a Unix-like system for example. See [`File::open`] or
994 /// [`OpenOptions::open`] for more information.
1001 /// fn main() -> std::io::Result<()> {
1002 /// let metadata = fs::metadata("foo.txt")?;
1004 /// assert!(metadata.is_file());
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 pub fn is_file(&self) -> bool {
1010 self.file_type().is_file()
1013 /// Returns `true` if this metadata is for a symbolic link.
1017 #[cfg_attr(unix, doc = "```no_run")]
1018 #[cfg_attr(not(unix), doc = "```ignore")]
1019 /// #![feature(is_symlink)]
1021 /// use std::path::Path;
1022 /// use std::os::unix::fs::symlink;
1024 /// fn main() -> std::io::Result<()> {
1025 /// let link_path = Path::new("link");
1026 /// symlink("/origin_does_not_exists/", link_path)?;
1028 /// let metadata = fs::symlink_metadata(link_path)?;
1030 /// assert!(metadata.is_symlink());
1034 #[unstable(feature = "is_symlink", issue = "85748")]
1035 pub fn is_symlink(&self) -> bool {
1036 self.file_type().is_symlink()
1039 /// Returns the size of the file, in bytes, this metadata is for.
1046 /// fn main() -> std::io::Result<()> {
1047 /// let metadata = fs::metadata("foo.txt")?;
1049 /// assert_eq!(0, metadata.len());
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub fn len(&self) -> u64 {
1058 /// Returns the permissions of the file this metadata is for.
1065 /// fn main() -> std::io::Result<()> {
1066 /// let metadata = fs::metadata("foo.txt")?;
1068 /// assert!(!metadata.permissions().readonly());
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn permissions(&self) -> Permissions {
1074 Permissions(self.0.perm())
1077 /// Returns the last modification time listed in this metadata.
1079 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1080 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1084 /// This field may not be available on all platforms, and will return an
1085 /// `Err` on platforms where it is not available.
1092 /// fn main() -> std::io::Result<()> {
1093 /// let metadata = fs::metadata("foo.txt")?;
1095 /// if let Ok(time) = metadata.modified() {
1096 /// println!("{:?}", time);
1098 /// println!("Not supported on this platform");
1103 #[stable(feature = "fs_time", since = "1.10.0")]
1104 pub fn modified(&self) -> io::Result<SystemTime> {
1105 self.0.modified().map(FromInner::from_inner)
1108 /// Returns the last access time of this metadata.
1110 /// The returned value corresponds to the `atime` field of `stat` on Unix
1111 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1113 /// Note that not all platforms will keep this field update in a file's
1114 /// metadata, for example Windows has an option to disable updating this
1115 /// time when files are accessed and Linux similarly has `noatime`.
1119 /// This field may not be available on all platforms, and will return an
1120 /// `Err` on platforms where it is not available.
1127 /// fn main() -> std::io::Result<()> {
1128 /// let metadata = fs::metadata("foo.txt")?;
1130 /// if let Ok(time) = metadata.accessed() {
1131 /// println!("{:?}", time);
1133 /// println!("Not supported on this platform");
1138 #[stable(feature = "fs_time", since = "1.10.0")]
1139 pub fn accessed(&self) -> io::Result<SystemTime> {
1140 self.0.accessed().map(FromInner::from_inner)
1143 /// Returns the creation time listed in this metadata.
1145 /// The returned value corresponds to the `btime` field of `statx` on
1146 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1147 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1151 /// This field may not be available on all platforms, and will return an
1152 /// `Err` on platforms or filesystems where it is not available.
1159 /// fn main() -> std::io::Result<()> {
1160 /// let metadata = fs::metadata("foo.txt")?;
1162 /// if let Ok(time) = metadata.created() {
1163 /// println!("{:?}", time);
1165 /// println!("Not supported on this platform or filesystem");
1170 #[stable(feature = "fs_time", since = "1.10.0")]
1171 pub fn created(&self) -> io::Result<SystemTime> {
1172 self.0.created().map(FromInner::from_inner)
1176 #[stable(feature = "std_debug", since = "1.16.0")]
1177 impl fmt::Debug for Metadata {
1178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1179 f.debug_struct("Metadata")
1180 .field("file_type", &self.file_type())
1181 .field("is_dir", &self.is_dir())
1182 .field("is_file", &self.is_file())
1183 .field("permissions", &self.permissions())
1184 .field("modified", &self.modified())
1185 .field("accessed", &self.accessed())
1186 .field("created", &self.created())
1187 .finish_non_exhaustive()
1191 impl AsInner<fs_imp::FileAttr> for Metadata {
1192 fn as_inner(&self) -> &fs_imp::FileAttr {
1197 impl FromInner<fs_imp::FileAttr> for Metadata {
1198 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1204 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1209 /// use std::fs::File;
1211 /// fn main() -> std::io::Result<()> {
1212 /// let mut f = File::create("foo.txt")?;
1213 /// let metadata = f.metadata()?;
1215 /// assert_eq!(false, metadata.permissions().readonly());
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub fn readonly(&self) -> bool {
1224 /// Modifies the readonly flag for this set of permissions. If the
1225 /// `readonly` argument is `true`, using the resulting `Permission` will
1226 /// update file permissions to forbid writing. Conversely, if it's `false`,
1227 /// using the resulting `Permission` will update file permissions to allow
1230 /// This operation does **not** modify the filesystem. To modify the
1231 /// filesystem use the [`set_permissions`] function.
1236 /// use std::fs::File;
1238 /// fn main() -> std::io::Result<()> {
1239 /// let f = File::create("foo.txt")?;
1240 /// let metadata = f.metadata()?;
1241 /// let mut permissions = metadata.permissions();
1243 /// permissions.set_readonly(true);
1245 /// // filesystem doesn't change
1246 /// assert_eq!(false, metadata.permissions().readonly());
1248 /// // just this particular `permissions`.
1249 /// assert_eq!(true, permissions.readonly());
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 pub fn set_readonly(&mut self, readonly: bool) {
1255 self.0.set_readonly(readonly)
1260 /// Tests whether this file type represents a directory. The
1261 /// result is mutually exclusive to the results of
1262 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1265 /// [`is_file`]: FileType::is_file
1266 /// [`is_symlink`]: FileType::is_symlink
1271 /// fn main() -> std::io::Result<()> {
1274 /// let metadata = fs::metadata("foo.txt")?;
1275 /// let file_type = metadata.file_type();
1277 /// assert_eq!(file_type.is_dir(), false);
1281 #[stable(feature = "file_type", since = "1.1.0")]
1282 pub fn is_dir(&self) -> bool {
1286 /// Tests whether this file type represents a regular file.
1287 /// The result is mutually exclusive to the results of
1288 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1291 /// When the goal is simply to read from (or write to) the source, the most
1292 /// reliable way to test the source can be read (or written to) is to open
1293 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1294 /// a Unix-like system for example. See [`File::open`] or
1295 /// [`OpenOptions::open`] for more information.
1297 /// [`is_dir`]: FileType::is_dir
1298 /// [`is_symlink`]: FileType::is_symlink
1303 /// fn main() -> std::io::Result<()> {
1306 /// let metadata = fs::metadata("foo.txt")?;
1307 /// let file_type = metadata.file_type();
1309 /// assert_eq!(file_type.is_file(), true);
1313 #[stable(feature = "file_type", since = "1.1.0")]
1314 pub fn is_file(&self) -> bool {
1318 /// Tests whether this file type represents a symbolic link.
1319 /// The result is mutually exclusive to the results of
1320 /// [`is_dir`] and [`is_file`]; only zero or one of these
1323 /// The underlying [`Metadata`] struct needs to be retrieved
1324 /// with the [`fs::symlink_metadata`] function and not the
1325 /// [`fs::metadata`] function. The [`fs::metadata`] function
1326 /// follows symbolic links, so [`is_symlink`] would always
1327 /// return `false` for the target file.
1329 /// [`fs::metadata`]: metadata
1330 /// [`fs::symlink_metadata`]: symlink_metadata
1331 /// [`is_dir`]: FileType::is_dir
1332 /// [`is_file`]: FileType::is_file
1333 /// [`is_symlink`]: FileType::is_symlink
1340 /// fn main() -> std::io::Result<()> {
1341 /// let metadata = fs::symlink_metadata("foo.txt")?;
1342 /// let file_type = metadata.file_type();
1344 /// assert_eq!(file_type.is_symlink(), false);
1348 #[stable(feature = "file_type", since = "1.1.0")]
1349 pub fn is_symlink(&self) -> bool {
1354 impl AsInner<fs_imp::FileType> for FileType {
1355 fn as_inner(&self) -> &fs_imp::FileType {
1360 impl FromInner<fs_imp::FilePermissions> for Permissions {
1361 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1366 impl AsInner<fs_imp::FilePermissions> for Permissions {
1367 fn as_inner(&self) -> &fs_imp::FilePermissions {
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl Iterator for ReadDir {
1374 type Item = io::Result<DirEntry>;
1376 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1377 self.0.next().map(|entry| entry.map(DirEntry))
1382 /// Returns the full path to the file that this entry represents.
1384 /// The full path is created by joining the original path to `read_dir`
1385 /// with the filename of this entry.
1392 /// fn main() -> std::io::Result<()> {
1393 /// for entry in fs::read_dir(".")? {
1394 /// let dir = entry?;
1395 /// println!("{:?}", dir.path());
1401 /// This prints output like:
1404 /// "./whatever.txt"
1406 /// "./hello_world.rs"
1409 /// The exact text, of course, depends on what files you have in `.`.
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 pub fn path(&self) -> PathBuf {
1415 /// Returns the metadata for the file that this entry points at.
1417 /// This function will not traverse symlinks if this entry points at a
1418 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1420 /// [`fs::metadata`]: metadata
1421 /// [`fs::File::metadata`]: File::metadata
1423 /// # Platform-specific behavior
1425 /// On Windows this function is cheap to call (no extra system calls
1426 /// needed), but on Unix platforms this function is the equivalent of
1427 /// calling `symlink_metadata` on the path.
1434 /// if let Ok(entries) = fs::read_dir(".") {
1435 /// for entry in entries {
1436 /// if let Ok(entry) = entry {
1437 /// // Here, `entry` is a `DirEntry`.
1438 /// if let Ok(metadata) = entry.metadata() {
1439 /// // Now let's show our entry's permissions!
1440 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1442 /// println!("Couldn't get metadata for {:?}", entry.path());
1448 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1449 pub fn metadata(&self) -> io::Result<Metadata> {
1450 self.0.metadata().map(Metadata)
1453 /// Returns the file type for the file that this entry points at.
1455 /// This function will not traverse symlinks if this entry points at a
1458 /// # Platform-specific behavior
1460 /// On Windows and most Unix platforms this function is free (no extra
1461 /// system calls needed), but some Unix platforms may require the equivalent
1462 /// call to `symlink_metadata` to learn about the target file type.
1469 /// if let Ok(entries) = fs::read_dir(".") {
1470 /// for entry in entries {
1471 /// if let Ok(entry) = entry {
1472 /// // Here, `entry` is a `DirEntry`.
1473 /// if let Ok(file_type) = entry.file_type() {
1474 /// // Now let's show our entry's file type!
1475 /// println!("{:?}: {:?}", entry.path(), file_type);
1477 /// println!("Couldn't get file type for {:?}", entry.path());
1483 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1484 pub fn file_type(&self) -> io::Result<FileType> {
1485 self.0.file_type().map(FileType)
1488 /// Returns the bare file name of this directory entry without any other
1489 /// leading path component.
1496 /// if let Ok(entries) = fs::read_dir(".") {
1497 /// for entry in entries {
1498 /// if let Ok(entry) = entry {
1499 /// // Here, `entry` is a `DirEntry`.
1500 /// println!("{:?}", entry.file_name());
1505 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1506 pub fn file_name(&self) -> OsString {
1511 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1512 impl fmt::Debug for DirEntry {
1513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514 f.debug_tuple("DirEntry").field(&self.path()).finish()
1518 impl AsInner<fs_imp::DirEntry> for DirEntry {
1519 fn as_inner(&self) -> &fs_imp::DirEntry {
1524 /// Removes a file from the filesystem.
1526 /// Note that there is no
1527 /// guarantee that the file is immediately deleted (e.g., depending on
1528 /// platform, other open file descriptors may prevent immediate removal).
1530 /// # Platform-specific behavior
1532 /// This function currently corresponds to the `unlink` function on Unix
1533 /// and the `DeleteFile` function on Windows.
1534 /// Note that, this [may change in the future][changes].
1536 /// [changes]: io#platform-specific-behavior
1540 /// This function will return an error in the following situations, but is not
1541 /// limited to just these cases:
1543 /// * `path` points to a directory.
1544 /// * The file doesn't exist.
1545 /// * The user lacks permissions to remove the file.
1552 /// fn main() -> std::io::Result<()> {
1553 /// fs::remove_file("a.txt")?;
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1559 fs_imp::unlink(path.as_ref())
1562 /// Given a path, query the file system to get information about a file,
1565 /// This function will traverse symbolic links to query information about the
1566 /// destination file.
1568 /// # Platform-specific behavior
1570 /// This function currently corresponds to the `stat` function on Unix
1571 /// and the `GetFileAttributesEx` function on Windows.
1572 /// Note that, this [may change in the future][changes].
1574 /// [changes]: io#platform-specific-behavior
1578 /// This function will return an error in the following situations, but is not
1579 /// limited to just these cases:
1581 /// * The user lacks permissions to perform `metadata` call on `path`.
1582 /// * `path` does not exist.
1589 /// fn main() -> std::io::Result<()> {
1590 /// let attr = fs::metadata("/some/file/path.txt")?;
1591 /// // inspect attr ...
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1597 fs_imp::stat(path.as_ref()).map(Metadata)
1600 /// Query the metadata about a file without following symlinks.
1602 /// # Platform-specific behavior
1604 /// This function currently corresponds to the `lstat` function on Unix
1605 /// and the `GetFileAttributesEx` function on Windows.
1606 /// Note that, this [may change in the future][changes].
1608 /// [changes]: io#platform-specific-behavior
1612 /// This function will return an error in the following situations, but is not
1613 /// limited to just these cases:
1615 /// * The user lacks permissions to perform `metadata` call on `path`.
1616 /// * `path` does not exist.
1623 /// fn main() -> std::io::Result<()> {
1624 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1625 /// // inspect attr ...
1629 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1630 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1631 fs_imp::lstat(path.as_ref()).map(Metadata)
1634 /// Rename a file or directory to a new name, replacing the original file if
1635 /// `to` already exists.
1637 /// This will not work if the new name is on a different mount point.
1639 /// # Platform-specific behavior
1641 /// This function currently corresponds to the `rename` function on Unix
1642 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1644 /// Because of this, the behavior when both `from` and `to` exist differs. On
1645 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1646 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1647 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1649 /// Note that, this [may change in the future][changes].
1651 /// [changes]: io#platform-specific-behavior
1655 /// This function will return an error in the following situations, but is not
1656 /// limited to just these cases:
1658 /// * `from` does not exist.
1659 /// * The user lacks permissions to view contents.
1660 /// * `from` and `to` are on separate filesystems.
1667 /// fn main() -> std::io::Result<()> {
1668 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1674 fs_imp::rename(from.as_ref(), to.as_ref())
1677 /// Copies the contents of one file to another. This function will also
1678 /// copy the permission bits of the original file to the destination file.
1680 /// This function will **overwrite** the contents of `to`.
1682 /// Note that if `from` and `to` both point to the same file, then the file
1683 /// will likely get truncated by this operation.
1685 /// On success, the total number of bytes copied is returned and it is equal to
1686 /// the length of the `to` file as reported by `metadata`.
1688 /// If you’re wanting to copy the contents of one file to another and you’re
1689 /// working with [`File`]s, see the [`io::copy()`] function.
1691 /// # Platform-specific behavior
1693 /// This function currently corresponds to the `open` function in Unix
1694 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1695 /// `O_CLOEXEC` is set for returned file descriptors.
1696 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1697 /// NTFS streams are copied but only the size of the main stream is returned by
1698 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1700 /// Note that, this [may change in the future][changes].
1702 /// [changes]: io#platform-specific-behavior
1706 /// This function will return an error in the following situations, but is not
1707 /// limited to just these cases:
1709 /// * `from` is neither a regular file nor a symlink to a regular file.
1710 /// * `from` does not exist.
1711 /// * The current process does not have the permission rights to read
1712 /// `from` or write `to`.
1719 /// fn main() -> std::io::Result<()> {
1720 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1726 fs_imp::copy(from.as_ref(), to.as_ref())
1729 /// Creates a new hard link on the filesystem.
1731 /// The `link` path will be a link pointing to the `original` path. Note that
1732 /// systems often require these two paths to both be located on the same
1735 /// If `original` names a symbolic link, it is platform-specific whether the
1736 /// symbolic link is followed. On platforms where it's possible to not follow
1737 /// it, it is not followed, and the created hard link points to the symbolic
1740 /// # Platform-specific behavior
1742 /// This function currently corresponds the `CreateHardLink` function on Windows.
1743 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1744 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1745 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1746 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1747 /// Note that, this [may change in the future][changes].
1749 /// [changes]: io#platform-specific-behavior
1753 /// This function will return an error in the following situations, but is not
1754 /// limited to just these cases:
1756 /// * The `original` path is not a file or doesn't exist.
1763 /// fn main() -> std::io::Result<()> {
1764 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1770 fs_imp::link(original.as_ref(), link.as_ref())
1773 /// Creates a new symbolic link on the filesystem.
1775 /// The `link` path will be a symbolic link pointing to the `original` path.
1776 /// On Windows, this will be a file symlink, not a directory symlink;
1777 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1778 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1779 /// used instead to make the intent explicit.
1781 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1782 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1783 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1790 /// fn main() -> std::io::Result<()> {
1791 /// fs::soft_link("a.txt", "b.txt")?;
1795 #[stable(feature = "rust1", since = "1.0.0")]
1798 reason = "replaced with std::os::unix::fs::symlink and \
1799 std::os::windows::fs::{symlink_file, symlink_dir}"
1801 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1802 fs_imp::symlink(original.as_ref(), link.as_ref())
1805 /// Reads a symbolic link, returning the file that the link points to.
1807 /// # Platform-specific behavior
1809 /// This function currently corresponds to the `readlink` function on Unix
1810 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1811 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1812 /// Note that, this [may change in the future][changes].
1814 /// [changes]: io#platform-specific-behavior
1818 /// This function will return an error in the following situations, but is not
1819 /// limited to just these cases:
1821 /// * `path` is not a symbolic link.
1822 /// * `path` does not exist.
1829 /// fn main() -> std::io::Result<()> {
1830 /// let path = fs::read_link("a.txt")?;
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1836 fs_imp::readlink(path.as_ref())
1839 /// Returns the canonical, absolute form of a path with all intermediate
1840 /// components normalized and symbolic links resolved.
1842 /// # Platform-specific behavior
1844 /// This function currently corresponds to the `realpath` function on Unix
1845 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1846 /// Note that, this [may change in the future][changes].
1848 /// On Windows, this converts the path to use [extended length path][path]
1849 /// syntax, which allows your program to use longer path names, but means you
1850 /// can only join backslash-delimited paths to it, and it may be incompatible
1851 /// with other applications (if passed to the application on the command-line,
1852 /// or written to a file another application may read).
1854 /// [changes]: io#platform-specific-behavior
1855 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1859 /// This function will return an error in the following situations, but is not
1860 /// limited to just these cases:
1862 /// * `path` does not exist.
1863 /// * A non-final component in path is not a directory.
1870 /// fn main() -> std::io::Result<()> {
1871 /// let path = fs::canonicalize("../a/../foo.txt")?;
1875 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1876 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1877 fs_imp::canonicalize(path.as_ref())
1880 /// Creates a new, empty directory at the provided path
1882 /// # Platform-specific behavior
1884 /// This function currently corresponds to the `mkdir` function on Unix
1885 /// and the `CreateDirectory` function on Windows.
1886 /// Note that, this [may change in the future][changes].
1888 /// [changes]: io#platform-specific-behavior
1890 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1891 /// return an error. To create a directory and all its missing parents at the
1892 /// same time, use the [`create_dir_all`] function.
1896 /// This function will return an error in the following situations, but is not
1897 /// limited to just these cases:
1899 /// * User lacks permissions to create directory at `path`.
1900 /// * A parent of the given path doesn't exist. (To create a directory and all
1901 /// its missing parents at the same time, use the [`create_dir_all`]
1903 /// * `path` already exists.
1910 /// fn main() -> std::io::Result<()> {
1911 /// fs::create_dir("/some/dir")?;
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1917 DirBuilder::new().create(path.as_ref())
1920 /// Recursively create a directory and all of its parent components if they
1923 /// # Platform-specific behavior
1925 /// This function currently corresponds to the `mkdir` function on Unix
1926 /// and the `CreateDirectory` function on Windows.
1927 /// Note that, this [may change in the future][changes].
1929 /// [changes]: io#platform-specific-behavior
1933 /// This function will return an error in the following situations, but is not
1934 /// limited to just these cases:
1936 /// * If any directory in the path specified by `path`
1937 /// does not already exist and it could not be created otherwise. The specific
1938 /// error conditions for when a directory is being created (after it is
1939 /// determined to not exist) are outlined by [`fs::create_dir`].
1941 /// Notable exception is made for situations where any of the directories
1942 /// specified in the `path` could not be created as it was being created concurrently.
1943 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1944 /// concurrently from multiple threads or processes is guaranteed not to fail
1945 /// due to a race condition with itself.
1947 /// [`fs::create_dir`]: create_dir
1954 /// fn main() -> std::io::Result<()> {
1955 /// fs::create_dir_all("/some/dir")?;
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1961 DirBuilder::new().recursive(true).create(path.as_ref())
1964 /// Removes an empty directory.
1966 /// # Platform-specific behavior
1968 /// This function currently corresponds to the `rmdir` function on Unix
1969 /// and the `RemoveDirectory` function on Windows.
1970 /// Note that, this [may change in the future][changes].
1972 /// [changes]: io#platform-specific-behavior
1976 /// This function will return an error in the following situations, but is not
1977 /// limited to just these cases:
1979 /// * `path` doesn't exist.
1980 /// * `path` isn't a directory.
1981 /// * The user lacks permissions to remove the directory at the provided `path`.
1982 /// * The directory isn't empty.
1989 /// fn main() -> std::io::Result<()> {
1990 /// fs::remove_dir("/some/dir")?;
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1996 fs_imp::rmdir(path.as_ref())
1999 /// Removes a directory at this path, after removing all its contents. Use
2002 /// This function does **not** follow symbolic links and it will simply remove the
2003 /// symbolic link itself.
2005 /// # Platform-specific behavior
2007 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2008 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2010 /// Note that, this [may change in the future][changes].
2012 /// [changes]: io#platform-specific-behavior
2016 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2018 /// [`fs::remove_file`]: remove_file
2019 /// [`fs::remove_dir`]: remove_dir
2026 /// fn main() -> std::io::Result<()> {
2027 /// fs::remove_dir_all("/some/dir")?;
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2033 fs_imp::remove_dir_all(path.as_ref())
2036 /// Returns an iterator over the entries within a directory.
2038 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2039 /// New errors may be encountered after an iterator is initially constructed.
2041 /// # Platform-specific behavior
2043 /// This function currently corresponds to the `opendir` function on Unix
2044 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2045 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2046 /// Note that, this [may change in the future][changes].
2048 /// [changes]: io#platform-specific-behavior
2050 /// The order in which this iterator returns entries is platform and filesystem
2055 /// This function will return an error in the following situations, but is not
2056 /// limited to just these cases:
2058 /// * The provided `path` doesn't exist.
2059 /// * The process lacks permissions to view the contents.
2060 /// * The `path` points at a non-directory file.
2066 /// use std::fs::{self, DirEntry};
2067 /// use std::path::Path;
2069 /// // one possible implementation of walking a directory only visiting files
2070 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2071 /// if dir.is_dir() {
2072 /// for entry in fs::read_dir(dir)? {
2073 /// let entry = entry?;
2074 /// let path = entry.path();
2075 /// if path.is_dir() {
2076 /// visit_dirs(&path, cb)?;
2087 /// use std::{fs, io};
2089 /// fn main() -> io::Result<()> {
2090 /// let mut entries = fs::read_dir(".")?
2091 /// .map(|res| res.map(|e| e.path()))
2092 /// .collect::<Result<Vec<_>, io::Error>>()?;
2094 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2095 /// // ordering is required the entries should be explicitly sorted.
2099 /// // The entries have now been sorted by their path.
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2106 fs_imp::readdir(path.as_ref()).map(ReadDir)
2109 /// Changes the permissions found on a file or a directory.
2111 /// # Platform-specific behavior
2113 /// This function currently corresponds to the `chmod` function on Unix
2114 /// and the `SetFileAttributes` function on Windows.
2115 /// Note that, this [may change in the future][changes].
2117 /// [changes]: io#platform-specific-behavior
2121 /// This function will return an error in the following situations, but is not
2122 /// limited to just these cases:
2124 /// * `path` does not exist.
2125 /// * The user lacks the permission to change attributes of the file.
2132 /// fn main() -> std::io::Result<()> {
2133 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2134 /// perms.set_readonly(true);
2135 /// fs::set_permissions("foo.txt", perms)?;
2139 #[stable(feature = "set_permissions", since = "1.1.0")]
2140 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2141 fs_imp::set_perm(path.as_ref(), perm.0)
2145 /// Creates a new set of options with default mode/security settings for all
2146 /// platforms and also non-recursive.
2151 /// use std::fs::DirBuilder;
2153 /// let builder = DirBuilder::new();
2155 #[stable(feature = "dir_builder", since = "1.6.0")]
2156 pub fn new() -> DirBuilder {
2157 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2160 /// Indicates that directories should be created recursively, creating all
2161 /// parent directories. Parents that do not exist are created with the same
2162 /// security and permissions settings.
2164 /// This option defaults to `false`.
2169 /// use std::fs::DirBuilder;
2171 /// let mut builder = DirBuilder::new();
2172 /// builder.recursive(true);
2174 #[stable(feature = "dir_builder", since = "1.6.0")]
2175 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2176 self.recursive = recursive;
2180 /// Creates the specified directory with the options configured in this
2183 /// It is considered an error if the directory already exists unless
2184 /// recursive mode is enabled.
2189 /// use std::fs::{self, DirBuilder};
2191 /// let path = "/tmp/foo/bar/baz";
2192 /// DirBuilder::new()
2193 /// .recursive(true)
2194 /// .create(path).unwrap();
2196 /// assert!(fs::metadata(path).unwrap().is_dir());
2198 #[stable(feature = "dir_builder", since = "1.6.0")]
2199 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2200 self._create(path.as_ref())
2203 fn _create(&self, path: &Path) -> io::Result<()> {
2204 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2207 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2208 if path == Path::new("") {
2212 match self.inner.mkdir(path) {
2213 Ok(()) => return Ok(()),
2214 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2215 Err(_) if path.is_dir() => return Ok(()),
2216 Err(e) => return Err(e),
2218 match path.parent() {
2219 Some(p) => self.create_dir_all(p)?,
2221 return Err(io::Error::new_const(
2222 io::ErrorKind::Uncategorized,
2223 &"failed to create whole tree",
2227 match self.inner.mkdir(path) {
2229 Err(_) if path.is_dir() => Ok(()),
2235 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2236 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2241 /// Returns `Ok(true)` if the path points at an existing entity.
2243 /// This function will traverse symbolic links to query information about the
2244 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2246 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2247 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2248 /// denied on some of the parent directories.)
2253 /// #![feature(path_try_exists)]
2256 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2257 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2259 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2261 #[unstable(feature = "path_try_exists", issue = "83186")]
2263 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2264 fs_imp::try_exists(path.as_ref())