1 //! Filesystem manipulation operations.
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
8 #![stable(feature = "rust1", since = "1.0.0")]
9 #![deny(unsafe_op_in_unsafe_fn)]
11 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
14 use crate::ffi::OsString;
16 use crate::io::{self, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write};
17 use crate::path::{Path, PathBuf};
18 use crate::sys::fs as fs_imp;
19 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
20 use crate::time::SystemTime;
22 /// A reference to an open file on the filesystem.
24 /// An instance of a `File` can be read and/or written depending on what options
25 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
26 /// that the file contains internally.
28 /// Files are automatically closed when they go out of scope. Errors detected
29 /// on closing are ignored by the implementation of `Drop`. Use the method
30 /// [`sync_all`] if these errors must be manually handled.
34 /// Creates a new file and write bytes to it (you can also use [`write()`]):
37 /// use std::fs::File;
38 /// use std::io::prelude::*;
40 /// fn main() -> std::io::Result<()> {
41 /// let mut file = File::create("foo.txt")?;
42 /// file.write_all(b"Hello, world!")?;
47 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
50 /// use std::fs::File;
51 /// use std::io::prelude::*;
53 /// fn main() -> std::io::Result<()> {
54 /// let mut file = File::open("foo.txt")?;
55 /// let mut contents = String::new();
56 /// file.read_to_string(&mut contents)?;
57 /// assert_eq!(contents, "Hello, world!");
62 /// It can be more efficient to read the contents of a file with a buffered
63 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
66 /// use std::fs::File;
67 /// use std::io::BufReader;
68 /// use std::io::prelude::*;
70 /// fn main() -> std::io::Result<()> {
71 /// let file = File::open("foo.txt")?;
72 /// let mut buf_reader = BufReader::new(file);
73 /// let mut contents = String::new();
74 /// buf_reader.read_to_string(&mut contents)?;
75 /// assert_eq!(contents, "Hello, world!");
80 /// Note that, although read and write methods require a `&mut File`, because
81 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
82 /// still modify the file, either through methods that take `&File` or by
83 /// retrieving the underlying OS object and modifying the file that way.
84 /// Additionally, many operating systems allow concurrent modification of files
85 /// by different processes. Avoid assuming that holding a `&File` means that the
86 /// file will not change.
88 /// [`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 <code>[io::Result]<[DirEntry]></code>. 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 /// Read the entire contents of a file into a bytes vector.
203 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
204 /// with fewer imports and without an intermediate variable.
206 /// [`read_to_end`]: Read::read_to_end
210 /// This function will return an error if `path` does not already exist.
211 /// Other errors may also be returned according to [`OpenOptions::open`].
213 /// It will also return an error if it encounters while reading an error
214 /// of a kind other than [`io::ErrorKind::Interrupted`].
220 /// use std::net::SocketAddr;
222 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
223 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
227 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
228 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
229 fn inner(path: &Path) -> io::Result<Vec<u8>> {
230 let mut file = File::open(path)?;
231 let mut bytes = Vec::new();
232 file.read_to_end(&mut bytes)?;
238 /// Read the entire contents of a file into a string.
240 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
241 /// with fewer imports and without an intermediate variable.
243 /// [`read_to_string`]: Read::read_to_string
247 /// This function will return an error if `path` does not already exist.
248 /// Other errors may also be returned according to [`OpenOptions::open`].
250 /// It will also return an error if it encounters while reading an error
251 /// of a kind other than [`io::ErrorKind::Interrupted`],
252 /// or if the contents of the file are not valid UTF-8.
258 /// use std::net::SocketAddr;
259 /// use std::error::Error;
261 /// fn main() -> Result<(), Box<dyn Error>> {
262 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
266 #[stable(feature = "fs_read_write", since = "1.26.0")]
267 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
268 fn inner(path: &Path) -> io::Result<String> {
269 let mut file = File::open(path)?;
270 let mut string = String::new();
271 file.read_to_string(&mut string)?;
277 /// Write a slice as the entire contents of a file.
279 /// This function will create a file if it does not exist,
280 /// and will entirely replace its contents if it does.
282 /// This is a convenience function for using [`File::create`] and [`write_all`]
283 /// with fewer imports.
285 /// [`write_all`]: Write::write_all
292 /// fn main() -> std::io::Result<()> {
293 /// fs::write("foo.txt", b"Lorem ipsum")?;
294 /// fs::write("bar.txt", "dolor sit")?;
298 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
299 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
300 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
301 File::create(path)?.write_all(contents)
303 inner(path.as_ref(), contents.as_ref())
307 /// Attempts to open a file in read-only mode.
309 /// See the [`OpenOptions::open`] method for more details.
313 /// This function will return an error if `path` does not already exist.
314 /// Other errors may also be returned according to [`OpenOptions::open`].
319 /// use std::fs::File;
321 /// fn main() -> std::io::Result<()> {
322 /// let mut f = File::open("foo.txt")?;
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
328 OpenOptions::new().read(true).open(path.as_ref())
331 /// Opens a file in write-only mode.
333 /// This function will create a file if it does not exist,
334 /// and will truncate it if it does.
336 /// See the [`OpenOptions::open`] function for more details.
341 /// use std::fs::File;
343 /// fn main() -> std::io::Result<()> {
344 /// let mut f = File::create("foo.txt")?;
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
350 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
353 /// Returns a new OpenOptions object.
355 /// This function returns a new OpenOptions object that you can use to
356 /// open or create a file with specific options if `open()` or `create()`
357 /// are not appropriate.
359 /// It is equivalent to `OpenOptions::new()` but allows you to write more
360 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
361 /// you can write `File::options().read(true).open("foo.txt")`. This
362 /// also avoids the need to import `OpenOptions`.
364 /// See the [`OpenOptions::new`] function for more details.
369 /// use std::fs::File;
371 /// fn main() -> std::io::Result<()> {
372 /// let mut f = File::options().read(true).open("foo.txt")?;
377 #[stable(feature = "with_options", since = "1.58.0")]
378 pub fn options() -> OpenOptions {
382 /// Attempts to sync all OS-internal metadata to disk.
384 /// This function will attempt to ensure that all in-memory data reaches the
385 /// filesystem before returning.
387 /// This can be used to handle errors that would otherwise only be caught
388 /// when the `File` is closed. Dropping a file will ignore errors in
389 /// synchronizing this in-memory data.
394 /// use std::fs::File;
395 /// use std::io::prelude::*;
397 /// fn main() -> std::io::Result<()> {
398 /// let mut f = File::create("foo.txt")?;
399 /// f.write_all(b"Hello, world!")?;
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn sync_all(&self) -> io::Result<()> {
410 /// This function is similar to [`sync_all`], except that it might not
411 /// synchronize file metadata to the filesystem.
413 /// This is intended for use cases that must synchronize content, but don't
414 /// need the metadata on disk. The goal of this method is to reduce disk
417 /// Note that some platforms may simply implement this in terms of
420 /// [`sync_all`]: File::sync_all
425 /// use std::fs::File;
426 /// use std::io::prelude::*;
428 /// fn main() -> std::io::Result<()> {
429 /// let mut f = File::create("foo.txt")?;
430 /// f.write_all(b"Hello, world!")?;
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn sync_data(&self) -> io::Result<()> {
438 self.inner.datasync()
441 /// Truncates or extends the underlying file, updating the size of
442 /// this file to become `size`.
444 /// If the `size` is less than the current file's size, then the file will
445 /// be shrunk. If it is greater than the current file's size, then the file
446 /// will be extended to `size` and have all of the intermediate data filled
449 /// The file's cursor isn't changed. In particular, if the cursor was at the
450 /// end and the file is shrunk using this operation, the cursor will now be
455 /// This function will return an error if the file is not opened for writing.
456 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
457 /// length would cause an overflow due to the implementation specifics.
462 /// use std::fs::File;
464 /// fn main() -> std::io::Result<()> {
465 /// let mut f = File::create("foo.txt")?;
471 /// Note that this method alters the content of the underlying file, even
472 /// though it takes `&self` rather than `&mut self`.
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn set_len(&self, size: u64) -> io::Result<()> {
475 self.inner.truncate(size)
478 /// Queries metadata about the underlying file.
483 /// use std::fs::File;
485 /// fn main() -> std::io::Result<()> {
486 /// let mut f = File::open("foo.txt")?;
487 /// let metadata = f.metadata()?;
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn metadata(&self) -> io::Result<Metadata> {
493 self.inner.file_attr().map(Metadata)
496 /// Creates a new `File` instance that shares the same underlying file handle
497 /// as the existing `File` instance. Reads, writes, and seeks will affect
498 /// both `File` instances simultaneously.
502 /// Creates two handles for a file named `foo.txt`:
505 /// use std::fs::File;
507 /// fn main() -> std::io::Result<()> {
508 /// let mut file = File::open("foo.txt")?;
509 /// let file_copy = file.try_clone()?;
514 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
515 /// two handles, seek one of them, and read the remaining bytes from the
519 /// use std::fs::File;
520 /// use std::io::SeekFrom;
521 /// use std::io::prelude::*;
523 /// fn main() -> std::io::Result<()> {
524 /// let mut file = File::open("foo.txt")?;
525 /// let mut file_copy = file.try_clone()?;
527 /// file.seek(SeekFrom::Start(3))?;
529 /// let mut contents = vec![];
530 /// file_copy.read_to_end(&mut contents)?;
531 /// assert_eq!(contents, b"def\n");
535 #[stable(feature = "file_try_clone", since = "1.9.0")]
536 pub fn try_clone(&self) -> io::Result<File> {
537 Ok(File { inner: self.inner.duplicate()? })
540 /// Changes the permissions on the underlying file.
542 /// # Platform-specific behavior
544 /// This function currently corresponds to the `fchmod` function on Unix and
545 /// the `SetFileInformationByHandle` function on Windows. Note that, this
546 /// [may change in the future][changes].
548 /// [changes]: io#platform-specific-behavior
552 /// This function will return an error if the user lacks permission change
553 /// attributes on the underlying file. It may also return an error in other
554 /// os-specific unspecified cases.
559 /// fn main() -> std::io::Result<()> {
560 /// use std::fs::File;
562 /// let file = File::open("foo.txt")?;
563 /// let mut perms = file.metadata()?.permissions();
564 /// perms.set_readonly(true);
565 /// file.set_permissions(perms)?;
570 /// Note that this method alters the permissions of the underlying file,
571 /// even though it takes `&self` rather than `&mut self`.
572 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
573 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
574 self.inner.set_permissions(perm.0)
578 // In addition to the `impl`s here, `File` also has `impl`s for
579 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
580 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
581 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
582 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
584 impl AsInner<fs_imp::File> for File {
585 fn as_inner(&self) -> &fs_imp::File {
589 impl FromInner<fs_imp::File> for File {
590 fn from_inner(f: fs_imp::File) -> File {
594 impl IntoInner<fs_imp::File> for File {
595 fn into_inner(self) -> fs_imp::File {
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl fmt::Debug for File {
602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 /// Indicates how much extra capacity is needed to read the rest of the file.
608 fn buffer_capacity_required(mut file: &File) -> usize {
609 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
610 let pos = file.stream_position().unwrap_or(0);
611 // Don't worry about `usize` overflow because reading will fail regardless
613 size.saturating_sub(pos) as usize
616 #[stable(feature = "rust1", since = "1.0.0")]
618 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
622 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
623 self.inner.read_vectored(bufs)
626 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
627 self.inner.read_buf(buf)
631 fn is_read_vectored(&self) -> bool {
632 self.inner.is_read_vectored()
635 // Reserves space in the buffer based on the file size when available.
636 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
637 buf.reserve(buffer_capacity_required(self));
638 io::default_read_to_end(self, buf)
641 // Reserves space in the buffer based on the file size when available.
642 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
643 buf.reserve(buffer_capacity_required(self));
644 io::default_read_to_string(self, buf)
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl Write for File {
649 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
650 self.inner.write(buf)
653 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
654 self.inner.write_vectored(bufs)
658 fn is_write_vectored(&self) -> bool {
659 self.inner.is_write_vectored()
662 fn flush(&mut self) -> io::Result<()> {
666 #[stable(feature = "rust1", since = "1.0.0")]
668 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl Read for &File {
674 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
678 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
679 self.inner.read_buf(buf)
682 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
683 self.inner.read_vectored(bufs)
687 fn is_read_vectored(&self) -> bool {
688 self.inner.is_read_vectored()
691 // Reserves space in the buffer based on the file size when available.
692 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
693 buf.reserve(buffer_capacity_required(self));
694 io::default_read_to_end(self, buf)
697 // Reserves space in the buffer based on the file size when available.
698 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
699 buf.reserve(buffer_capacity_required(self));
700 io::default_read_to_string(self, buf)
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl Write for &File {
705 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
706 self.inner.write(buf)
709 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
710 self.inner.write_vectored(bufs)
714 fn is_write_vectored(&self) -> bool {
715 self.inner.is_write_vectored()
718 fn flush(&mut self) -> io::Result<()> {
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl Seek for &File {
724 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
730 /// Creates a blank new set of options ready for configuration.
732 /// All options are initially set to `false`.
737 /// use std::fs::OpenOptions;
739 /// let mut options = OpenOptions::new();
740 /// let file = options.read(true).open("foo.txt");
742 #[stable(feature = "rust1", since = "1.0.0")]
744 pub fn new() -> Self {
745 OpenOptions(fs_imp::OpenOptions::new())
748 /// Sets the option for read access.
750 /// This option, when true, will indicate that the file should be
751 /// `read`-able if opened.
756 /// use std::fs::OpenOptions;
758 /// let file = OpenOptions::new().read(true).open("foo.txt");
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn read(&mut self, read: bool) -> &mut Self {
766 /// Sets the option for write access.
768 /// This option, when true, will indicate that the file should be
769 /// `write`-able if opened.
771 /// If the file already exists, any write calls on it will overwrite its
772 /// contents, without truncating it.
777 /// use std::fs::OpenOptions;
779 /// let file = OpenOptions::new().write(true).open("foo.txt");
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn write(&mut self, write: bool) -> &mut Self {
787 /// Sets the option for the append mode.
789 /// This option, when true, means that writes will append to a file instead
790 /// of overwriting previous contents.
791 /// Note that setting `.write(true).append(true)` has the same effect as
792 /// setting only `.append(true)`.
794 /// For most filesystems, the operating system guarantees that all writes are
795 /// atomic: no writes get mangled because another process writes at the same
798 /// One maybe obvious note when using append-mode: make sure that all data
799 /// that belongs together is written to the file in one operation. This
800 /// can be done by concatenating strings before passing them to [`write()`],
801 /// or using a buffered writer (with a buffer of adequate size),
802 /// and calling [`flush()`] when the message is complete.
804 /// If a file is opened with both read and append access, beware that after
805 /// opening, and after every write, the position for reading may be set at the
806 /// end of the file. So, before writing, save the current position (using
807 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
811 /// This function doesn't create the file if it doesn't exist. Use the
812 /// [`OpenOptions::create`] method to do so.
814 /// [`write()`]: Write::write "io::Write::write"
815 /// [`flush()`]: Write::flush "io::Write::flush"
816 /// [seek]: Seek::seek "io::Seek::seek"
817 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
822 /// use std::fs::OpenOptions;
824 /// let file = OpenOptions::new().append(true).open("foo.txt");
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn append(&mut self, append: bool) -> &mut Self {
828 self.0.append(append);
832 /// Sets the option for truncating a previous file.
834 /// If a file is successfully opened with this option set it will truncate
835 /// the file to 0 length if it already exists.
837 /// The file must be opened with write access for truncate to work.
842 /// use std::fs::OpenOptions;
844 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
848 self.0.truncate(truncate);
852 /// Sets the option to create a new file, or open it if it already exists.
854 /// In order for the file to be created, [`OpenOptions::write`] or
855 /// [`OpenOptions::append`] access must be used.
860 /// use std::fs::OpenOptions;
862 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn create(&mut self, create: bool) -> &mut Self {
866 self.0.create(create);
870 /// Sets the option to create a new file, failing if it already exists.
872 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
873 /// way, if the call succeeds, the file returned is guaranteed to be new.
875 /// This option is useful because it is atomic. Otherwise between checking
876 /// whether a file exists and creating a new one, the file may have been
877 /// created by another process (a TOCTOU race condition / attack).
879 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
882 /// The file must be opened with write or append access in order to create
885 /// [`.create()`]: OpenOptions::create
886 /// [`.truncate()`]: OpenOptions::truncate
891 /// use std::fs::OpenOptions;
893 /// let file = OpenOptions::new().write(true)
894 /// .create_new(true)
895 /// .open("foo.txt");
897 #[stable(feature = "expand_open_options2", since = "1.9.0")]
898 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
899 self.0.create_new(create_new);
903 /// Opens a file at `path` with the options specified by `self`.
907 /// This function will return an error under a number of different
908 /// circumstances. Some of these error conditions are listed here, together
909 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
910 /// part of the compatibility contract of the function.
912 /// * [`NotFound`]: The specified file does not exist and neither `create`
913 /// or `create_new` is set.
914 /// * [`NotFound`]: One of the directory components of the file path does
916 /// * [`PermissionDenied`]: The user lacks permission to get the specified
917 /// access rights for the file.
918 /// * [`PermissionDenied`]: The user lacks permission to open one of the
919 /// directory components of the specified path.
920 /// * [`AlreadyExists`]: `create_new` was specified and the file already
922 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
923 /// without write access, no access mode set, etc.).
925 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
926 /// * One of the directory components of the specified file path
927 /// was not, in fact, a directory.
928 /// * Filesystem-level errors: full disk, write permission
929 /// requested on a read-only file system, exceeded disk quota, too many
930 /// open files, too long filename, too many symbolic links in the
931 /// specified path (Unix-like systems only), etc.
936 /// use std::fs::OpenOptions;
938 /// let file = OpenOptions::new().read(true).open("foo.txt");
941 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
942 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
943 /// [`NotFound`]: io::ErrorKind::NotFound
944 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
945 #[stable(feature = "rust1", since = "1.0.0")]
946 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
947 self._open(path.as_ref())
950 fn _open(&self, path: &Path) -> io::Result<File> {
951 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
955 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
956 fn as_inner(&self) -> &fs_imp::OpenOptions {
961 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
962 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
968 /// Returns the file type for this metadata.
973 /// fn main() -> std::io::Result<()> {
976 /// let metadata = fs::metadata("foo.txt")?;
978 /// println!("{:?}", metadata.file_type());
983 #[stable(feature = "file_type", since = "1.1.0")]
984 pub fn file_type(&self) -> FileType {
985 FileType(self.0.file_type())
988 /// Returns `true` if this metadata is for a directory. The
989 /// result is mutually exclusive to the result of
990 /// [`Metadata::is_file`], and will be false for symlink metadata
991 /// obtained from [`symlink_metadata`].
996 /// fn main() -> std::io::Result<()> {
999 /// let metadata = fs::metadata("foo.txt")?;
1001 /// assert!(!metadata.is_dir());
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn is_dir(&self) -> bool {
1008 self.file_type().is_dir()
1011 /// Returns `true` if this metadata is for a regular file. The
1012 /// result is mutually exclusive to the result of
1013 /// [`Metadata::is_dir`], and will be false for symlink metadata
1014 /// obtained from [`symlink_metadata`].
1016 /// When the goal is simply to read from (or write to) the source, the most
1017 /// reliable way to test the source can be read (or written to) is to open
1018 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1019 /// a Unix-like system for example. See [`File::open`] or
1020 /// [`OpenOptions::open`] for more information.
1027 /// fn main() -> std::io::Result<()> {
1028 /// let metadata = fs::metadata("foo.txt")?;
1030 /// assert!(metadata.is_file());
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 pub fn is_file(&self) -> bool {
1037 self.file_type().is_file()
1040 /// Returns `true` if this metadata is for a symbolic link.
1044 #[cfg_attr(unix, doc = "```no_run")]
1045 #[cfg_attr(not(unix), doc = "```ignore")]
1047 /// use std::path::Path;
1048 /// use std::os::unix::fs::symlink;
1050 /// fn main() -> std::io::Result<()> {
1051 /// let link_path = Path::new("link");
1052 /// symlink("/origin_does_not_exists/", link_path)?;
1054 /// let metadata = fs::symlink_metadata(link_path)?;
1056 /// assert!(metadata.is_symlink());
1061 #[stable(feature = "is_symlink", since = "1.58.0")]
1062 pub fn is_symlink(&self) -> bool {
1063 self.file_type().is_symlink()
1066 /// Returns the size of the file, in bytes, this metadata is for.
1073 /// fn main() -> std::io::Result<()> {
1074 /// let metadata = fs::metadata("foo.txt")?;
1076 /// assert_eq!(0, metadata.len());
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn len(&self) -> u64 {
1086 /// Returns the permissions of the file this metadata is for.
1093 /// fn main() -> std::io::Result<()> {
1094 /// let metadata = fs::metadata("foo.txt")?;
1096 /// assert!(!metadata.permissions().readonly());
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub fn permissions(&self) -> Permissions {
1103 Permissions(self.0.perm())
1106 /// Returns the last modification time listed in this metadata.
1108 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1109 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1113 /// This field might not be available on all platforms, and will return an
1114 /// `Err` on platforms where it is not available.
1121 /// fn main() -> std::io::Result<()> {
1122 /// let metadata = fs::metadata("foo.txt")?;
1124 /// if let Ok(time) = metadata.modified() {
1125 /// println!("{:?}", time);
1127 /// println!("Not supported on this platform");
1132 #[stable(feature = "fs_time", since = "1.10.0")]
1133 pub fn modified(&self) -> io::Result<SystemTime> {
1134 self.0.modified().map(FromInner::from_inner)
1137 /// Returns the last access time of this metadata.
1139 /// The returned value corresponds to the `atime` field of `stat` on Unix
1140 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1142 /// Note that not all platforms will keep this field update in a file's
1143 /// metadata, for example Windows has an option to disable updating this
1144 /// time when files are accessed and Linux similarly has `noatime`.
1148 /// This field might not be available on all platforms, and will return an
1149 /// `Err` on platforms where it is not available.
1156 /// fn main() -> std::io::Result<()> {
1157 /// let metadata = fs::metadata("foo.txt")?;
1159 /// if let Ok(time) = metadata.accessed() {
1160 /// println!("{:?}", time);
1162 /// println!("Not supported on this platform");
1167 #[stable(feature = "fs_time", since = "1.10.0")]
1168 pub fn accessed(&self) -> io::Result<SystemTime> {
1169 self.0.accessed().map(FromInner::from_inner)
1172 /// Returns the creation time listed in this metadata.
1174 /// The returned value corresponds to the `btime` field of `statx` on
1175 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1176 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1180 /// This field might not be available on all platforms, and will return an
1181 /// `Err` on platforms or filesystems where it is not available.
1188 /// fn main() -> std::io::Result<()> {
1189 /// let metadata = fs::metadata("foo.txt")?;
1191 /// if let Ok(time) = metadata.created() {
1192 /// println!("{:?}", time);
1194 /// println!("Not supported on this platform or filesystem");
1199 #[stable(feature = "fs_time", since = "1.10.0")]
1200 pub fn created(&self) -> io::Result<SystemTime> {
1201 self.0.created().map(FromInner::from_inner)
1205 #[stable(feature = "std_debug", since = "1.16.0")]
1206 impl fmt::Debug for Metadata {
1207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1208 f.debug_struct("Metadata")
1209 .field("file_type", &self.file_type())
1210 .field("is_dir", &self.is_dir())
1211 .field("is_file", &self.is_file())
1212 .field("permissions", &self.permissions())
1213 .field("modified", &self.modified())
1214 .field("accessed", &self.accessed())
1215 .field("created", &self.created())
1216 .finish_non_exhaustive()
1220 impl AsInner<fs_imp::FileAttr> for Metadata {
1221 fn as_inner(&self) -> &fs_imp::FileAttr {
1226 impl FromInner<fs_imp::FileAttr> for Metadata {
1227 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1233 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1238 /// use std::fs::File;
1240 /// fn main() -> std::io::Result<()> {
1241 /// let mut f = File::create("foo.txt")?;
1242 /// let metadata = f.metadata()?;
1244 /// assert_eq!(false, metadata.permissions().readonly());
1248 #[must_use = "call `set_readonly` to modify the readonly flag"]
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn readonly(&self) -> bool {
1254 /// Modifies the readonly flag for this set of permissions. If the
1255 /// `readonly` argument is `true`, using the resulting `Permission` will
1256 /// update file permissions to forbid writing. Conversely, if it's `false`,
1257 /// using the resulting `Permission` will update file permissions to allow
1260 /// This operation does **not** modify the filesystem. To modify the
1261 /// filesystem use the [`set_permissions`] function.
1266 /// use std::fs::File;
1268 /// fn main() -> std::io::Result<()> {
1269 /// let f = File::create("foo.txt")?;
1270 /// let metadata = f.metadata()?;
1271 /// let mut permissions = metadata.permissions();
1273 /// permissions.set_readonly(true);
1275 /// // filesystem doesn't change
1276 /// assert_eq!(false, metadata.permissions().readonly());
1278 /// // just this particular `permissions`.
1279 /// assert_eq!(true, permissions.readonly());
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn set_readonly(&mut self, readonly: bool) {
1285 self.0.set_readonly(readonly)
1290 /// Tests whether this file type represents a directory. The
1291 /// result is mutually exclusive to the results of
1292 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1295 /// [`is_file`]: FileType::is_file
1296 /// [`is_symlink`]: FileType::is_symlink
1301 /// fn main() -> std::io::Result<()> {
1304 /// let metadata = fs::metadata("foo.txt")?;
1305 /// let file_type = metadata.file_type();
1307 /// assert_eq!(file_type.is_dir(), false);
1312 #[stable(feature = "file_type", since = "1.1.0")]
1313 pub fn is_dir(&self) -> bool {
1317 /// Tests whether this file type represents a regular file.
1318 /// The result is mutually exclusive to the results of
1319 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1322 /// When the goal is simply to read from (or write to) the source, the most
1323 /// reliable way to test the source can be read (or written to) is to open
1324 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1325 /// a Unix-like system for example. See [`File::open`] or
1326 /// [`OpenOptions::open`] for more information.
1328 /// [`is_dir`]: FileType::is_dir
1329 /// [`is_symlink`]: FileType::is_symlink
1334 /// fn main() -> std::io::Result<()> {
1337 /// let metadata = fs::metadata("foo.txt")?;
1338 /// let file_type = metadata.file_type();
1340 /// assert_eq!(file_type.is_file(), true);
1345 #[stable(feature = "file_type", since = "1.1.0")]
1346 pub fn is_file(&self) -> bool {
1350 /// Tests whether this file type represents a symbolic link.
1351 /// The result is mutually exclusive to the results of
1352 /// [`is_dir`] and [`is_file`]; only zero or one of these
1355 /// The underlying [`Metadata`] struct needs to be retrieved
1356 /// with the [`fs::symlink_metadata`] function and not the
1357 /// [`fs::metadata`] function. The [`fs::metadata`] function
1358 /// follows symbolic links, so [`is_symlink`] would always
1359 /// return `false` for the target file.
1361 /// [`fs::metadata`]: metadata
1362 /// [`fs::symlink_metadata`]: symlink_metadata
1363 /// [`is_dir`]: FileType::is_dir
1364 /// [`is_file`]: FileType::is_file
1365 /// [`is_symlink`]: FileType::is_symlink
1372 /// fn main() -> std::io::Result<()> {
1373 /// let metadata = fs::symlink_metadata("foo.txt")?;
1374 /// let file_type = metadata.file_type();
1376 /// assert_eq!(file_type.is_symlink(), false);
1381 #[stable(feature = "file_type", since = "1.1.0")]
1382 pub fn is_symlink(&self) -> bool {
1387 impl AsInner<fs_imp::FileType> for FileType {
1388 fn as_inner(&self) -> &fs_imp::FileType {
1393 impl FromInner<fs_imp::FilePermissions> for Permissions {
1394 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1399 impl AsInner<fs_imp::FilePermissions> for Permissions {
1400 fn as_inner(&self) -> &fs_imp::FilePermissions {
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl Iterator for ReadDir {
1407 type Item = io::Result<DirEntry>;
1409 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1410 self.0.next().map(|entry| entry.map(DirEntry))
1415 /// Returns the full path to the file that this entry represents.
1417 /// The full path is created by joining the original path to `read_dir`
1418 /// with the filename of this entry.
1425 /// fn main() -> std::io::Result<()> {
1426 /// for entry in fs::read_dir(".")? {
1427 /// let dir = entry?;
1428 /// println!("{:?}", dir.path());
1434 /// This prints output like:
1437 /// "./whatever.txt"
1439 /// "./hello_world.rs"
1442 /// The exact text, of course, depends on what files you have in `.`.
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 pub fn path(&self) -> PathBuf {
1449 /// Returns the metadata for the file that this entry points at.
1451 /// This function will not traverse symlinks if this entry points at a
1452 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1454 /// [`fs::metadata`]: metadata
1455 /// [`fs::File::metadata`]: File::metadata
1457 /// # Platform-specific behavior
1459 /// On Windows this function is cheap to call (no extra system calls
1460 /// needed), but on Unix platforms this function is the equivalent of
1461 /// calling `symlink_metadata` on the path.
1468 /// if let Ok(entries) = fs::read_dir(".") {
1469 /// for entry in entries {
1470 /// if let Ok(entry) = entry {
1471 /// // Here, `entry` is a `DirEntry`.
1472 /// if let Ok(metadata) = entry.metadata() {
1473 /// // Now let's show our entry's permissions!
1474 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1476 /// println!("Couldn't get metadata for {:?}", entry.path());
1482 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1483 pub fn metadata(&self) -> io::Result<Metadata> {
1484 self.0.metadata().map(Metadata)
1487 /// Returns the file type for the file that this entry points at.
1489 /// This function will not traverse symlinks if this entry points at a
1492 /// # Platform-specific behavior
1494 /// On Windows and most Unix platforms this function is free (no extra
1495 /// system calls needed), but some Unix platforms may require the equivalent
1496 /// call to `symlink_metadata` to learn about the target file type.
1503 /// if let Ok(entries) = fs::read_dir(".") {
1504 /// for entry in entries {
1505 /// if let Ok(entry) = entry {
1506 /// // Here, `entry` is a `DirEntry`.
1507 /// if let Ok(file_type) = entry.file_type() {
1508 /// // Now let's show our entry's file type!
1509 /// println!("{:?}: {:?}", entry.path(), file_type);
1511 /// println!("Couldn't get file type for {:?}", entry.path());
1517 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1518 pub fn file_type(&self) -> io::Result<FileType> {
1519 self.0.file_type().map(FileType)
1522 /// Returns the bare file name of this directory entry without any other
1523 /// leading path component.
1530 /// if let Ok(entries) = fs::read_dir(".") {
1531 /// for entry in entries {
1532 /// if let Ok(entry) = entry {
1533 /// // Here, `entry` is a `DirEntry`.
1534 /// println!("{:?}", entry.file_name());
1540 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1541 pub fn file_name(&self) -> OsString {
1546 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1547 impl fmt::Debug for DirEntry {
1548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549 f.debug_tuple("DirEntry").field(&self.path()).finish()
1553 impl AsInner<fs_imp::DirEntry> for DirEntry {
1554 fn as_inner(&self) -> &fs_imp::DirEntry {
1559 /// Removes a file from the filesystem.
1561 /// Note that there is no
1562 /// guarantee that the file is immediately deleted (e.g., depending on
1563 /// platform, other open file descriptors may prevent immediate removal).
1565 /// # Platform-specific behavior
1567 /// This function currently corresponds to the `unlink` function on Unix
1568 /// and the `DeleteFile` function on Windows.
1569 /// Note that, this [may change in the future][changes].
1571 /// [changes]: io#platform-specific-behavior
1575 /// This function will return an error in the following situations, but is not
1576 /// limited to just these cases:
1578 /// * `path` points to a directory.
1579 /// * The file doesn't exist.
1580 /// * The user lacks permissions to remove the file.
1587 /// fn main() -> std::io::Result<()> {
1588 /// fs::remove_file("a.txt")?;
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1594 fs_imp::unlink(path.as_ref())
1597 /// Given a path, query the file system to get information about a file,
1600 /// This function will traverse symbolic links to query information about the
1601 /// destination file.
1603 /// # Platform-specific behavior
1605 /// This function currently corresponds to the `stat` function on Unix
1606 /// and the `GetFileAttributesEx` function on Windows.
1607 /// Note that, this [may change in the future][changes].
1609 /// [changes]: io#platform-specific-behavior
1613 /// This function will return an error in the following situations, but is not
1614 /// limited to just these cases:
1616 /// * The user lacks permissions to perform `metadata` call on `path`.
1617 /// * `path` does not exist.
1624 /// fn main() -> std::io::Result<()> {
1625 /// let attr = fs::metadata("/some/file/path.txt")?;
1626 /// // inspect attr ...
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1632 fs_imp::stat(path.as_ref()).map(Metadata)
1635 /// Query the metadata about a file without following symlinks.
1637 /// # Platform-specific behavior
1639 /// This function currently corresponds to the `lstat` function on Unix
1640 /// and the `GetFileAttributesEx` function on Windows.
1641 /// Note that, this [may change in the future][changes].
1643 /// [changes]: io#platform-specific-behavior
1647 /// This function will return an error in the following situations, but is not
1648 /// limited to just these cases:
1650 /// * The user lacks permissions to perform `metadata` call on `path`.
1651 /// * `path` does not exist.
1658 /// fn main() -> std::io::Result<()> {
1659 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1660 /// // inspect attr ...
1664 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1665 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1666 fs_imp::lstat(path.as_ref()).map(Metadata)
1669 /// Rename a file or directory to a new name, replacing the original file if
1670 /// `to` already exists.
1672 /// This will not work if the new name is on a different mount point.
1674 /// # Platform-specific behavior
1676 /// This function currently corresponds to the `rename` function on Unix
1677 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1679 /// Because of this, the behavior when both `from` and `to` exist differs. On
1680 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1681 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1682 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1684 /// Note that, this [may change in the future][changes].
1686 /// [changes]: io#platform-specific-behavior
1690 /// This function will return an error in the following situations, but is not
1691 /// limited to just these cases:
1693 /// * `from` does not exist.
1694 /// * The user lacks permissions to view contents.
1695 /// * `from` and `to` are on separate filesystems.
1702 /// fn main() -> std::io::Result<()> {
1703 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1709 fs_imp::rename(from.as_ref(), to.as_ref())
1712 /// Copies the contents of one file to another. This function will also
1713 /// copy the permission bits of the original file to the destination file.
1715 /// This function will **overwrite** the contents of `to`.
1717 /// Note that if `from` and `to` both point to the same file, then the file
1718 /// will likely get truncated by this operation.
1720 /// On success, the total number of bytes copied is returned and it is equal to
1721 /// the length of the `to` file as reported by `metadata`.
1723 /// If you’re wanting to copy the contents of one file to another and you’re
1724 /// working with [`File`]s, see the [`io::copy()`] function.
1726 /// # Platform-specific behavior
1728 /// This function currently corresponds to the `open` function in Unix
1729 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1730 /// `O_CLOEXEC` is set for returned file descriptors.
1731 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1732 /// NTFS streams are copied but only the size of the main stream is returned by
1733 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1735 /// Note that, this [may change in the future][changes].
1737 /// [changes]: io#platform-specific-behavior
1741 /// This function will return an error in the following situations, but is not
1742 /// limited to just these cases:
1744 /// * `from` is neither a regular file nor a symlink to a regular file.
1745 /// * `from` does not exist.
1746 /// * The current process does not have the permission rights to read
1747 /// `from` or write `to`.
1754 /// fn main() -> std::io::Result<()> {
1755 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1761 fs_imp::copy(from.as_ref(), to.as_ref())
1764 /// Creates a new hard link on the filesystem.
1766 /// The `link` path will be a link pointing to the `original` path. Note that
1767 /// systems often require these two paths to both be located on the same
1770 /// If `original` names a symbolic link, it is platform-specific whether the
1771 /// symbolic link is followed. On platforms where it's possible to not follow
1772 /// it, it is not followed, and the created hard link points to the symbolic
1775 /// # Platform-specific behavior
1777 /// This function currently corresponds the `CreateHardLink` function on Windows.
1778 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1779 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1780 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1781 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1782 /// Note that, this [may change in the future][changes].
1784 /// [changes]: io#platform-specific-behavior
1788 /// This function will return an error in the following situations, but is not
1789 /// limited to just these cases:
1791 /// * The `original` path is not a file or doesn't exist.
1798 /// fn main() -> std::io::Result<()> {
1799 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1805 fs_imp::link(original.as_ref(), link.as_ref())
1808 /// Creates a new symbolic link on the filesystem.
1810 /// The `link` path will be a symbolic link pointing to the `original` path.
1811 /// On Windows, this will be a file symlink, not a directory symlink;
1812 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1813 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1814 /// used instead to make the intent explicit.
1816 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1817 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1818 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1825 /// fn main() -> std::io::Result<()> {
1826 /// fs::soft_link("a.txt", "b.txt")?;
1830 #[stable(feature = "rust1", since = "1.0.0")]
1833 reason = "replaced with std::os::unix::fs::symlink and \
1834 std::os::windows::fs::{symlink_file, symlink_dir}"
1836 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1837 fs_imp::symlink(original.as_ref(), link.as_ref())
1840 /// Reads a symbolic link, returning the file that the link points to.
1842 /// # Platform-specific behavior
1844 /// This function currently corresponds to the `readlink` function on Unix
1845 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1846 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1847 /// Note that, this [may change in the future][changes].
1849 /// [changes]: io#platform-specific-behavior
1853 /// This function will return an error in the following situations, but is not
1854 /// limited to just these cases:
1856 /// * `path` is not a symbolic link.
1857 /// * `path` does not exist.
1864 /// fn main() -> std::io::Result<()> {
1865 /// let path = fs::read_link("a.txt")?;
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1871 fs_imp::readlink(path.as_ref())
1874 /// Returns the canonical, absolute form of a path with all intermediate
1875 /// components normalized and symbolic links resolved.
1877 /// # Platform-specific behavior
1879 /// This function currently corresponds to the `realpath` function on Unix
1880 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1881 /// Note that, this [may change in the future][changes].
1883 /// On Windows, this converts the path to use [extended length path][path]
1884 /// syntax, which allows your program to use longer path names, but means you
1885 /// can only join backslash-delimited paths to it, and it may be incompatible
1886 /// with other applications (if passed to the application on the command-line,
1887 /// or written to a file another application may read).
1889 /// [changes]: io#platform-specific-behavior
1890 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1894 /// This function will return an error in the following situations, but is not
1895 /// limited to just these cases:
1897 /// * `path` does not exist.
1898 /// * A non-final component in path is not a directory.
1905 /// fn main() -> std::io::Result<()> {
1906 /// let path = fs::canonicalize("../a/../foo.txt")?;
1910 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1911 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1912 fs_imp::canonicalize(path.as_ref())
1915 /// Creates a new, empty directory at the provided path
1917 /// # Platform-specific behavior
1919 /// This function currently corresponds to the `mkdir` function on Unix
1920 /// and the `CreateDirectory` function on Windows.
1921 /// Note that, this [may change in the future][changes].
1923 /// [changes]: io#platform-specific-behavior
1925 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1926 /// return an error. To create a directory and all its missing parents at the
1927 /// same time, use the [`create_dir_all`] function.
1931 /// This function will return an error in the following situations, but is not
1932 /// limited to just these cases:
1934 /// * User lacks permissions to create directory at `path`.
1935 /// * A parent of the given path doesn't exist. (To create a directory and all
1936 /// its missing parents at the same time, use the [`create_dir_all`]
1938 /// * `path` already exists.
1945 /// fn main() -> std::io::Result<()> {
1946 /// fs::create_dir("/some/dir")?;
1950 #[doc(alias = "mkdir")]
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1953 DirBuilder::new().create(path.as_ref())
1956 /// Recursively create a directory and all of its parent components if they
1959 /// # Platform-specific behavior
1961 /// This function currently corresponds to the `mkdir` function on Unix
1962 /// and the `CreateDirectory` function on Windows.
1963 /// Note that, this [may change in the future][changes].
1965 /// [changes]: io#platform-specific-behavior
1969 /// This function will return an error in the following situations, but is not
1970 /// limited to just these cases:
1972 /// * If any directory in the path specified by `path`
1973 /// does not already exist and it could not be created otherwise. The specific
1974 /// error conditions for when a directory is being created (after it is
1975 /// determined to not exist) are outlined by [`fs::create_dir`].
1977 /// Notable exception is made for situations where any of the directories
1978 /// specified in the `path` could not be created as it was being created concurrently.
1979 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1980 /// concurrently from multiple threads or processes is guaranteed not to fail
1981 /// due to a race condition with itself.
1983 /// [`fs::create_dir`]: create_dir
1990 /// fn main() -> std::io::Result<()> {
1991 /// fs::create_dir_all("/some/dir")?;
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1997 DirBuilder::new().recursive(true).create(path.as_ref())
2000 /// Removes an empty directory.
2002 /// # Platform-specific behavior
2004 /// This function currently corresponds to the `rmdir` function on Unix
2005 /// and the `RemoveDirectory` function on Windows.
2006 /// Note that, this [may change in the future][changes].
2008 /// [changes]: io#platform-specific-behavior
2012 /// This function will return an error in the following situations, but is not
2013 /// limited to just these cases:
2015 /// * `path` doesn't exist.
2016 /// * `path` isn't a directory.
2017 /// * The user lacks permissions to remove the directory at the provided `path`.
2018 /// * The directory isn't empty.
2025 /// fn main() -> std::io::Result<()> {
2026 /// fs::remove_dir("/some/dir")?;
2030 #[doc(alias = "rmdir")]
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2033 fs_imp::rmdir(path.as_ref())
2036 /// Removes a directory at this path, after removing all its contents. Use
2039 /// This function does **not** follow symbolic links and it will simply remove the
2040 /// symbolic link itself.
2042 /// # Platform-specific behavior
2044 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2045 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2047 /// Note that, this [may change in the future][changes].
2049 /// [changes]: io#platform-specific-behavior
2053 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2055 /// [`fs::remove_file`]: remove_file
2056 /// [`fs::remove_dir`]: remove_dir
2063 /// fn main() -> std::io::Result<()> {
2064 /// fs::remove_dir_all("/some/dir")?;
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2070 fs_imp::remove_dir_all(path.as_ref())
2073 /// Returns an iterator over the entries within a directory.
2075 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2076 /// New errors may be encountered after an iterator is initially constructed.
2077 /// Entries for the current and parent directories (typically `.` and `..`) are
2080 /// # Platform-specific behavior
2082 /// This function currently corresponds to the `opendir` function on Unix
2083 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2084 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2085 /// Note that, this [may change in the future][changes].
2087 /// [changes]: io#platform-specific-behavior
2089 /// The order in which this iterator returns entries is platform and filesystem
2094 /// This function will return an error in the following situations, but is not
2095 /// limited to just these cases:
2097 /// * The provided `path` doesn't exist.
2098 /// * The process lacks permissions to view the contents.
2099 /// * The `path` points at a non-directory file.
2105 /// use std::fs::{self, DirEntry};
2106 /// use std::path::Path;
2108 /// // one possible implementation of walking a directory only visiting files
2109 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2110 /// if dir.is_dir() {
2111 /// for entry in fs::read_dir(dir)? {
2112 /// let entry = entry?;
2113 /// let path = entry.path();
2114 /// if path.is_dir() {
2115 /// visit_dirs(&path, cb)?;
2126 /// use std::{fs, io};
2128 /// fn main() -> io::Result<()> {
2129 /// let mut entries = fs::read_dir(".")?
2130 /// .map(|res| res.map(|e| e.path()))
2131 /// .collect::<Result<Vec<_>, io::Error>>()?;
2133 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2134 /// // ordering is required the entries should be explicitly sorted.
2138 /// // The entries have now been sorted by their path.
2143 #[stable(feature = "rust1", since = "1.0.0")]
2144 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2145 fs_imp::readdir(path.as_ref()).map(ReadDir)
2148 /// Changes the permissions found on a file or a directory.
2150 /// # Platform-specific behavior
2152 /// This function currently corresponds to the `chmod` function on Unix
2153 /// and the `SetFileAttributes` function on Windows.
2154 /// Note that, this [may change in the future][changes].
2156 /// [changes]: io#platform-specific-behavior
2160 /// This function will return an error in the following situations, but is not
2161 /// limited to just these cases:
2163 /// * `path` does not exist.
2164 /// * The user lacks the permission to change attributes of the file.
2171 /// fn main() -> std::io::Result<()> {
2172 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2173 /// perms.set_readonly(true);
2174 /// fs::set_permissions("foo.txt", perms)?;
2178 #[stable(feature = "set_permissions", since = "1.1.0")]
2179 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2180 fs_imp::set_perm(path.as_ref(), perm.0)
2184 /// Creates a new set of options with default mode/security settings for all
2185 /// platforms and also non-recursive.
2190 /// use std::fs::DirBuilder;
2192 /// let builder = DirBuilder::new();
2194 #[stable(feature = "dir_builder", since = "1.6.0")]
2196 pub fn new() -> DirBuilder {
2197 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2200 /// Indicates that directories should be created recursively, creating all
2201 /// parent directories. Parents that do not exist are created with the same
2202 /// security and permissions settings.
2204 /// This option defaults to `false`.
2209 /// use std::fs::DirBuilder;
2211 /// let mut builder = DirBuilder::new();
2212 /// builder.recursive(true);
2214 #[stable(feature = "dir_builder", since = "1.6.0")]
2215 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2216 self.recursive = recursive;
2220 /// Creates the specified directory with the options configured in this
2223 /// It is considered an error if the directory already exists unless
2224 /// recursive mode is enabled.
2229 /// use std::fs::{self, DirBuilder};
2231 /// let path = "/tmp/foo/bar/baz";
2232 /// DirBuilder::new()
2233 /// .recursive(true)
2234 /// .create(path).unwrap();
2236 /// assert!(fs::metadata(path).unwrap().is_dir());
2238 #[stable(feature = "dir_builder", since = "1.6.0")]
2239 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2240 self._create(path.as_ref())
2243 fn _create(&self, path: &Path) -> io::Result<()> {
2244 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2247 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2248 if path == Path::new("") {
2252 match self.inner.mkdir(path) {
2253 Ok(()) => return Ok(()),
2254 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2255 Err(_) if path.is_dir() => return Ok(()),
2256 Err(e) => return Err(e),
2258 match path.parent() {
2259 Some(p) => self.create_dir_all(p)?,
2261 return Err(io::Error::new_const(
2262 io::ErrorKind::Uncategorized,
2263 &"failed to create whole tree",
2267 match self.inner.mkdir(path) {
2269 Err(_) if path.is_dir() => Ok(()),
2275 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2276 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2281 /// Returns `Ok(true)` if the path points at an existing entity.
2283 /// This function will traverse symbolic links to query information about the
2284 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2286 /// As opposed to the `exists()` method, this one doesn't silently ignore errors
2287 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2288 /// denied on some of the parent directories.)
2293 /// #![feature(path_try_exists)]
2296 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2297 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2299 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2301 #[unstable(feature = "path_try_exists", issue = "83186")]
2303 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2304 fs_imp::try_exists(path.as_ref())