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
361 /// `OpenOptions::new().append(true).open("example.log")`,
362 /// you can write `File::options().append(true).open("example.log")`. This
363 /// also avoids the need to import `OpenOptions`.
365 /// See the [`OpenOptions::new`] function for more details.
370 /// use std::fs::File;
372 /// fn main() -> std::io::Result<()> {
373 /// let mut f = File::options().append(true).open("example.log")?;
378 #[stable(feature = "with_options", since = "1.58.0")]
379 pub fn options() -> OpenOptions {
383 /// Attempts to sync all OS-internal metadata to disk.
385 /// This function will attempt to ensure that all in-memory data reaches the
386 /// filesystem before returning.
388 /// This can be used to handle errors that would otherwise only be caught
389 /// when the `File` is closed. Dropping a file will ignore errors in
390 /// synchronizing this in-memory data.
395 /// use std::fs::File;
396 /// use std::io::prelude::*;
398 /// fn main() -> std::io::Result<()> {
399 /// let mut f = File::create("foo.txt")?;
400 /// f.write_all(b"Hello, world!")?;
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn sync_all(&self) -> io::Result<()> {
411 /// This function is similar to [`sync_all`], except that it might not
412 /// synchronize file metadata to the filesystem.
414 /// This is intended for use cases that must synchronize content, but don't
415 /// need the metadata on disk. The goal of this method is to reduce disk
418 /// Note that some platforms may simply implement this in terms of
421 /// [`sync_all`]: File::sync_all
426 /// use std::fs::File;
427 /// use std::io::prelude::*;
429 /// fn main() -> std::io::Result<()> {
430 /// let mut f = File::create("foo.txt")?;
431 /// f.write_all(b"Hello, world!")?;
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn sync_data(&self) -> io::Result<()> {
439 self.inner.datasync()
442 /// Truncates or extends the underlying file, updating the size of
443 /// this file to become `size`.
445 /// If the `size` is less than the current file's size, then the file will
446 /// be shrunk. If it is greater than the current file's size, then the file
447 /// will be extended to `size` and have all of the intermediate data filled
450 /// The file's cursor isn't changed. In particular, if the cursor was at the
451 /// end and the file is shrunk using this operation, the cursor will now be
456 /// This function will return an error if the file is not opened for writing.
457 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
458 /// length would cause an overflow due to the implementation specifics.
463 /// use std::fs::File;
465 /// fn main() -> std::io::Result<()> {
466 /// let mut f = File::create("foo.txt")?;
472 /// Note that this method alters the content of the underlying file, even
473 /// though it takes `&self` rather than `&mut self`.
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn set_len(&self, size: u64) -> io::Result<()> {
476 self.inner.truncate(size)
479 /// Queries metadata about the underlying file.
484 /// use std::fs::File;
486 /// fn main() -> std::io::Result<()> {
487 /// let mut f = File::open("foo.txt")?;
488 /// let metadata = f.metadata()?;
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn metadata(&self) -> io::Result<Metadata> {
494 self.inner.file_attr().map(Metadata)
497 /// Creates a new `File` instance that shares the same underlying file handle
498 /// as the existing `File` instance. Reads, writes, and seeks will affect
499 /// both `File` instances simultaneously.
503 /// Creates two handles for a file named `foo.txt`:
506 /// use std::fs::File;
508 /// fn main() -> std::io::Result<()> {
509 /// let mut file = File::open("foo.txt")?;
510 /// let file_copy = file.try_clone()?;
515 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
516 /// two handles, seek one of them, and read the remaining bytes from the
520 /// use std::fs::File;
521 /// use std::io::SeekFrom;
522 /// use std::io::prelude::*;
524 /// fn main() -> std::io::Result<()> {
525 /// let mut file = File::open("foo.txt")?;
526 /// let mut file_copy = file.try_clone()?;
528 /// file.seek(SeekFrom::Start(3))?;
530 /// let mut contents = vec![];
531 /// file_copy.read_to_end(&mut contents)?;
532 /// assert_eq!(contents, b"def\n");
536 #[stable(feature = "file_try_clone", since = "1.9.0")]
537 pub fn try_clone(&self) -> io::Result<File> {
538 Ok(File { inner: self.inner.duplicate()? })
541 /// Changes the permissions on the underlying file.
543 /// # Platform-specific behavior
545 /// This function currently corresponds to the `fchmod` function on Unix and
546 /// the `SetFileInformationByHandle` function on Windows. Note that, this
547 /// [may change in the future][changes].
549 /// [changes]: io#platform-specific-behavior
553 /// This function will return an error if the user lacks permission change
554 /// attributes on the underlying file. It may also return an error in other
555 /// os-specific unspecified cases.
560 /// fn main() -> std::io::Result<()> {
561 /// use std::fs::File;
563 /// let file = File::open("foo.txt")?;
564 /// let mut perms = file.metadata()?.permissions();
565 /// perms.set_readonly(true);
566 /// file.set_permissions(perms)?;
571 /// Note that this method alters the permissions of the underlying file,
572 /// even though it takes `&self` rather than `&mut self`.
573 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
574 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
575 self.inner.set_permissions(perm.0)
579 // In addition to the `impl`s here, `File` also has `impl`s for
580 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
581 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
582 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
583 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
585 impl AsInner<fs_imp::File> for File {
586 fn as_inner(&self) -> &fs_imp::File {
590 impl FromInner<fs_imp::File> for File {
591 fn from_inner(f: fs_imp::File) -> File {
595 impl IntoInner<fs_imp::File> for File {
596 fn into_inner(self) -> fs_imp::File {
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl fmt::Debug for File {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 /// Indicates how much extra capacity is needed to read the rest of the file.
609 fn buffer_capacity_required(mut file: &File) -> usize {
610 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
611 let pos = file.stream_position().unwrap_or(0);
612 // Don't worry about `usize` overflow because reading will fail regardless
614 size.saturating_sub(pos) as usize
617 #[stable(feature = "rust1", since = "1.0.0")]
619 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
623 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
624 self.inner.read_vectored(bufs)
627 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
628 self.inner.read_buf(buf)
632 fn is_read_vectored(&self) -> bool {
633 self.inner.is_read_vectored()
636 // Reserves space in the buffer based on the file size when available.
637 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
638 buf.reserve(buffer_capacity_required(self));
639 io::default_read_to_end(self, buf)
642 // Reserves space in the buffer based on the file size when available.
643 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
644 buf.reserve(buffer_capacity_required(self));
645 io::default_read_to_string(self, buf)
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl Write for File {
650 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
651 self.inner.write(buf)
654 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
655 self.inner.write_vectored(bufs)
659 fn is_write_vectored(&self) -> bool {
660 self.inner.is_write_vectored()
663 fn flush(&mut self) -> io::Result<()> {
667 #[stable(feature = "rust1", since = "1.0.0")]
669 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl Read for &File {
675 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
679 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
680 self.inner.read_buf(buf)
683 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
684 self.inner.read_vectored(bufs)
688 fn is_read_vectored(&self) -> bool {
689 self.inner.is_read_vectored()
692 // Reserves space in the buffer based on the file size when available.
693 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
694 buf.reserve(buffer_capacity_required(self));
695 io::default_read_to_end(self, buf)
698 // Reserves space in the buffer based on the file size when available.
699 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
700 buf.reserve(buffer_capacity_required(self));
701 io::default_read_to_string(self, buf)
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl Write for &File {
706 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
707 self.inner.write(buf)
710 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
711 self.inner.write_vectored(bufs)
715 fn is_write_vectored(&self) -> bool {
716 self.inner.is_write_vectored()
719 fn flush(&mut self) -> io::Result<()> {
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl Seek for &File {
725 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
731 /// Creates a blank new set of options ready for configuration.
733 /// All options are initially set to `false`.
738 /// use std::fs::OpenOptions;
740 /// let mut options = OpenOptions::new();
741 /// let file = options.read(true).open("foo.txt");
743 #[stable(feature = "rust1", since = "1.0.0")]
745 pub fn new() -> Self {
746 OpenOptions(fs_imp::OpenOptions::new())
749 /// Sets the option for read access.
751 /// This option, when true, will indicate that the file should be
752 /// `read`-able if opened.
757 /// use std::fs::OpenOptions;
759 /// let file = OpenOptions::new().read(true).open("foo.txt");
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn read(&mut self, read: bool) -> &mut Self {
767 /// Sets the option for write access.
769 /// This option, when true, will indicate that the file should be
770 /// `write`-able if opened.
772 /// If the file already exists, any write calls on it will overwrite its
773 /// contents, without truncating it.
778 /// use std::fs::OpenOptions;
780 /// let file = OpenOptions::new().write(true).open("foo.txt");
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn write(&mut self, write: bool) -> &mut Self {
788 /// Sets the option for the append mode.
790 /// This option, when true, means that writes will append to a file instead
791 /// of overwriting previous contents.
792 /// Note that setting `.write(true).append(true)` has the same effect as
793 /// setting only `.append(true)`.
795 /// For most filesystems, the operating system guarantees that all writes are
796 /// atomic: no writes get mangled because another process writes at the same
799 /// One maybe obvious note when using append-mode: make sure that all data
800 /// that belongs together is written to the file in one operation. This
801 /// can be done by concatenating strings before passing them to [`write()`],
802 /// or using a buffered writer (with a buffer of adequate size),
803 /// and calling [`flush()`] when the message is complete.
805 /// If a file is opened with both read and append access, beware that after
806 /// opening, and after every write, the position for reading may be set at the
807 /// end of the file. So, before writing, save the current position (using
808 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
812 /// This function doesn't create the file if it doesn't exist. Use the
813 /// [`OpenOptions::create`] method to do so.
815 /// [`write()`]: Write::write "io::Write::write"
816 /// [`flush()`]: Write::flush "io::Write::flush"
817 /// [seek]: Seek::seek "io::Seek::seek"
818 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
823 /// use std::fs::OpenOptions;
825 /// let file = OpenOptions::new().append(true).open("foo.txt");
827 #[stable(feature = "rust1", since = "1.0.0")]
828 pub fn append(&mut self, append: bool) -> &mut Self {
829 self.0.append(append);
833 /// Sets the option for truncating a previous file.
835 /// If a file is successfully opened with this option set it will truncate
836 /// the file to 0 length if it already exists.
838 /// The file must be opened with write access for truncate to work.
843 /// use std::fs::OpenOptions;
845 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
849 self.0.truncate(truncate);
853 /// Sets the option to create a new file, or open it if it already exists.
855 /// In order for the file to be created, [`OpenOptions::write`] or
856 /// [`OpenOptions::append`] access must be used.
861 /// use std::fs::OpenOptions;
863 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
865 #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn create(&mut self, create: bool) -> &mut Self {
867 self.0.create(create);
871 /// Sets the option to create a new file, failing if it already exists.
873 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
874 /// way, if the call succeeds, the file returned is guaranteed to be new.
876 /// This option is useful because it is atomic. Otherwise between checking
877 /// whether a file exists and creating a new one, the file may have been
878 /// created by another process (a TOCTOU race condition / attack).
880 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
883 /// The file must be opened with write or append access in order to create
886 /// [`.create()`]: OpenOptions::create
887 /// [`.truncate()`]: OpenOptions::truncate
892 /// use std::fs::OpenOptions;
894 /// let file = OpenOptions::new().write(true)
895 /// .create_new(true)
896 /// .open("foo.txt");
898 #[stable(feature = "expand_open_options2", since = "1.9.0")]
899 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
900 self.0.create_new(create_new);
904 /// Opens a file at `path` with the options specified by `self`.
908 /// This function will return an error under a number of different
909 /// circumstances. Some of these error conditions are listed here, together
910 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
911 /// part of the compatibility contract of the function.
913 /// * [`NotFound`]: The specified file does not exist and neither `create`
914 /// or `create_new` is set.
915 /// * [`NotFound`]: One of the directory components of the file path does
917 /// * [`PermissionDenied`]: The user lacks permission to get the specified
918 /// access rights for the file.
919 /// * [`PermissionDenied`]: The user lacks permission to open one of the
920 /// directory components of the specified path.
921 /// * [`AlreadyExists`]: `create_new` was specified and the file already
923 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
924 /// without write access, no access mode set, etc.).
926 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
927 /// * One of the directory components of the specified file path
928 /// was not, in fact, a directory.
929 /// * Filesystem-level errors: full disk, write permission
930 /// requested on a read-only file system, exceeded disk quota, too many
931 /// open files, too long filename, too many symbolic links in the
932 /// specified path (Unix-like systems only), etc.
937 /// use std::fs::OpenOptions;
939 /// let file = OpenOptions::new().read(true).open("foo.txt");
942 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
943 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
944 /// [`NotFound`]: io::ErrorKind::NotFound
945 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
946 #[stable(feature = "rust1", since = "1.0.0")]
947 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
948 self._open(path.as_ref())
951 fn _open(&self, path: &Path) -> io::Result<File> {
952 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
956 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
957 fn as_inner(&self) -> &fs_imp::OpenOptions {
962 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
963 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
969 /// Returns the file type for this metadata.
974 /// fn main() -> std::io::Result<()> {
977 /// let metadata = fs::metadata("foo.txt")?;
979 /// println!("{:?}", metadata.file_type());
984 #[stable(feature = "file_type", since = "1.1.0")]
985 pub fn file_type(&self) -> FileType {
986 FileType(self.0.file_type())
989 /// Returns `true` if this metadata is for a directory. The
990 /// result is mutually exclusive to the result of
991 /// [`Metadata::is_file`], and will be false for symlink metadata
992 /// obtained from [`symlink_metadata`].
997 /// fn main() -> std::io::Result<()> {
1000 /// let metadata = fs::metadata("foo.txt")?;
1002 /// assert!(!metadata.is_dir());
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn is_dir(&self) -> bool {
1009 self.file_type().is_dir()
1012 /// Returns `true` if this metadata is for a regular file. The
1013 /// result is mutually exclusive to the result of
1014 /// [`Metadata::is_dir`], and will be false for symlink metadata
1015 /// obtained from [`symlink_metadata`].
1017 /// When the goal is simply to read from (or write to) the source, the most
1018 /// reliable way to test the source can be read (or written to) is to open
1019 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1020 /// a Unix-like system for example. See [`File::open`] or
1021 /// [`OpenOptions::open`] for more information.
1028 /// fn main() -> std::io::Result<()> {
1029 /// let metadata = fs::metadata("foo.txt")?;
1031 /// assert!(metadata.is_file());
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn is_file(&self) -> bool {
1038 self.file_type().is_file()
1041 /// Returns `true` if this metadata is for a symbolic link.
1045 #[cfg_attr(unix, doc = "```no_run")]
1046 #[cfg_attr(not(unix), doc = "```ignore")]
1048 /// use std::path::Path;
1049 /// use std::os::unix::fs::symlink;
1051 /// fn main() -> std::io::Result<()> {
1052 /// let link_path = Path::new("link");
1053 /// symlink("/origin_does_not_exist/", link_path)?;
1055 /// let metadata = fs::symlink_metadata(link_path)?;
1057 /// assert!(metadata.is_symlink());
1062 #[stable(feature = "is_symlink", since = "1.58.0")]
1063 pub fn is_symlink(&self) -> bool {
1064 self.file_type().is_symlink()
1067 /// Returns the size of the file, in bytes, this metadata is for.
1074 /// fn main() -> std::io::Result<()> {
1075 /// let metadata = fs::metadata("foo.txt")?;
1077 /// assert_eq!(0, metadata.len());
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub fn len(&self) -> u64 {
1087 /// Returns the permissions of the file this metadata is for.
1094 /// fn main() -> std::io::Result<()> {
1095 /// let metadata = fs::metadata("foo.txt")?;
1097 /// assert!(!metadata.permissions().readonly());
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 pub fn permissions(&self) -> Permissions {
1104 Permissions(self.0.perm())
1107 /// Returns the last modification time listed in this metadata.
1109 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1110 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1114 /// This field might not be available on all platforms, and will return an
1115 /// `Err` on platforms where it is not available.
1122 /// fn main() -> std::io::Result<()> {
1123 /// let metadata = fs::metadata("foo.txt")?;
1125 /// if let Ok(time) = metadata.modified() {
1126 /// println!("{time:?}");
1128 /// println!("Not supported on this platform");
1133 #[stable(feature = "fs_time", since = "1.10.0")]
1134 pub fn modified(&self) -> io::Result<SystemTime> {
1135 self.0.modified().map(FromInner::from_inner)
1138 /// Returns the last access time of this metadata.
1140 /// The returned value corresponds to the `atime` field of `stat` on Unix
1141 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1143 /// Note that not all platforms will keep this field update in a file's
1144 /// metadata, for example Windows has an option to disable updating this
1145 /// time when files are accessed and Linux similarly has `noatime`.
1149 /// This field might not be available on all platforms, and will return an
1150 /// `Err` on platforms where it is not available.
1157 /// fn main() -> std::io::Result<()> {
1158 /// let metadata = fs::metadata("foo.txt")?;
1160 /// if let Ok(time) = metadata.accessed() {
1161 /// println!("{time:?}");
1163 /// println!("Not supported on this platform");
1168 #[stable(feature = "fs_time", since = "1.10.0")]
1169 pub fn accessed(&self) -> io::Result<SystemTime> {
1170 self.0.accessed().map(FromInner::from_inner)
1173 /// Returns the creation time listed in this metadata.
1175 /// The returned value corresponds to the `btime` field of `statx` on
1176 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1177 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1181 /// This field might not be available on all platforms, and will return an
1182 /// `Err` on platforms or filesystems where it is not available.
1189 /// fn main() -> std::io::Result<()> {
1190 /// let metadata = fs::metadata("foo.txt")?;
1192 /// if let Ok(time) = metadata.created() {
1193 /// println!("{time:?}");
1195 /// println!("Not supported on this platform or filesystem");
1200 #[stable(feature = "fs_time", since = "1.10.0")]
1201 pub fn created(&self) -> io::Result<SystemTime> {
1202 self.0.created().map(FromInner::from_inner)
1206 #[stable(feature = "std_debug", since = "1.16.0")]
1207 impl fmt::Debug for Metadata {
1208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1209 f.debug_struct("Metadata")
1210 .field("file_type", &self.file_type())
1211 .field("is_dir", &self.is_dir())
1212 .field("is_file", &self.is_file())
1213 .field("permissions", &self.permissions())
1214 .field("modified", &self.modified())
1215 .field("accessed", &self.accessed())
1216 .field("created", &self.created())
1217 .finish_non_exhaustive()
1221 impl AsInner<fs_imp::FileAttr> for Metadata {
1222 fn as_inner(&self) -> &fs_imp::FileAttr {
1227 impl FromInner<fs_imp::FileAttr> for Metadata {
1228 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1234 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1239 /// use std::fs::File;
1241 /// fn main() -> std::io::Result<()> {
1242 /// let mut f = File::create("foo.txt")?;
1243 /// let metadata = f.metadata()?;
1245 /// assert_eq!(false, metadata.permissions().readonly());
1249 #[must_use = "call `set_readonly` to modify the readonly flag"]
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 pub fn readonly(&self) -> bool {
1255 /// Modifies the readonly flag for this set of permissions. If the
1256 /// `readonly` argument is `true`, using the resulting `Permission` will
1257 /// update file permissions to forbid writing. Conversely, if it's `false`,
1258 /// using the resulting `Permission` will update file permissions to allow
1261 /// This operation does **not** modify the filesystem. To modify the
1262 /// filesystem use the [`set_permissions`] function.
1267 /// use std::fs::File;
1269 /// fn main() -> std::io::Result<()> {
1270 /// let f = File::create("foo.txt")?;
1271 /// let metadata = f.metadata()?;
1272 /// let mut permissions = metadata.permissions();
1274 /// permissions.set_readonly(true);
1276 /// // filesystem doesn't change
1277 /// assert_eq!(false, metadata.permissions().readonly());
1279 /// // just this particular `permissions`.
1280 /// assert_eq!(true, permissions.readonly());
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub fn set_readonly(&mut self, readonly: bool) {
1286 self.0.set_readonly(readonly)
1291 /// Tests whether this file type represents a directory. The
1292 /// result is mutually exclusive to the results of
1293 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1296 /// [`is_file`]: FileType::is_file
1297 /// [`is_symlink`]: FileType::is_symlink
1302 /// fn main() -> std::io::Result<()> {
1305 /// let metadata = fs::metadata("foo.txt")?;
1306 /// let file_type = metadata.file_type();
1308 /// assert_eq!(file_type.is_dir(), false);
1313 #[stable(feature = "file_type", since = "1.1.0")]
1314 pub fn is_dir(&self) -> bool {
1318 /// Tests whether this file type represents a regular file.
1319 /// The result is mutually exclusive to the results of
1320 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1323 /// When the goal is simply to read from (or write to) the source, the most
1324 /// reliable way to test the source can be read (or written to) is to open
1325 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1326 /// a Unix-like system for example. See [`File::open`] or
1327 /// [`OpenOptions::open`] for more information.
1329 /// [`is_dir`]: FileType::is_dir
1330 /// [`is_symlink`]: FileType::is_symlink
1335 /// fn main() -> std::io::Result<()> {
1338 /// let metadata = fs::metadata("foo.txt")?;
1339 /// let file_type = metadata.file_type();
1341 /// assert_eq!(file_type.is_file(), true);
1346 #[stable(feature = "file_type", since = "1.1.0")]
1347 pub fn is_file(&self) -> bool {
1351 /// Tests whether this file type represents a symbolic link.
1352 /// The result is mutually exclusive to the results of
1353 /// [`is_dir`] and [`is_file`]; only zero or one of these
1356 /// The underlying [`Metadata`] struct needs to be retrieved
1357 /// with the [`fs::symlink_metadata`] function and not the
1358 /// [`fs::metadata`] function. The [`fs::metadata`] function
1359 /// follows symbolic links, so [`is_symlink`] would always
1360 /// return `false` for the target file.
1362 /// [`fs::metadata`]: metadata
1363 /// [`fs::symlink_metadata`]: symlink_metadata
1364 /// [`is_dir`]: FileType::is_dir
1365 /// [`is_file`]: FileType::is_file
1366 /// [`is_symlink`]: FileType::is_symlink
1373 /// fn main() -> std::io::Result<()> {
1374 /// let metadata = fs::symlink_metadata("foo.txt")?;
1375 /// let file_type = metadata.file_type();
1377 /// assert_eq!(file_type.is_symlink(), false);
1382 #[stable(feature = "file_type", since = "1.1.0")]
1383 pub fn is_symlink(&self) -> bool {
1388 impl AsInner<fs_imp::FileType> for FileType {
1389 fn as_inner(&self) -> &fs_imp::FileType {
1394 impl FromInner<fs_imp::FilePermissions> for Permissions {
1395 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1400 impl AsInner<fs_imp::FilePermissions> for Permissions {
1401 fn as_inner(&self) -> &fs_imp::FilePermissions {
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl Iterator for ReadDir {
1408 type Item = io::Result<DirEntry>;
1410 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1411 self.0.next().map(|entry| entry.map(DirEntry))
1416 /// Returns the full path to the file that this entry represents.
1418 /// The full path is created by joining the original path to `read_dir`
1419 /// with the filename of this entry.
1426 /// fn main() -> std::io::Result<()> {
1427 /// for entry in fs::read_dir(".")? {
1428 /// let dir = entry?;
1429 /// println!("{:?}", dir.path());
1435 /// This prints output like:
1438 /// "./whatever.txt"
1440 /// "./hello_world.rs"
1443 /// The exact text, of course, depends on what files you have in `.`.
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn path(&self) -> PathBuf {
1450 /// Returns the metadata for the file that this entry points at.
1452 /// This function will not traverse symlinks if this entry points at a
1453 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1455 /// [`fs::metadata`]: metadata
1456 /// [`fs::File::metadata`]: File::metadata
1458 /// # Platform-specific behavior
1460 /// On Windows this function is cheap to call (no extra system calls
1461 /// needed), but on Unix platforms this function is the equivalent of
1462 /// calling `symlink_metadata` on the path.
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(metadata) = entry.metadata() {
1474 /// // Now let's show our entry's permissions!
1475 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1477 /// println!("Couldn't get metadata for {:?}", entry.path());
1483 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1484 pub fn metadata(&self) -> io::Result<Metadata> {
1485 self.0.metadata().map(Metadata)
1488 /// Returns the file type for the file that this entry points at.
1490 /// This function will not traverse symlinks if this entry points at a
1493 /// # Platform-specific behavior
1495 /// On Windows and most Unix platforms this function is free (no extra
1496 /// system calls needed), but some Unix platforms may require the equivalent
1497 /// call to `symlink_metadata` to learn about the target file type.
1504 /// if let Ok(entries) = fs::read_dir(".") {
1505 /// for entry in entries {
1506 /// if let Ok(entry) = entry {
1507 /// // Here, `entry` is a `DirEntry`.
1508 /// if let Ok(file_type) = entry.file_type() {
1509 /// // Now let's show our entry's file type!
1510 /// println!("{:?}: {:?}", entry.path(), file_type);
1512 /// println!("Couldn't get file type for {:?}", entry.path());
1518 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1519 pub fn file_type(&self) -> io::Result<FileType> {
1520 self.0.file_type().map(FileType)
1523 /// Returns the bare file name of this directory entry without any other
1524 /// leading path component.
1531 /// if let Ok(entries) = fs::read_dir(".") {
1532 /// for entry in entries {
1533 /// if let Ok(entry) = entry {
1534 /// // Here, `entry` is a `DirEntry`.
1535 /// println!("{:?}", entry.file_name());
1541 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1542 pub fn file_name(&self) -> OsString {
1547 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1548 impl fmt::Debug for DirEntry {
1549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550 f.debug_tuple("DirEntry").field(&self.path()).finish()
1554 impl AsInner<fs_imp::DirEntry> for DirEntry {
1555 fn as_inner(&self) -> &fs_imp::DirEntry {
1560 /// Removes a file from the filesystem.
1562 /// Note that there is no
1563 /// guarantee that the file is immediately deleted (e.g., depending on
1564 /// platform, other open file descriptors may prevent immediate removal).
1566 /// # Platform-specific behavior
1568 /// This function currently corresponds to the `unlink` function on Unix
1569 /// and the `DeleteFile` function on Windows.
1570 /// Note that, this [may change in the future][changes].
1572 /// [changes]: io#platform-specific-behavior
1576 /// This function will return an error in the following situations, but is not
1577 /// limited to just these cases:
1579 /// * `path` points to a directory.
1580 /// * The file doesn't exist.
1581 /// * The user lacks permissions to remove the file.
1588 /// fn main() -> std::io::Result<()> {
1589 /// fs::remove_file("a.txt")?;
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1595 fs_imp::unlink(path.as_ref())
1598 /// Given a path, query the file system to get information about a file,
1601 /// This function will traverse symbolic links to query information about the
1602 /// destination file.
1604 /// # Platform-specific behavior
1606 /// This function currently corresponds to the `stat` function on Unix
1607 /// and the `GetFileAttributesEx` function on Windows.
1608 /// Note that, this [may change in the future][changes].
1610 /// [changes]: io#platform-specific-behavior
1614 /// This function will return an error in the following situations, but is not
1615 /// limited to just these cases:
1617 /// * The user lacks permissions to perform `metadata` call on `path`.
1618 /// * `path` does not exist.
1625 /// fn main() -> std::io::Result<()> {
1626 /// let attr = fs::metadata("/some/file/path.txt")?;
1627 /// // inspect attr ...
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1633 fs_imp::stat(path.as_ref()).map(Metadata)
1636 /// Query the metadata about a file without following symlinks.
1638 /// # Platform-specific behavior
1640 /// This function currently corresponds to the `lstat` function on Unix
1641 /// and the `GetFileAttributesEx` function on Windows.
1642 /// Note that, this [may change in the future][changes].
1644 /// [changes]: io#platform-specific-behavior
1648 /// This function will return an error in the following situations, but is not
1649 /// limited to just these cases:
1651 /// * The user lacks permissions to perform `metadata` call on `path`.
1652 /// * `path` does not exist.
1659 /// fn main() -> std::io::Result<()> {
1660 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1661 /// // inspect attr ...
1665 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1666 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1667 fs_imp::lstat(path.as_ref()).map(Metadata)
1670 /// Rename a file or directory to a new name, replacing the original file if
1671 /// `to` already exists.
1673 /// This will not work if the new name is on a different mount point.
1675 /// # Platform-specific behavior
1677 /// This function currently corresponds to the `rename` function on Unix
1678 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1680 /// Because of this, the behavior when both `from` and `to` exist differs. On
1681 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1682 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1683 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1685 /// Note that, this [may change in the future][changes].
1687 /// [changes]: io#platform-specific-behavior
1691 /// This function will return an error in the following situations, but is not
1692 /// limited to just these cases:
1694 /// * `from` does not exist.
1695 /// * The user lacks permissions to view contents.
1696 /// * `from` and `to` are on separate filesystems.
1703 /// fn main() -> std::io::Result<()> {
1704 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1710 fs_imp::rename(from.as_ref(), to.as_ref())
1713 /// Copies the contents of one file to another. This function will also
1714 /// copy the permission bits of the original file to the destination file.
1716 /// This function will **overwrite** the contents of `to`.
1718 /// Note that if `from` and `to` both point to the same file, then the file
1719 /// will likely get truncated by this operation.
1721 /// On success, the total number of bytes copied is returned and it is equal to
1722 /// the length of the `to` file as reported by `metadata`.
1724 /// If you’re wanting to copy the contents of one file to another and you’re
1725 /// working with [`File`]s, see the [`io::copy()`] function.
1727 /// # Platform-specific behavior
1729 /// This function currently corresponds to the `open` function in Unix
1730 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1731 /// `O_CLOEXEC` is set for returned file descriptors.
1733 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1734 /// and falls back to reading and writing if that is not possible.
1736 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1737 /// NTFS streams are copied but only the size of the main stream is returned by
1740 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1742 /// Note that platform-specific behavior [may change in the future][changes].
1744 /// [changes]: io#platform-specific-behavior
1748 /// This function will return an error in the following situations, but is not
1749 /// limited to just these cases:
1751 /// * `from` is neither a regular file nor a symlink to a regular file.
1752 /// * `from` does not exist.
1753 /// * The current process does not have the permission rights to read
1754 /// `from` or write `to`.
1761 /// fn main() -> std::io::Result<()> {
1762 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1768 fs_imp::copy(from.as_ref(), to.as_ref())
1771 /// Creates a new hard link on the filesystem.
1773 /// The `link` path will be a link pointing to the `original` path. Note that
1774 /// systems often require these two paths to both be located on the same
1777 /// If `original` names a symbolic link, it is platform-specific whether the
1778 /// symbolic link is followed. On platforms where it's possible to not follow
1779 /// it, it is not followed, and the created hard link points to the symbolic
1782 /// # Platform-specific behavior
1784 /// This function currently corresponds the `CreateHardLink` function on Windows.
1785 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1786 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1787 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1788 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1789 /// Note that, this [may change in the future][changes].
1791 /// [changes]: io#platform-specific-behavior
1795 /// This function will return an error in the following situations, but is not
1796 /// limited to just these cases:
1798 /// * The `original` path is not a file or doesn't exist.
1805 /// fn main() -> std::io::Result<()> {
1806 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1812 fs_imp::link(original.as_ref(), link.as_ref())
1815 /// Creates a new symbolic link on the filesystem.
1817 /// The `link` path will be a symbolic link pointing to the `original` path.
1818 /// On Windows, this will be a file symlink, not a directory symlink;
1819 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1820 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1821 /// used instead to make the intent explicit.
1823 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1824 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1825 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1832 /// fn main() -> std::io::Result<()> {
1833 /// fs::soft_link("a.txt", "b.txt")?;
1837 #[stable(feature = "rust1", since = "1.0.0")]
1840 reason = "replaced with std::os::unix::fs::symlink and \
1841 std::os::windows::fs::{symlink_file, symlink_dir}"
1843 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1844 fs_imp::symlink(original.as_ref(), link.as_ref())
1847 /// Reads a symbolic link, returning the file that the link points to.
1849 /// # Platform-specific behavior
1851 /// This function currently corresponds to the `readlink` function on Unix
1852 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1853 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1854 /// Note that, this [may change in the future][changes].
1856 /// [changes]: io#platform-specific-behavior
1860 /// This function will return an error in the following situations, but is not
1861 /// limited to just these cases:
1863 /// * `path` is not a symbolic link.
1864 /// * `path` does not exist.
1871 /// fn main() -> std::io::Result<()> {
1872 /// let path = fs::read_link("a.txt")?;
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1878 fs_imp::readlink(path.as_ref())
1881 /// Returns the canonical, absolute form of a path with all intermediate
1882 /// components normalized and symbolic links resolved.
1884 /// # Platform-specific behavior
1886 /// This function currently corresponds to the `realpath` function on Unix
1887 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1888 /// Note that, this [may change in the future][changes].
1890 /// On Windows, this converts the path to use [extended length path][path]
1891 /// syntax, which allows your program to use longer path names, but means you
1892 /// can only join backslash-delimited paths to it, and it may be incompatible
1893 /// with other applications (if passed to the application on the command-line,
1894 /// or written to a file another application may read).
1896 /// [changes]: io#platform-specific-behavior
1897 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1901 /// This function will return an error in the following situations, but is not
1902 /// limited to just these cases:
1904 /// * `path` does not exist.
1905 /// * A non-final component in path is not a directory.
1912 /// fn main() -> std::io::Result<()> {
1913 /// let path = fs::canonicalize("../a/../foo.txt")?;
1917 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1918 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1919 fs_imp::canonicalize(path.as_ref())
1922 /// Creates a new, empty directory at the provided path
1924 /// # Platform-specific behavior
1926 /// This function currently corresponds to the `mkdir` function on Unix
1927 /// and the `CreateDirectory` function on Windows.
1928 /// Note that, this [may change in the future][changes].
1930 /// [changes]: io#platform-specific-behavior
1932 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1933 /// return an error. To create a directory and all its missing parents at the
1934 /// same time, use the [`create_dir_all`] function.
1938 /// This function will return an error in the following situations, but is not
1939 /// limited to just these cases:
1941 /// * User lacks permissions to create directory at `path`.
1942 /// * A parent of the given path doesn't exist. (To create a directory and all
1943 /// its missing parents at the same time, use the [`create_dir_all`]
1945 /// * `path` already exists.
1952 /// fn main() -> std::io::Result<()> {
1953 /// fs::create_dir("/some/dir")?;
1957 #[doc(alias = "mkdir")]
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1960 DirBuilder::new().create(path.as_ref())
1963 /// Recursively create a directory and all of its parent components if they
1966 /// # Platform-specific behavior
1968 /// This function currently corresponds to the `mkdir` function on Unix
1969 /// and the `CreateDirectory` 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 /// * If any directory in the path specified by `path`
1980 /// does not already exist and it could not be created otherwise. The specific
1981 /// error conditions for when a directory is being created (after it is
1982 /// determined to not exist) are outlined by [`fs::create_dir`].
1984 /// Notable exception is made for situations where any of the directories
1985 /// specified in the `path` could not be created as it was being created concurrently.
1986 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1987 /// concurrently from multiple threads or processes is guaranteed not to fail
1988 /// due to a race condition with itself.
1990 /// [`fs::create_dir`]: create_dir
1997 /// fn main() -> std::io::Result<()> {
1998 /// fs::create_dir_all("/some/dir")?;
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2004 DirBuilder::new().recursive(true).create(path.as_ref())
2007 /// Removes an empty directory.
2009 /// # Platform-specific behavior
2011 /// This function currently corresponds to the `rmdir` function on Unix
2012 /// and the `RemoveDirectory` function on Windows.
2013 /// Note that, this [may change in the future][changes].
2015 /// [changes]: io#platform-specific-behavior
2019 /// This function will return an error in the following situations, but is not
2020 /// limited to just these cases:
2022 /// * `path` doesn't exist.
2023 /// * `path` isn't a directory.
2024 /// * The user lacks permissions to remove the directory at the provided `path`.
2025 /// * The directory isn't empty.
2032 /// fn main() -> std::io::Result<()> {
2033 /// fs::remove_dir("/some/dir")?;
2037 #[doc(alias = "rmdir")]
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2040 fs_imp::rmdir(path.as_ref())
2043 /// Removes a directory at this path, after removing all its contents. Use
2046 /// This function does **not** follow symbolic links and it will simply remove the
2047 /// symbolic link itself.
2049 /// # Platform-specific behavior
2051 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2052 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2053 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2054 /// Windows. Note that, this [may change in the future][changes].
2056 /// [changes]: io#platform-specific-behavior
2058 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2059 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2060 /// should not be used in security-sensitive code on those platforms. All other platforms are
2065 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2067 /// [`fs::remove_file`]: remove_file
2068 /// [`fs::remove_dir`]: remove_dir
2075 /// fn main() -> std::io::Result<()> {
2076 /// fs::remove_dir_all("/some/dir")?;
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2082 fs_imp::remove_dir_all(path.as_ref())
2085 /// Returns an iterator over the entries within a directory.
2087 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2088 /// New errors may be encountered after an iterator is initially constructed.
2089 /// Entries for the current and parent directories (typically `.` and `..`) are
2092 /// # Platform-specific behavior
2094 /// This function currently corresponds to the `opendir` function on Unix
2095 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2096 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2097 /// Note that, this [may change in the future][changes].
2099 /// [changes]: io#platform-specific-behavior
2101 /// The order in which this iterator returns entries is platform and filesystem
2106 /// This function will return an error in the following situations, but is not
2107 /// limited to just these cases:
2109 /// * The provided `path` doesn't exist.
2110 /// * The process lacks permissions to view the contents.
2111 /// * The `path` points at a non-directory file.
2117 /// use std::fs::{self, DirEntry};
2118 /// use std::path::Path;
2120 /// // one possible implementation of walking a directory only visiting files
2121 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2122 /// if dir.is_dir() {
2123 /// for entry in fs::read_dir(dir)? {
2124 /// let entry = entry?;
2125 /// let path = entry.path();
2126 /// if path.is_dir() {
2127 /// visit_dirs(&path, cb)?;
2138 /// use std::{fs, io};
2140 /// fn main() -> io::Result<()> {
2141 /// let mut entries = fs::read_dir(".")?
2142 /// .map(|res| res.map(|e| e.path()))
2143 /// .collect::<Result<Vec<_>, io::Error>>()?;
2145 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2146 /// // ordering is required the entries should be explicitly sorted.
2150 /// // The entries have now been sorted by their path.
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2157 fs_imp::readdir(path.as_ref()).map(ReadDir)
2160 /// Changes the permissions found on a file or a directory.
2162 /// # Platform-specific behavior
2164 /// This function currently corresponds to the `chmod` function on Unix
2165 /// and the `SetFileAttributes` function on Windows.
2166 /// Note that, this [may change in the future][changes].
2168 /// [changes]: io#platform-specific-behavior
2172 /// This function will return an error in the following situations, but is not
2173 /// limited to just these cases:
2175 /// * `path` does not exist.
2176 /// * The user lacks the permission to change attributes of the file.
2183 /// fn main() -> std::io::Result<()> {
2184 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2185 /// perms.set_readonly(true);
2186 /// fs::set_permissions("foo.txt", perms)?;
2190 #[stable(feature = "set_permissions", since = "1.1.0")]
2191 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2192 fs_imp::set_perm(path.as_ref(), perm.0)
2196 /// Creates a new set of options with default mode/security settings for all
2197 /// platforms and also non-recursive.
2202 /// use std::fs::DirBuilder;
2204 /// let builder = DirBuilder::new();
2206 #[stable(feature = "dir_builder", since = "1.6.0")]
2208 pub fn new() -> DirBuilder {
2209 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2212 /// Indicates that directories should be created recursively, creating all
2213 /// parent directories. Parents that do not exist are created with the same
2214 /// security and permissions settings.
2216 /// This option defaults to `false`.
2221 /// use std::fs::DirBuilder;
2223 /// let mut builder = DirBuilder::new();
2224 /// builder.recursive(true);
2226 #[stable(feature = "dir_builder", since = "1.6.0")]
2227 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2228 self.recursive = recursive;
2232 /// Creates the specified directory with the options configured in this
2235 /// It is considered an error if the directory already exists unless
2236 /// recursive mode is enabled.
2241 /// use std::fs::{self, DirBuilder};
2243 /// let path = "/tmp/foo/bar/baz";
2244 /// DirBuilder::new()
2245 /// .recursive(true)
2246 /// .create(path).unwrap();
2248 /// assert!(fs::metadata(path).unwrap().is_dir());
2250 #[stable(feature = "dir_builder", since = "1.6.0")]
2251 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2252 self._create(path.as_ref())
2255 fn _create(&self, path: &Path) -> io::Result<()> {
2256 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2259 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2260 if path == Path::new("") {
2264 match self.inner.mkdir(path) {
2265 Ok(()) => return Ok(()),
2266 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2267 Err(_) if path.is_dir() => return Ok(()),
2268 Err(e) => return Err(e),
2270 match path.parent() {
2271 Some(p) => self.create_dir_all(p)?,
2273 return Err(io::const_io_error!(
2274 io::ErrorKind::Uncategorized,
2275 "failed to create whole tree",
2279 match self.inner.mkdir(path) {
2281 Err(_) if path.is_dir() => Ok(()),
2287 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2288 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2293 /// Returns `Ok(true)` if the path points at an existing entity.
2295 /// This function will traverse symbolic links to query information about the
2296 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2298 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2299 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2300 /// denied on some of the parent directories.)
2305 /// #![feature(path_try_exists)]
2308 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2309 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2312 /// [`Path::exists`]: crate::path::Path::exists
2313 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2315 #[unstable(feature = "path_try_exists", issue = "83186")]
2317 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2318 fs_imp::try_exists(path.as_ref())