1 //! Filesystem manipulation operations.
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
8 #![stable(feature = "rust1", since = "1.0.0")]
9 #![deny(unsafe_op_in_unsafe_fn)]
11 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
14 use crate::ffi::OsString;
16 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
17 use crate::path::{Path, PathBuf};
18 use crate::sys::fs as fs_imp;
19 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
20 use crate::time::SystemTime;
22 /// A reference to an open file on the filesystem.
24 /// An instance of a `File` can be read and/or written depending on what options
25 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
26 /// that the file contains internally.
28 /// Files are automatically closed when they go out of scope. Errors detected
29 /// on closing are ignored by the implementation of `Drop`. Use the method
30 /// [`sync_all`] if these errors must be manually handled.
34 /// Creates a new file and write bytes to it (you can also use [`write()`]):
37 /// use std::fs::File;
38 /// use std::io::prelude::*;
40 /// fn main() -> std::io::Result<()> {
41 /// let mut file = File::create("foo.txt")?;
42 /// file.write_all(b"Hello, world!")?;
47 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
50 /// use std::fs::File;
51 /// use std::io::prelude::*;
53 /// fn main() -> std::io::Result<()> {
54 /// let mut file = File::open("foo.txt")?;
55 /// let mut contents = String::new();
56 /// file.read_to_string(&mut contents)?;
57 /// assert_eq!(contents, "Hello, world!");
62 /// It can be more efficient to read the contents of a file with a buffered
63 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
66 /// use std::fs::File;
67 /// use std::io::BufReader;
68 /// use std::io::prelude::*;
70 /// fn main() -> std::io::Result<()> {
71 /// let file = File::open("foo.txt")?;
72 /// let mut buf_reader = BufReader::new(file);
73 /// let mut contents = String::new();
74 /// buf_reader.read_to_string(&mut contents)?;
75 /// assert_eq!(contents, "Hello, world!");
80 /// Note that, although read and write methods require a `&mut File`, because
81 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
82 /// still modify the file, either through methods that take `&File` or by
83 /// retrieving the underlying OS object and modifying the file that way.
84 /// Additionally, many operating systems allow concurrent modification of files
85 /// by different processes. Avoid assuming that holding a `&File` means that the
86 /// file will not change.
88 /// [`BufReader<R>`]: io::BufReader
89 /// [`sync_all`]: File::sync_all
90 #[stable(feature = "rust1", since = "1.0.0")]
95 /// Metadata information about a file.
97 /// This structure is returned from the [`metadata`] or
98 /// [`symlink_metadata`] function or method and represents known
99 /// metadata about a file such as its permissions, size, modification
101 #[stable(feature = "rust1", since = "1.0.0")]
103 pub struct Metadata(fs_imp::FileAttr);
105 /// Iterator over the entries in a directory.
107 /// This iterator is returned from the [`read_dir`] function of this module and
108 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
109 /// information like the entry's path and possibly other metadata can be
112 /// The order in which this iterator returns entries is platform and filesystem
117 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
118 /// IO error during iteration.
119 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct ReadDir(fs_imp::ReadDir);
123 /// Entries returned by the [`ReadDir`] iterator.
125 /// An instance of `DirEntry` represents an entry inside of a directory on the
126 /// filesystem. Each entry can be inspected via methods to learn about the full
127 /// path or possibly other metadata through per-platform extension traits.
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct DirEntry(fs_imp::DirEntry);
131 /// Options and flags which can be used to configure how a file is opened.
133 /// This builder exposes the ability to configure how a [`File`] is opened and
134 /// what operations are permitted on the open file. The [`File::open`] and
135 /// [`File::create`] methods are aliases for commonly used options using this
138 /// Generally speaking, when using `OpenOptions`, you'll first call
139 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
140 /// call [`OpenOptions::open`], passing the path of the file you're trying to
141 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
142 /// can further operate on.
146 /// Opening a file to read:
149 /// use std::fs::OpenOptions;
151 /// let file = OpenOptions::new().read(true).open("foo.txt");
154 /// Opening a file for both reading and writing, as well as creating it if it
158 /// use std::fs::OpenOptions;
160 /// let file = OpenOptions::new()
164 /// .open("foo.txt");
166 #[derive(Clone, Debug)]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct OpenOptions(fs_imp::OpenOptions);
170 /// Representation of the various permissions on a file.
172 /// This module only currently provides one bit of information,
173 /// [`Permissions::readonly`], which is exposed on all currently supported
174 /// platforms. Unix-specific functionality, such as mode bits, is available
175 /// through the [`PermissionsExt`] trait.
177 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
178 #[derive(Clone, PartialEq, Eq, Debug)]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct Permissions(fs_imp::FilePermissions);
182 /// A structure representing a type of file with accessors for each file type.
183 /// It is returned by [`Metadata::file_type`] method.
184 #[stable(feature = "file_type", since = "1.1.0")]
185 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
186 pub struct FileType(fs_imp::FileType);
188 /// A builder used to create directories in various manners.
190 /// This builder also supports platform-specific options.
191 #[stable(feature = "dir_builder", since = "1.6.0")]
193 pub struct DirBuilder {
194 inner: fs_imp::DirBuilder,
198 /// Indicates how large a buffer to pre-allocate before reading the entire file.
199 fn initial_buffer_size(file: &File) -> usize {
200 // Allocate one extra byte so the buffer doesn't need to grow before the
201 // final `read` call at the end of the file. Don't worry about `usize`
202 // overflow because reading will fail regardless in that case.
203 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
206 /// Read the entire contents of a file into a bytes vector.
208 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
209 /// with fewer imports and without an intermediate variable. It pre-allocates a
210 /// buffer based on the file size when available, so it is generally faster than
211 /// reading into a vector created with [`Vec::new()`].
213 /// [`read_to_end`]: Read::read_to_end
217 /// This function will return an error if `path` does not already exist.
218 /// Other errors may also be returned according to [`OpenOptions::open`].
220 /// It will also return an error if it encounters while reading an error
221 /// of a kind other than [`io::ErrorKind::Interrupted`].
227 /// use std::net::SocketAddr;
229 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
230 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
234 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
235 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
236 fn inner(path: &Path) -> io::Result<Vec<u8>> {
237 let mut file = File::open(path)?;
238 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
239 file.read_to_end(&mut bytes)?;
245 /// Read the entire contents of a file into a string.
247 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
248 /// with fewer imports and without an intermediate variable. It pre-allocates a
249 /// buffer based on the file size when available, so it is generally faster than
250 /// reading into a string created with [`String::new()`].
252 /// [`read_to_string`]: Read::read_to_string
256 /// This function will return an error if `path` does not already exist.
257 /// Other errors may also be returned according to [`OpenOptions::open`].
259 /// It will also return an error if it encounters while reading an error
260 /// of a kind other than [`io::ErrorKind::Interrupted`],
261 /// or if the contents of the file are not valid UTF-8.
267 /// use std::net::SocketAddr;
269 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
270 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
274 #[stable(feature = "fs_read_write", since = "1.26.0")]
275 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
276 fn inner(path: &Path) -> io::Result<String> {
277 let mut file = File::open(path)?;
278 let mut string = String::with_capacity(initial_buffer_size(&file));
279 file.read_to_string(&mut string)?;
285 /// Write a slice as the entire contents of a file.
287 /// This function will create a file if it does not exist,
288 /// and will entirely replace its contents if it does.
290 /// This is a convenience function for using [`File::create`] and [`write_all`]
291 /// with fewer imports.
293 /// [`write_all`]: Write::write_all
300 /// fn main() -> std::io::Result<()> {
301 /// fs::write("foo.txt", b"Lorem ipsum")?;
302 /// fs::write("bar.txt", "dolor sit")?;
306 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
307 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
308 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
309 File::create(path)?.write_all(contents)
311 inner(path.as_ref(), contents.as_ref())
315 /// Attempts to open a file in read-only mode.
317 /// See the [`OpenOptions::open`] method for more details.
321 /// This function will return an error if `path` does not already exist.
322 /// Other errors may also be returned according to [`OpenOptions::open`].
327 /// use std::fs::File;
329 /// fn main() -> std::io::Result<()> {
330 /// let mut f = File::open("foo.txt")?;
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
336 OpenOptions::new().read(true).open(path.as_ref())
339 /// Opens a file in write-only mode.
341 /// This function will create a file if it does not exist,
342 /// and will truncate it if it does.
344 /// See the [`OpenOptions::open`] function for more details.
349 /// use std::fs::File;
351 /// fn main() -> std::io::Result<()> {
352 /// let mut f = File::create("foo.txt")?;
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
358 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
361 /// Returns a new OpenOptions object.
363 /// This function returns a new OpenOptions object that you can use to
364 /// open or create a file with specific options if `open()` or `create()`
365 /// are not appropriate.
367 /// It is equivalent to `OpenOptions::new()` but allows you to write more
368 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
369 /// you can write `File::with_options().read(true).open("foo.txt")`. This
370 /// also avoids the need to import `OpenOptions`.
372 /// See the [`OpenOptions::new`] function for more details.
377 /// #![feature(with_options)]
378 /// use std::fs::File;
380 /// fn main() -> std::io::Result<()> {
381 /// let mut f = File::with_options().read(true).open("foo.txt")?;
385 #[unstable(feature = "with_options", issue = "65439")]
386 pub fn with_options() -> OpenOptions {
390 /// Attempts to sync all OS-internal metadata to disk.
392 /// This function will attempt to ensure that all in-memory data reaches the
393 /// filesystem before returning.
395 /// This can be used to handle errors that would otherwise only be caught
396 /// when the `File` is closed. Dropping a file will ignore errors in
397 /// synchronizing this in-memory data.
402 /// use std::fs::File;
403 /// use std::io::prelude::*;
405 /// fn main() -> std::io::Result<()> {
406 /// let mut f = File::create("foo.txt")?;
407 /// f.write_all(b"Hello, world!")?;
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn sync_all(&self) -> io::Result<()> {
418 /// This function is similar to [`sync_all`], except that it may not
419 /// synchronize file metadata to the filesystem.
421 /// This is intended for use cases that must synchronize content, but don't
422 /// need the metadata on disk. The goal of this method is to reduce disk
425 /// Note that some platforms may simply implement this in terms of
428 /// [`sync_all`]: File::sync_all
433 /// use std::fs::File;
434 /// use std::io::prelude::*;
436 /// fn main() -> std::io::Result<()> {
437 /// let mut f = File::create("foo.txt")?;
438 /// f.write_all(b"Hello, world!")?;
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn sync_data(&self) -> io::Result<()> {
446 self.inner.datasync()
449 /// Truncates or extends the underlying file, updating the size of
450 /// this file to become `size`.
452 /// If the `size` is less than the current file's size, then the file will
453 /// be shrunk. If it is greater than the current file's size, then the file
454 /// will be extended to `size` and have all of the intermediate data filled
457 /// The file's cursor isn't changed. In particular, if the cursor was at the
458 /// end and the file is shrunk using this operation, the cursor will now be
463 /// This function will return an error if the file is not opened for writing.
464 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
465 /// length would cause an overflow due to the implementation specifics.
470 /// use std::fs::File;
472 /// fn main() -> std::io::Result<()> {
473 /// let mut f = File::create("foo.txt")?;
479 /// Note that this method alters the content of the underlying file, even
480 /// though it takes `&self` rather than `&mut self`.
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn set_len(&self, size: u64) -> io::Result<()> {
483 self.inner.truncate(size)
486 /// Queries metadata about the underlying file.
491 /// use std::fs::File;
493 /// fn main() -> std::io::Result<()> {
494 /// let mut f = File::open("foo.txt")?;
495 /// let metadata = f.metadata()?;
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn metadata(&self) -> io::Result<Metadata> {
501 self.inner.file_attr().map(Metadata)
504 /// Creates a new `File` instance that shares the same underlying file handle
505 /// as the existing `File` instance. Reads, writes, and seeks will affect
506 /// both `File` instances simultaneously.
510 /// Creates two handles for a file named `foo.txt`:
513 /// use std::fs::File;
515 /// fn main() -> std::io::Result<()> {
516 /// let mut file = File::open("foo.txt")?;
517 /// let file_copy = file.try_clone()?;
522 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
523 /// two handles, seek one of them, and read the remaining bytes from the
527 /// use std::fs::File;
528 /// use std::io::SeekFrom;
529 /// use std::io::prelude::*;
531 /// fn main() -> std::io::Result<()> {
532 /// let mut file = File::open("foo.txt")?;
533 /// let mut file_copy = file.try_clone()?;
535 /// file.seek(SeekFrom::Start(3))?;
537 /// let mut contents = vec![];
538 /// file_copy.read_to_end(&mut contents)?;
539 /// assert_eq!(contents, b"def\n");
543 #[stable(feature = "file_try_clone", since = "1.9.0")]
544 pub fn try_clone(&self) -> io::Result<File> {
545 Ok(File { inner: self.inner.duplicate()? })
548 /// Changes the permissions on the underlying file.
550 /// # Platform-specific behavior
552 /// This function currently corresponds to the `fchmod` function on Unix and
553 /// the `SetFileInformationByHandle` function on Windows. Note that, this
554 /// [may change in the future][changes].
556 /// [changes]: io#platform-specific-behavior
560 /// This function will return an error if the user lacks permission change
561 /// attributes on the underlying file. It may also return an error in other
562 /// os-specific unspecified cases.
567 /// fn main() -> std::io::Result<()> {
568 /// use std::fs::File;
570 /// let file = File::open("foo.txt")?;
571 /// let mut perms = file.metadata()?.permissions();
572 /// perms.set_readonly(true);
573 /// file.set_permissions(perms)?;
578 /// Note that this method alters the permissions of the underlying file,
579 /// even though it takes `&self` rather than `&mut self`.
580 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
581 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
582 self.inner.set_permissions(perm.0)
586 impl AsInner<fs_imp::File> for File {
587 fn as_inner(&self) -> &fs_imp::File {
591 impl FromInner<fs_imp::File> for File {
592 fn from_inner(f: fs_imp::File) -> File {
596 impl IntoInner<fs_imp::File> for File {
597 fn into_inner(self) -> fs_imp::File {
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl fmt::Debug for File {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 #[stable(feature = "rust1", since = "1.0.0")]
611 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
615 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
616 self.inner.read_vectored(bufs)
620 fn is_read_vectored(&self) -> bool {
621 self.inner.is_read_vectored()
625 unsafe fn initializer(&self) -> Initializer {
626 // SAFETY: Read is guaranteed to work on uninitialized memory
627 unsafe { Initializer::nop() }
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Write for File {
632 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
633 self.inner.write(buf)
636 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
637 self.inner.write_vectored(bufs)
641 fn is_write_vectored(&self) -> bool {
642 self.inner.is_write_vectored()
645 fn flush(&mut self) -> io::Result<()> {
649 #[stable(feature = "rust1", since = "1.0.0")]
651 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl Read for &File {
657 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
661 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
662 self.inner.read_vectored(bufs)
666 fn is_read_vectored(&self) -> bool {
667 self.inner.is_read_vectored()
671 unsafe fn initializer(&self) -> Initializer {
672 // SAFETY: Read is guaranteed to work on uninitialized memory
673 unsafe { Initializer::nop() }
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Write for &File {
678 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
679 self.inner.write(buf)
682 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
683 self.inner.write_vectored(bufs)
687 fn is_write_vectored(&self) -> bool {
688 self.inner.is_write_vectored()
691 fn flush(&mut self) -> io::Result<()> {
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl Seek for &File {
697 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
703 /// Creates a blank new set of options ready for configuration.
705 /// All options are initially set to `false`.
710 /// use std::fs::OpenOptions;
712 /// let mut options = OpenOptions::new();
713 /// let file = options.read(true).open("foo.txt");
715 #[stable(feature = "rust1", since = "1.0.0")]
716 pub fn new() -> Self {
717 OpenOptions(fs_imp::OpenOptions::new())
720 /// Sets the option for read access.
722 /// This option, when true, will indicate that the file should be
723 /// `read`-able if opened.
728 /// use std::fs::OpenOptions;
730 /// let file = OpenOptions::new().read(true).open("foo.txt");
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn read(&mut self, read: bool) -> &mut Self {
738 /// Sets the option for write access.
740 /// This option, when true, will indicate that the file should be
741 /// `write`-able if opened.
743 /// If the file already exists, any write calls on it will overwrite its
744 /// contents, without truncating it.
749 /// use std::fs::OpenOptions;
751 /// let file = OpenOptions::new().write(true).open("foo.txt");
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn write(&mut self, write: bool) -> &mut Self {
759 /// Sets the option for the append mode.
761 /// This option, when true, means that writes will append to a file instead
762 /// of overwriting previous contents.
763 /// Note that setting `.write(true).append(true)` has the same effect as
764 /// setting only `.append(true)`.
766 /// For most filesystems, the operating system guarantees that all writes are
767 /// atomic: no writes get mangled because another process writes at the same
770 /// One maybe obvious note when using append-mode: make sure that all data
771 /// that belongs together is written to the file in one operation. This
772 /// can be done by concatenating strings before passing them to [`write()`],
773 /// or using a buffered writer (with a buffer of adequate size),
774 /// and calling [`flush()`] when the message is complete.
776 /// If a file is opened with both read and append access, beware that after
777 /// opening, and after every write, the position for reading may be set at the
778 /// end of the file. So, before writing, save the current position (using
779 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
783 /// This function doesn't create the file if it doesn't exist. Use the
784 /// [`OpenOptions::create`] method to do so.
786 /// [`write()`]: Write::write
787 /// [`flush()`]: Write::flush
788 /// [`seek`]: Seek::seek
789 /// [`Current`]: SeekFrom::Current
794 /// use std::fs::OpenOptions;
796 /// let file = OpenOptions::new().append(true).open("foo.txt");
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub fn append(&mut self, append: bool) -> &mut Self {
800 self.0.append(append);
804 /// Sets the option for truncating a previous file.
806 /// If a file is successfully opened with this option set it will truncate
807 /// the file to 0 length if it already exists.
809 /// The file must be opened with write access for truncate to work.
814 /// use std::fs::OpenOptions;
816 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
820 self.0.truncate(truncate);
824 /// Sets the option to create a new file, or open it if it already exists.
826 /// In order for the file to be created, [`OpenOptions::write`] or
827 /// [`OpenOptions::append`] access must be used.
832 /// use std::fs::OpenOptions;
834 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
836 #[stable(feature = "rust1", since = "1.0.0")]
837 pub fn create(&mut self, create: bool) -> &mut Self {
838 self.0.create(create);
842 /// Sets the option to create a new file, failing if it already exists.
844 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
845 /// way, if the call succeeds, the file returned is guaranteed to be new.
847 /// This option is useful because it is atomic. Otherwise between checking
848 /// whether a file exists and creating a new one, the file may have been
849 /// created by another process (a TOCTOU race condition / attack).
851 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
854 /// The file must be opened with write or append access in order to create
857 /// [`.create()`]: OpenOptions::create
858 /// [`.truncate()`]: OpenOptions::truncate
863 /// use std::fs::OpenOptions;
865 /// let file = OpenOptions::new().write(true)
866 /// .create_new(true)
867 /// .open("foo.txt");
869 #[stable(feature = "expand_open_options2", since = "1.9.0")]
870 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
871 self.0.create_new(create_new);
875 /// Opens a file at `path` with the options specified by `self`.
879 /// This function will return an error under a number of different
880 /// circumstances. Some of these error conditions are listed here, together
881 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
882 /// part of the compatibility contract of the function, especially the
883 /// [`Other`] kind might change to more specific kinds in the future.
885 /// * [`NotFound`]: The specified file does not exist and neither `create`
886 /// or `create_new` is set.
887 /// * [`NotFound`]: One of the directory components of the file path does
889 /// * [`PermissionDenied`]: The user lacks permission to get the specified
890 /// access rights for the file.
891 /// * [`PermissionDenied`]: The user lacks permission to open one of the
892 /// directory components of the specified path.
893 /// * [`AlreadyExists`]: `create_new` was specified and the file already
895 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
896 /// without write access, no access mode set, etc.).
897 /// * [`Other`]: One of the directory components of the specified file path
898 /// was not, in fact, a directory.
899 /// * [`Other`]: Filesystem-level errors: full disk, write permission
900 /// requested on a read-only file system, exceeded disk quota, too many
901 /// open files, too long filename, too many symbolic links in the
902 /// specified path (Unix-like systems only), etc.
907 /// use std::fs::OpenOptions;
909 /// let file = OpenOptions::new().read(true).open("foo.txt");
912 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
913 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
914 /// [`NotFound`]: io::ErrorKind::NotFound
915 /// [`Other`]: io::ErrorKind::Other
916 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
917 #[stable(feature = "rust1", since = "1.0.0")]
918 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
919 self._open(path.as_ref())
922 fn _open(&self, path: &Path) -> io::Result<File> {
923 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
927 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
928 fn as_inner(&self) -> &fs_imp::OpenOptions {
933 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
934 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
940 /// Returns the file type for this metadata.
945 /// fn main() -> std::io::Result<()> {
948 /// let metadata = fs::metadata("foo.txt")?;
950 /// println!("{:?}", metadata.file_type());
954 #[stable(feature = "file_type", since = "1.1.0")]
955 pub fn file_type(&self) -> FileType {
956 FileType(self.0.file_type())
959 /// Returns `true` if this metadata is for a directory. The
960 /// result is mutually exclusive to the result of
961 /// [`Metadata::is_file`], and will be false for symlink metadata
962 /// obtained from [`symlink_metadata`].
967 /// fn main() -> std::io::Result<()> {
970 /// let metadata = fs::metadata("foo.txt")?;
972 /// assert!(!metadata.is_dir());
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn is_dir(&self) -> bool {
978 self.file_type().is_dir()
981 /// Returns `true` if this metadata is for a regular file. The
982 /// result is mutually exclusive to the result of
983 /// [`Metadata::is_dir`], and will be false for symlink metadata
984 /// obtained from [`symlink_metadata`].
986 /// When the goal is simply to read from (or write to) the source, the most
987 /// reliable way to test the source can be read (or written to) is to open
988 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
989 /// a Unix-like system for example. See [`File::open`] or
990 /// [`OpenOptions::open`] for more information.
997 /// fn main() -> std::io::Result<()> {
998 /// let metadata = fs::metadata("foo.txt")?;
1000 /// assert!(metadata.is_file());
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 pub fn is_file(&self) -> bool {
1006 self.file_type().is_file()
1009 /// Returns the size of the file, in bytes, this metadata is for.
1016 /// fn main() -> std::io::Result<()> {
1017 /// let metadata = fs::metadata("foo.txt")?;
1019 /// assert_eq!(0, metadata.len());
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub fn len(&self) -> u64 {
1028 /// Returns the permissions of the file this metadata is for.
1035 /// fn main() -> std::io::Result<()> {
1036 /// let metadata = fs::metadata("foo.txt")?;
1038 /// assert!(!metadata.permissions().readonly());
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn permissions(&self) -> Permissions {
1044 Permissions(self.0.perm())
1047 /// Returns the last modification time listed in this metadata.
1049 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1050 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1054 /// This field may not be available on all platforms, and will return an
1055 /// `Err` on platforms where it is not available.
1062 /// fn main() -> std::io::Result<()> {
1063 /// let metadata = fs::metadata("foo.txt")?;
1065 /// if let Ok(time) = metadata.modified() {
1066 /// println!("{:?}", time);
1068 /// println!("Not supported on this platform");
1073 #[stable(feature = "fs_time", since = "1.10.0")]
1074 pub fn modified(&self) -> io::Result<SystemTime> {
1075 self.0.modified().map(FromInner::from_inner)
1078 /// Returns the last access time of this metadata.
1080 /// The returned value corresponds to the `atime` field of `stat` on Unix
1081 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1083 /// Note that not all platforms will keep this field update in a file's
1084 /// metadata, for example Windows has an option to disable updating this
1085 /// time when files are accessed and Linux similarly has `noatime`.
1089 /// This field may not be available on all platforms, and will return an
1090 /// `Err` on platforms where it is not available.
1097 /// fn main() -> std::io::Result<()> {
1098 /// let metadata = fs::metadata("foo.txt")?;
1100 /// if let Ok(time) = metadata.accessed() {
1101 /// println!("{:?}", time);
1103 /// println!("Not supported on this platform");
1108 #[stable(feature = "fs_time", since = "1.10.0")]
1109 pub fn accessed(&self) -> io::Result<SystemTime> {
1110 self.0.accessed().map(FromInner::from_inner)
1113 /// Returns the creation time listed in this metadata.
1115 /// The returned value corresponds to the `btime` field of `statx` on
1116 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1117 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1121 /// This field may not be available on all platforms, and will return an
1122 /// `Err` on platforms or filesystems where it is not available.
1129 /// fn main() -> std::io::Result<()> {
1130 /// let metadata = fs::metadata("foo.txt")?;
1132 /// if let Ok(time) = metadata.created() {
1133 /// println!("{:?}", time);
1135 /// println!("Not supported on this platform or filesystem");
1140 #[stable(feature = "fs_time", since = "1.10.0")]
1141 pub fn created(&self) -> io::Result<SystemTime> {
1142 self.0.created().map(FromInner::from_inner)
1146 #[stable(feature = "std_debug", since = "1.16.0")]
1147 impl fmt::Debug for Metadata {
1148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1149 f.debug_struct("Metadata")
1150 .field("file_type", &self.file_type())
1151 .field("is_dir", &self.is_dir())
1152 .field("is_file", &self.is_file())
1153 .field("permissions", &self.permissions())
1154 .field("modified", &self.modified())
1155 .field("accessed", &self.accessed())
1156 .field("created", &self.created())
1161 impl AsInner<fs_imp::FileAttr> for Metadata {
1162 fn as_inner(&self) -> &fs_imp::FileAttr {
1167 impl FromInner<fs_imp::FileAttr> for Metadata {
1168 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1174 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1179 /// use std::fs::File;
1181 /// fn main() -> std::io::Result<()> {
1182 /// let mut f = File::create("foo.txt")?;
1183 /// let metadata = f.metadata()?;
1185 /// assert_eq!(false, metadata.permissions().readonly());
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn readonly(&self) -> bool {
1194 /// Modifies the readonly flag for this set of permissions. If the
1195 /// `readonly` argument is `true`, using the resulting `Permission` will
1196 /// update file permissions to forbid writing. Conversely, if it's `false`,
1197 /// using the resulting `Permission` will update file permissions to allow
1200 /// This operation does **not** modify the filesystem. To modify the
1201 /// filesystem use the [`set_permissions`] function.
1206 /// use std::fs::File;
1208 /// fn main() -> std::io::Result<()> {
1209 /// let f = File::create("foo.txt")?;
1210 /// let metadata = f.metadata()?;
1211 /// let mut permissions = metadata.permissions();
1213 /// permissions.set_readonly(true);
1215 /// // filesystem doesn't change
1216 /// assert_eq!(false, metadata.permissions().readonly());
1218 /// // just this particular `permissions`.
1219 /// assert_eq!(true, permissions.readonly());
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn set_readonly(&mut self, readonly: bool) {
1225 self.0.set_readonly(readonly)
1230 /// Tests whether this file type represents a directory. The
1231 /// result is mutually exclusive to the results of
1232 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1235 /// [`is_file`]: FileType::is_file
1236 /// [`is_symlink`]: FileType::is_symlink
1241 /// fn main() -> std::io::Result<()> {
1244 /// let metadata = fs::metadata("foo.txt")?;
1245 /// let file_type = metadata.file_type();
1247 /// assert_eq!(file_type.is_dir(), false);
1251 #[stable(feature = "file_type", since = "1.1.0")]
1252 pub fn is_dir(&self) -> bool {
1256 /// Tests whether this file type represents a regular file.
1257 /// The result is mutually exclusive to the results of
1258 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1261 /// When the goal is simply to read from (or write to) the source, the most
1262 /// reliable way to test the source can be read (or written to) is to open
1263 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1264 /// a Unix-like system for example. See [`File::open`] or
1265 /// [`OpenOptions::open`] for more information.
1267 /// [`is_dir`]: FileType::is_dir
1268 /// [`is_symlink`]: FileType::is_symlink
1273 /// fn main() -> std::io::Result<()> {
1276 /// let metadata = fs::metadata("foo.txt")?;
1277 /// let file_type = metadata.file_type();
1279 /// assert_eq!(file_type.is_file(), true);
1283 #[stable(feature = "file_type", since = "1.1.0")]
1284 pub fn is_file(&self) -> bool {
1288 /// Tests whether this file type represents a symbolic link.
1289 /// The result is mutually exclusive to the results of
1290 /// [`is_dir`] and [`is_file`]; only zero or one of these
1293 /// The underlying [`Metadata`] struct needs to be retrieved
1294 /// with the [`fs::symlink_metadata`] function and not the
1295 /// [`fs::metadata`] function. The [`fs::metadata`] function
1296 /// follows symbolic links, so [`is_symlink`] would always
1297 /// return `false` for the target file.
1299 /// [`fs::metadata`]: metadata
1300 /// [`fs::symlink_metadata`]: symlink_metadata
1301 /// [`is_dir`]: FileType::is_dir
1302 /// [`is_file`]: FileType::is_file
1303 /// [`is_symlink`]: FileType::is_symlink
1310 /// fn main() -> std::io::Result<()> {
1311 /// let metadata = fs::symlink_metadata("foo.txt")?;
1312 /// let file_type = metadata.file_type();
1314 /// assert_eq!(file_type.is_symlink(), false);
1318 #[stable(feature = "file_type", since = "1.1.0")]
1319 pub fn is_symlink(&self) -> bool {
1324 impl AsInner<fs_imp::FileType> for FileType {
1325 fn as_inner(&self) -> &fs_imp::FileType {
1330 impl FromInner<fs_imp::FilePermissions> for Permissions {
1331 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1336 impl AsInner<fs_imp::FilePermissions> for Permissions {
1337 fn as_inner(&self) -> &fs_imp::FilePermissions {
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 impl Iterator for ReadDir {
1344 type Item = io::Result<DirEntry>;
1346 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1347 self.0.next().map(|entry| entry.map(DirEntry))
1352 /// Returns the full path to the file that this entry represents.
1354 /// The full path is created by joining the original path to `read_dir`
1355 /// with the filename of this entry.
1362 /// fn main() -> std::io::Result<()> {
1363 /// for entry in fs::read_dir(".")? {
1364 /// let dir = entry?;
1365 /// println!("{:?}", dir.path());
1371 /// This prints output like:
1374 /// "./whatever.txt"
1376 /// "./hello_world.rs"
1379 /// The exact text, of course, depends on what files you have in `.`.
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 pub fn path(&self) -> PathBuf {
1385 /// Returns the metadata for the file that this entry points at.
1387 /// This function will not traverse symlinks if this entry points at a
1388 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1390 /// [`fs::metadata`]: metadata
1391 /// [`fs::File::metadata`]: File::metadata
1393 /// # Platform-specific behavior
1395 /// On Windows this function is cheap to call (no extra system calls
1396 /// needed), but on Unix platforms this function is the equivalent of
1397 /// calling `symlink_metadata` on the path.
1404 /// if let Ok(entries) = fs::read_dir(".") {
1405 /// for entry in entries {
1406 /// if let Ok(entry) = entry {
1407 /// // Here, `entry` is a `DirEntry`.
1408 /// if let Ok(metadata) = entry.metadata() {
1409 /// // Now let's show our entry's permissions!
1410 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1412 /// println!("Couldn't get metadata for {:?}", entry.path());
1418 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1419 pub fn metadata(&self) -> io::Result<Metadata> {
1420 self.0.metadata().map(Metadata)
1423 /// Returns the file type for the file that this entry points at.
1425 /// This function will not traverse symlinks if this entry points at a
1428 /// # Platform-specific behavior
1430 /// On Windows and most Unix platforms this function is free (no extra
1431 /// system calls needed), but some Unix platforms may require the equivalent
1432 /// call to `symlink_metadata` to learn about the target file type.
1439 /// if let Ok(entries) = fs::read_dir(".") {
1440 /// for entry in entries {
1441 /// if let Ok(entry) = entry {
1442 /// // Here, `entry` is a `DirEntry`.
1443 /// if let Ok(file_type) = entry.file_type() {
1444 /// // Now let's show our entry's file type!
1445 /// println!("{:?}: {:?}", entry.path(), file_type);
1447 /// println!("Couldn't get file type for {:?}", entry.path());
1453 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1454 pub fn file_type(&self) -> io::Result<FileType> {
1455 self.0.file_type().map(FileType)
1458 /// Returns the bare file name of this directory entry without any other
1459 /// leading path component.
1466 /// if let Ok(entries) = fs::read_dir(".") {
1467 /// for entry in entries {
1468 /// if let Ok(entry) = entry {
1469 /// // Here, `entry` is a `DirEntry`.
1470 /// println!("{:?}", entry.file_name());
1475 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1476 pub fn file_name(&self) -> OsString {
1481 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1482 impl fmt::Debug for DirEntry {
1483 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1484 f.debug_tuple("DirEntry").field(&self.path()).finish()
1488 impl AsInner<fs_imp::DirEntry> for DirEntry {
1489 fn as_inner(&self) -> &fs_imp::DirEntry {
1494 /// Removes a file from the filesystem.
1496 /// Note that there is no
1497 /// guarantee that the file is immediately deleted (e.g., depending on
1498 /// platform, other open file descriptors may prevent immediate removal).
1500 /// # Platform-specific behavior
1502 /// This function currently corresponds to the `unlink` function on Unix
1503 /// and the `DeleteFile` function on Windows.
1504 /// Note that, this [may change in the future][changes].
1506 /// [changes]: io#platform-specific-behavior
1510 /// This function will return an error in the following situations, but is not
1511 /// limited to just these cases:
1513 /// * `path` points to a directory.
1514 /// * The file doesn't exist.
1515 /// * The user lacks permissions to remove the file.
1522 /// fn main() -> std::io::Result<()> {
1523 /// fs::remove_file("a.txt")?;
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1529 fs_imp::unlink(path.as_ref())
1532 /// Given a path, query the file system to get information about a file,
1535 /// This function will traverse symbolic links to query information about the
1536 /// destination file.
1538 /// # Platform-specific behavior
1540 /// This function currently corresponds to the `stat` function on Unix
1541 /// and the `GetFileAttributesEx` function on Windows.
1542 /// Note that, this [may change in the future][changes].
1544 /// [changes]: io#platform-specific-behavior
1548 /// This function will return an error in the following situations, but is not
1549 /// limited to just these cases:
1551 /// * The user lacks permissions to perform `metadata` call on `path`.
1552 /// * `path` does not exist.
1559 /// fn main() -> std::io::Result<()> {
1560 /// let attr = fs::metadata("/some/file/path.txt")?;
1561 /// // inspect attr ...
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1567 fs_imp::stat(path.as_ref()).map(Metadata)
1570 /// Query the metadata about a file without following symlinks.
1572 /// # Platform-specific behavior
1574 /// This function currently corresponds to the `lstat` function on Unix
1575 /// and the `GetFileAttributesEx` function on Windows.
1576 /// Note that, this [may change in the future][changes].
1578 /// [changes]: io#platform-specific-behavior
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1585 /// * The user lacks permissions to perform `metadata` call on `path`.
1586 /// * `path` does not exist.
1593 /// fn main() -> std::io::Result<()> {
1594 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1595 /// // inspect attr ...
1599 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1600 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1601 fs_imp::lstat(path.as_ref()).map(Metadata)
1604 /// Rename a file or directory to a new name, replacing the original file if
1605 /// `to` already exists.
1607 /// This will not work if the new name is on a different mount point.
1609 /// # Platform-specific behavior
1611 /// This function currently corresponds to the `rename` function on Unix
1612 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1614 /// Because of this, the behavior when both `from` and `to` exist differs. On
1615 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1616 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1617 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1619 /// Note that, this [may change in the future][changes].
1621 /// [changes]: io#platform-specific-behavior
1625 /// This function will return an error in the following situations, but is not
1626 /// limited to just these cases:
1628 /// * `from` does not exist.
1629 /// * The user lacks permissions to view contents.
1630 /// * `from` and `to` are on separate filesystems.
1637 /// fn main() -> std::io::Result<()> {
1638 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1644 fs_imp::rename(from.as_ref(), to.as_ref())
1647 /// Copies the contents of one file to another. This function will also
1648 /// copy the permission bits of the original file to the destination file.
1650 /// This function will **overwrite** the contents of `to`.
1652 /// Note that if `from` and `to` both point to the same file, then the file
1653 /// will likely get truncated by this operation.
1655 /// On success, the total number of bytes copied is returned and it is equal to
1656 /// the length of the `to` file as reported by `metadata`.
1658 /// If you’re wanting to copy the contents of one file to another and you’re
1659 /// working with [`File`]s, see the [`io::copy()`] function.
1661 /// # Platform-specific behavior
1663 /// This function currently corresponds to the `open` function in Unix
1664 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1665 /// `O_CLOEXEC` is set for returned file descriptors.
1666 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1667 /// NTFS streams are copied but only the size of the main stream is returned by
1668 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1670 /// Note that, this [may change in the future][changes].
1672 /// [changes]: io#platform-specific-behavior
1676 /// This function will return an error in the following situations, but is not
1677 /// limited to just these cases:
1679 /// * The `from` path is not a file.
1680 /// * The `from` file does not exist.
1681 /// * The current process does not have the permission rights to access
1682 /// `from` or write `to`.
1689 /// fn main() -> std::io::Result<()> {
1690 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1696 fs_imp::copy(from.as_ref(), to.as_ref())
1699 /// Creates a new hard link on the filesystem.
1701 /// The `link` path will be a link pointing to the `original` path. Note that
1702 /// systems often require these two paths to both be located on the same
1705 /// If `original` names a symbolic link, it is platform-specific whether the
1706 /// symbolic link is followed. On platforms where it's possible to not follow
1707 /// it, it is not followed, and the created hard link points to the symbolic
1710 /// # Platform-specific behavior
1712 /// This function currently corresponds to the `linkat` function with no flags
1713 /// on Unix and the `CreateHardLink` function on Windows.
1714 /// Note that, this [may change in the future][changes].
1716 /// [changes]: io#platform-specific-behavior
1720 /// This function will return an error in the following situations, but is not
1721 /// limited to just these cases:
1723 /// * The `original` path is not a file or doesn't exist.
1730 /// fn main() -> std::io::Result<()> {
1731 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1737 fs_imp::link(original.as_ref(), link.as_ref())
1740 /// Creates a new symbolic link on the filesystem.
1742 /// The `link` path will be a symbolic link pointing to the `original` path.
1743 /// On Windows, this will be a file symlink, not a directory symlink;
1744 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1745 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1746 /// used instead to make the intent explicit.
1748 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1749 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1750 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1757 /// fn main() -> std::io::Result<()> {
1758 /// fs::soft_link("a.txt", "b.txt")?;
1762 #[stable(feature = "rust1", since = "1.0.0")]
1765 reason = "replaced with std::os::unix::fs::symlink and \
1766 std::os::windows::fs::{symlink_file, symlink_dir}"
1768 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1769 fs_imp::symlink(original.as_ref(), link.as_ref())
1772 /// Reads a symbolic link, returning the file that the link points to.
1774 /// # Platform-specific behavior
1776 /// This function currently corresponds to the `readlink` function on Unix
1777 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1778 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1779 /// Note that, this [may change in the future][changes].
1781 /// [changes]: io#platform-specific-behavior
1785 /// This function will return an error in the following situations, but is not
1786 /// limited to just these cases:
1788 /// * `path` is not a symbolic link.
1789 /// * `path` does not exist.
1796 /// fn main() -> std::io::Result<()> {
1797 /// let path = fs::read_link("a.txt")?;
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1803 fs_imp::readlink(path.as_ref())
1806 /// Returns the canonical, absolute form of a path with all intermediate
1807 /// components normalized and symbolic links resolved.
1809 /// # Platform-specific behavior
1811 /// This function currently corresponds to the `realpath` function on Unix
1812 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1813 /// Note that, this [may change in the future][changes].
1815 /// On Windows, this converts the path to use [extended length path][path]
1816 /// syntax, which allows your program to use longer path names, but means you
1817 /// can only join backslash-delimited paths to it, and it may be incompatible
1818 /// with other applications (if passed to the application on the command-line,
1819 /// or written to a file another application may read).
1821 /// [changes]: io#platform-specific-behavior
1822 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1826 /// This function will return an error in the following situations, but is not
1827 /// limited to just these cases:
1829 /// * `path` does not exist.
1830 /// * A non-final component in path is not a directory.
1837 /// fn main() -> std::io::Result<()> {
1838 /// let path = fs::canonicalize("../a/../foo.txt")?;
1842 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1843 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1844 fs_imp::canonicalize(path.as_ref())
1847 /// Creates a new, empty directory at the provided path
1849 /// # Platform-specific behavior
1851 /// This function currently corresponds to the `mkdir` function on Unix
1852 /// and the `CreateDirectory` function on Windows.
1853 /// Note that, this [may change in the future][changes].
1855 /// [changes]: io#platform-specific-behavior
1857 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1858 /// return an error. To create a directory and all its missing parents at the
1859 /// same time, use the [`create_dir_all`] function.
1863 /// This function will return an error in the following situations, but is not
1864 /// limited to just these cases:
1866 /// * User lacks permissions to create directory at `path`.
1867 /// * A parent of the given path doesn't exist. (To create a directory and all
1868 /// its missing parents at the same time, use the [`create_dir_all`]
1870 /// * `path` already exists.
1877 /// fn main() -> std::io::Result<()> {
1878 /// fs::create_dir("/some/dir")?;
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1884 DirBuilder::new().create(path.as_ref())
1887 /// Recursively create a directory and all of its parent components if they
1890 /// # Platform-specific behavior
1892 /// This function currently corresponds to the `mkdir` function on Unix
1893 /// and the `CreateDirectory` function on Windows.
1894 /// Note that, this [may change in the future][changes].
1896 /// [changes]: io#platform-specific-behavior
1900 /// This function will return an error in the following situations, but is not
1901 /// limited to just these cases:
1903 /// * If any directory in the path specified by `path`
1904 /// does not already exist and it could not be created otherwise. The specific
1905 /// error conditions for when a directory is being created (after it is
1906 /// determined to not exist) are outlined by [`fs::create_dir`].
1908 /// Notable exception is made for situations where any of the directories
1909 /// specified in the `path` could not be created as it was being created concurrently.
1910 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1911 /// concurrently from multiple threads or processes is guaranteed not to fail
1912 /// due to a race condition with itself.
1914 /// [`fs::create_dir`]: create_dir
1921 /// fn main() -> std::io::Result<()> {
1922 /// fs::create_dir_all("/some/dir")?;
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1928 DirBuilder::new().recursive(true).create(path.as_ref())
1931 /// Removes an empty directory.
1933 /// # Platform-specific behavior
1935 /// This function currently corresponds to the `rmdir` function on Unix
1936 /// and the `RemoveDirectory` function on Windows.
1937 /// Note that, this [may change in the future][changes].
1939 /// [changes]: io#platform-specific-behavior
1943 /// This function will return an error in the following situations, but is not
1944 /// limited to just these cases:
1946 /// * `path` doesn't exist.
1947 /// * `path` isn't a directory.
1948 /// * The user lacks permissions to remove the directory at the provided `path`.
1949 /// * The directory isn't empty.
1956 /// fn main() -> std::io::Result<()> {
1957 /// fs::remove_dir("/some/dir")?;
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1963 fs_imp::rmdir(path.as_ref())
1966 /// Removes a directory at this path, after removing all its contents. Use
1969 /// This function does **not** follow symbolic links and it will simply remove the
1970 /// symbolic link itself.
1972 /// # Platform-specific behavior
1974 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1975 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1977 /// Note that, this [may change in the future][changes].
1979 /// [changes]: io#platform-specific-behavior
1983 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1985 /// [`fs::remove_file`]: remove_file
1986 /// [`fs::remove_dir`]: remove_dir
1993 /// fn main() -> std::io::Result<()> {
1994 /// fs::remove_dir_all("/some/dir")?;
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2000 fs_imp::remove_dir_all(path.as_ref())
2003 /// Returns an iterator over the entries within a directory.
2005 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2006 /// New errors may be encountered after an iterator is initially constructed.
2008 /// # Platform-specific behavior
2010 /// This function currently corresponds to the `opendir` function on Unix
2011 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2012 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2013 /// Note that, this [may change in the future][changes].
2015 /// [changes]: io#platform-specific-behavior
2017 /// The order in which this iterator returns entries is platform and filesystem
2022 /// This function will return an error in the following situations, but is not
2023 /// limited to just these cases:
2025 /// * The provided `path` doesn't exist.
2026 /// * The process lacks permissions to view the contents.
2027 /// * The `path` points at a non-directory file.
2033 /// use std::fs::{self, DirEntry};
2034 /// use std::path::Path;
2036 /// // one possible implementation of walking a directory only visiting files
2037 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2038 /// if dir.is_dir() {
2039 /// for entry in fs::read_dir(dir)? {
2040 /// let entry = entry?;
2041 /// let path = entry.path();
2042 /// if path.is_dir() {
2043 /// visit_dirs(&path, cb)?;
2054 /// use std::{fs, io};
2056 /// fn main() -> io::Result<()> {
2057 /// let mut entries = fs::read_dir(".")?
2058 /// .map(|res| res.map(|e| e.path()))
2059 /// .collect::<Result<Vec<_>, io::Error>>()?;
2061 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2062 /// // ordering is required the entries should be explicitly sorted.
2066 /// // The entries have now been sorted by their path.
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2073 fs_imp::readdir(path.as_ref()).map(ReadDir)
2076 /// Changes the permissions found on a file or a directory.
2078 /// # Platform-specific behavior
2080 /// This function currently corresponds to the `chmod` function on Unix
2081 /// and the `SetFileAttributes` function on Windows.
2082 /// Note that, this [may change in the future][changes].
2084 /// [changes]: io#platform-specific-behavior
2088 /// This function will return an error in the following situations, but is not
2089 /// limited to just these cases:
2091 /// * `path` does not exist.
2092 /// * The user lacks the permission to change attributes of the file.
2099 /// fn main() -> std::io::Result<()> {
2100 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2101 /// perms.set_readonly(true);
2102 /// fs::set_permissions("foo.txt", perms)?;
2106 #[stable(feature = "set_permissions", since = "1.1.0")]
2107 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2108 fs_imp::set_perm(path.as_ref(), perm.0)
2112 /// Creates a new set of options with default mode/security settings for all
2113 /// platforms and also non-recursive.
2118 /// use std::fs::DirBuilder;
2120 /// let builder = DirBuilder::new();
2122 #[stable(feature = "dir_builder", since = "1.6.0")]
2123 pub fn new() -> DirBuilder {
2124 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2127 /// Indicates that directories should be created recursively, creating all
2128 /// parent directories. Parents that do not exist are created with the same
2129 /// security and permissions settings.
2131 /// This option defaults to `false`.
2136 /// use std::fs::DirBuilder;
2138 /// let mut builder = DirBuilder::new();
2139 /// builder.recursive(true);
2141 #[stable(feature = "dir_builder", since = "1.6.0")]
2142 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2143 self.recursive = recursive;
2147 /// Creates the specified directory with the options configured in this
2150 /// It is considered an error if the directory already exists unless
2151 /// recursive mode is enabled.
2156 /// use std::fs::{self, DirBuilder};
2158 /// let path = "/tmp/foo/bar/baz";
2159 /// DirBuilder::new()
2160 /// .recursive(true)
2161 /// .create(path).unwrap();
2163 /// assert!(fs::metadata(path).unwrap().is_dir());
2165 #[stable(feature = "dir_builder", since = "1.6.0")]
2166 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2167 self._create(path.as_ref())
2170 fn _create(&self, path: &Path) -> io::Result<()> {
2171 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2174 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2175 if path == Path::new("") {
2179 match self.inner.mkdir(path) {
2180 Ok(()) => return Ok(()),
2181 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2182 Err(_) if path.is_dir() => return Ok(()),
2183 Err(e) => return Err(e),
2185 match path.parent() {
2186 Some(p) => self.create_dir_all(p)?,
2188 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2191 match self.inner.mkdir(path) {
2193 Err(_) if path.is_dir() => Ok(()),
2199 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2200 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {