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, BorrowedCursor, 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 /// An object providing access 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 /// # Platform-specific behavior
90 /// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
91 /// perform synchronous I/O operations. Therefore the underlying file must not
92 /// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
94 /// [`BufReader<R>`]: io::BufReader
95 /// [`sync_all`]: File::sync_all
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
102 /// Metadata information about a file.
104 /// This structure is returned from the [`metadata`] or
105 /// [`symlink_metadata`] function or method and represents known
106 /// metadata about a file such as its permissions, size, modification
108 #[stable(feature = "rust1", since = "1.0.0")]
110 pub struct Metadata(fs_imp::FileAttr);
112 /// Iterator over the entries in a directory.
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
119 /// The order in which this iterator returns entries is platform and filesystem
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
126 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct ReadDir(fs_imp::ReadDir);
130 /// Entries returned by the [`ReadDir`] iterator.
132 /// An instance of `DirEntry` represents an entry inside of a directory on the
133 /// filesystem. Each entry can be inspected via methods to learn about the full
134 /// path or possibly other metadata through per-platform extension traits.
136 /// # Platform-specific behavior
138 /// On Unix, the `DirEntry` struct contains an internal reference to the open
139 /// directory. Holding `DirEntry` objects will consume a file handle even
140 /// after the `ReadDir` iterator is dropped.
142 /// Note that this [may change in the future][changes].
144 /// [changes]: io#platform-specific-behavior
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub struct DirEntry(fs_imp::DirEntry);
148 /// Options and flags which can be used to configure how a file is opened.
150 /// This builder exposes the ability to configure how a [`File`] is opened and
151 /// what operations are permitted on the open file. The [`File::open`] and
152 /// [`File::create`] methods are aliases for commonly used options using this
155 /// Generally speaking, when using `OpenOptions`, you'll first call
156 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
157 /// call [`OpenOptions::open`], passing the path of the file you're trying to
158 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
159 /// can further operate on.
163 /// Opening a file to read:
166 /// use std::fs::OpenOptions;
168 /// let file = OpenOptions::new().read(true).open("foo.txt");
171 /// Opening a file for both reading and writing, as well as creating it if it
175 /// use std::fs::OpenOptions;
177 /// let file = OpenOptions::new()
181 /// .open("foo.txt");
183 #[derive(Clone, Debug)]
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub struct OpenOptions(fs_imp::OpenOptions);
187 /// Representation of the various timestamps on a file.
188 #[derive(Copy, Clone, Debug, Default)]
189 #[unstable(feature = "file_set_times", issue = "98245")]
190 pub struct FileTimes(fs_imp::FileTimes);
192 /// Representation of the various permissions on a file.
194 /// This module only currently provides one bit of information,
195 /// [`Permissions::readonly`], which is exposed on all currently supported
196 /// platforms. Unix-specific functionality, such as mode bits, is available
197 /// through the [`PermissionsExt`] trait.
199 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
200 #[derive(Clone, PartialEq, Eq, Debug)]
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub struct Permissions(fs_imp::FilePermissions);
204 /// A structure representing a type of file with accessors for each file type.
205 /// It is returned by [`Metadata::file_type`] method.
206 #[stable(feature = "file_type", since = "1.1.0")]
207 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
208 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
209 pub struct FileType(fs_imp::FileType);
211 /// A builder used to create directories in various manners.
213 /// This builder also supports platform-specific options.
214 #[stable(feature = "dir_builder", since = "1.6.0")]
215 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
217 pub struct DirBuilder {
218 inner: fs_imp::DirBuilder,
222 /// Read the entire contents of a file into a bytes vector.
224 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
225 /// with fewer imports and without an intermediate variable.
227 /// [`read_to_end`]: Read::read_to_end
231 /// This function will return an error if `path` does not already exist.
232 /// Other errors may also be returned according to [`OpenOptions::open`].
234 /// It will also return an error if it encounters while reading an error
235 /// of a kind other than [`io::ErrorKind::Interrupted`].
241 /// use std::net::SocketAddr;
243 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
244 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
248 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
249 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
250 fn inner(path: &Path) -> io::Result<Vec<u8>> {
251 let mut file = File::open(path)?;
252 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
253 let mut bytes = Vec::with_capacity(size as usize);
254 io::default_read_to_end(&mut file, &mut bytes)?;
260 /// Read the entire contents of a file into a string.
262 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
263 /// with fewer imports and without an intermediate variable.
265 /// [`read_to_string`]: Read::read_to_string
269 /// This function will return an error if `path` does not already exist.
270 /// Other errors may also be returned according to [`OpenOptions::open`].
272 /// It will also return an error if it encounters while reading an error
273 /// of a kind other than [`io::ErrorKind::Interrupted`],
274 /// or if the contents of the file are not valid UTF-8.
280 /// use std::net::SocketAddr;
281 /// use std::error::Error;
283 /// fn main() -> Result<(), Box<dyn Error>> {
284 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
288 #[stable(feature = "fs_read_write", since = "1.26.0")]
289 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
290 fn inner(path: &Path) -> io::Result<String> {
291 let mut file = File::open(path)?;
292 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
293 let mut string = String::with_capacity(size as usize);
294 io::default_read_to_string(&mut file, &mut string)?;
300 /// Write a slice as the entire contents of a file.
302 /// This function will create a file if it does not exist,
303 /// and will entirely replace its contents if it does.
305 /// Depending on the platform, this function may fail if the
306 /// full directory path does not exist.
308 /// This is a convenience function for using [`File::create`] and [`write_all`]
309 /// with fewer imports.
311 /// [`write_all`]: Write::write_all
318 /// fn main() -> std::io::Result<()> {
319 /// fs::write("foo.txt", b"Lorem ipsum")?;
320 /// fs::write("bar.txt", "dolor sit")?;
324 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
325 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
326 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
327 File::create(path)?.write_all(contents)
329 inner(path.as_ref(), contents.as_ref())
333 /// Attempts to open a file in read-only mode.
335 /// See the [`OpenOptions::open`] method for more details.
339 /// This function will return an error if `path` does not already exist.
340 /// Other errors may also be returned according to [`OpenOptions::open`].
345 /// use std::fs::File;
347 /// fn main() -> std::io::Result<()> {
348 /// let mut f = File::open("foo.txt")?;
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
354 OpenOptions::new().read(true).open(path.as_ref())
357 /// Opens a file in write-only mode.
359 /// This function will create a file if it does not exist,
360 /// and will truncate it if it does.
362 /// Depending on the platform, this function may fail if the
363 /// full directory path does not exist.
365 /// See the [`OpenOptions::open`] function for more details.
370 /// use std::fs::File;
372 /// fn main() -> std::io::Result<()> {
373 /// let mut f = File::create("foo.txt")?;
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
379 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
382 /// Creates a new file in read-write mode; error if the file exists.
384 /// This function will create a file if it does not exist, or return an error if it does. This
385 /// way, if the call succeeds, the file returned is guaranteed to be new.
387 /// This option is useful because it is atomic. Otherwise between checking whether a file
388 /// exists and creating a new one, the file may have been created by another process (a TOCTOU
389 /// race condition / attack).
391 /// This can also be written using
392 /// `File::options().read(true).write(true).create_new(true).open(...)`.
397 /// #![feature(file_create_new)]
399 /// use std::fs::File;
401 /// fn main() -> std::io::Result<()> {
402 /// let mut f = File::create_new("foo.txt")?;
406 #[unstable(feature = "file_create_new", issue = "105135")]
407 pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
408 OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
411 /// Returns a new OpenOptions object.
413 /// This function returns a new OpenOptions object that you can use to
414 /// open or create a file with specific options if `open()` or `create()`
415 /// are not appropriate.
417 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
418 /// readable code. Instead of
419 /// `OpenOptions::new().append(true).open("example.log")`,
420 /// you can write `File::options().append(true).open("example.log")`. This
421 /// also avoids the need to import `OpenOptions`.
423 /// See the [`OpenOptions::new`] function for more details.
428 /// use std::fs::File;
430 /// fn main() -> std::io::Result<()> {
431 /// let mut f = File::options().append(true).open("example.log")?;
436 #[stable(feature = "with_options", since = "1.58.0")]
437 pub fn options() -> OpenOptions {
441 /// Attempts to sync all OS-internal metadata to disk.
443 /// This function will attempt to ensure that all in-memory data reaches the
444 /// filesystem before returning.
446 /// This can be used to handle errors that would otherwise only be caught
447 /// when the `File` is closed. Dropping a file will ignore errors in
448 /// synchronizing this in-memory data.
453 /// use std::fs::File;
454 /// use std::io::prelude::*;
456 /// fn main() -> std::io::Result<()> {
457 /// let mut f = File::create("foo.txt")?;
458 /// f.write_all(b"Hello, world!")?;
464 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn sync_all(&self) -> io::Result<()> {
469 /// This function is similar to [`sync_all`], except that it might not
470 /// synchronize file metadata to the filesystem.
472 /// This is intended for use cases that must synchronize content, but don't
473 /// need the metadata on disk. The goal of this method is to reduce disk
476 /// Note that some platforms may simply implement this in terms of
479 /// [`sync_all`]: File::sync_all
484 /// use std::fs::File;
485 /// use std::io::prelude::*;
487 /// fn main() -> std::io::Result<()> {
488 /// let mut f = File::create("foo.txt")?;
489 /// f.write_all(b"Hello, world!")?;
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn sync_data(&self) -> io::Result<()> {
497 self.inner.datasync()
500 /// Truncates or extends the underlying file, updating the size of
501 /// this file to become `size`.
503 /// If the `size` is less than the current file's size, then the file will
504 /// be shrunk. If it is greater than the current file's size, then the file
505 /// will be extended to `size` and have all of the intermediate data filled
508 /// The file's cursor isn't changed. In particular, if the cursor was at the
509 /// end and the file is shrunk using this operation, the cursor will now be
514 /// This function will return an error if the file is not opened for writing.
515 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
516 /// will be returned if the desired length would cause an overflow due to
517 /// the implementation specifics.
522 /// use std::fs::File;
524 /// fn main() -> std::io::Result<()> {
525 /// let mut f = File::create("foo.txt")?;
531 /// Note that this method alters the content of the underlying file, even
532 /// though it takes `&self` rather than `&mut self`.
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn set_len(&self, size: u64) -> io::Result<()> {
535 self.inner.truncate(size)
538 /// Queries metadata about the underlying file.
543 /// use std::fs::File;
545 /// fn main() -> std::io::Result<()> {
546 /// let mut f = File::open("foo.txt")?;
547 /// let metadata = f.metadata()?;
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn metadata(&self) -> io::Result<Metadata> {
553 self.inner.file_attr().map(Metadata)
556 /// Creates a new `File` instance that shares the same underlying file handle
557 /// as the existing `File` instance. Reads, writes, and seeks will affect
558 /// both `File` instances simultaneously.
562 /// Creates two handles for a file named `foo.txt`:
565 /// use std::fs::File;
567 /// fn main() -> std::io::Result<()> {
568 /// let mut file = File::open("foo.txt")?;
569 /// let file_copy = file.try_clone()?;
574 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
575 /// two handles, seek one of them, and read the remaining bytes from the
579 /// use std::fs::File;
580 /// use std::io::SeekFrom;
581 /// use std::io::prelude::*;
583 /// fn main() -> std::io::Result<()> {
584 /// let mut file = File::open("foo.txt")?;
585 /// let mut file_copy = file.try_clone()?;
587 /// file.seek(SeekFrom::Start(3))?;
589 /// let mut contents = vec![];
590 /// file_copy.read_to_end(&mut contents)?;
591 /// assert_eq!(contents, b"def\n");
595 #[stable(feature = "file_try_clone", since = "1.9.0")]
596 pub fn try_clone(&self) -> io::Result<File> {
597 Ok(File { inner: self.inner.duplicate()? })
600 /// Changes the permissions on the underlying file.
602 /// # Platform-specific behavior
604 /// This function currently corresponds to the `fchmod` function on Unix and
605 /// the `SetFileInformationByHandle` function on Windows. Note that, this
606 /// [may change in the future][changes].
608 /// [changes]: io#platform-specific-behavior
612 /// This function will return an error if the user lacks permission change
613 /// attributes on the underlying file. It may also return an error in other
614 /// os-specific unspecified cases.
619 /// fn main() -> std::io::Result<()> {
620 /// use std::fs::File;
622 /// let file = File::open("foo.txt")?;
623 /// let mut perms = file.metadata()?.permissions();
624 /// perms.set_readonly(true);
625 /// file.set_permissions(perms)?;
630 /// Note that this method alters the permissions of the underlying file,
631 /// even though it takes `&self` rather than `&mut self`.
632 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
633 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
634 self.inner.set_permissions(perm.0)
637 /// Changes the timestamps of the underlying file.
639 /// # Platform-specific behavior
641 /// This function currently corresponds to the `futimens` function on Unix (falling back to
642 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
643 /// [may change in the future][changes].
645 /// [changes]: io#platform-specific-behavior
649 /// This function will return an error if the user lacks permission to change timestamps on the
650 /// underlying file. It may also return an error in other os-specific unspecified cases.
652 /// This function may return an error if the operating system lacks support to change one or
653 /// more of the timestamps set in the `FileTimes` structure.
658 /// #![feature(file_set_times)]
660 /// fn main() -> std::io::Result<()> {
661 /// use std::fs::{self, File, FileTimes};
663 /// let src = fs::metadata("src")?;
664 /// let dest = File::options().write(true).open("dest")?;
665 /// let times = FileTimes::new()
666 /// .set_accessed(src.accessed()?)
667 /// .set_modified(src.modified()?);
668 /// dest.set_times(times)?;
672 #[unstable(feature = "file_set_times", issue = "98245")]
673 #[doc(alias = "futimens")]
674 #[doc(alias = "futimes")]
675 #[doc(alias = "SetFileTime")]
676 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
677 self.inner.set_times(times.0)
680 /// Changes the modification time of the underlying file.
682 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
683 #[unstable(feature = "file_set_times", issue = "98245")]
685 pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
686 self.set_times(FileTimes::new().set_modified(time))
690 // In addition to the `impl`s here, `File` also has `impl`s for
691 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
692 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
693 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
694 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
696 impl AsInner<fs_imp::File> for File {
697 fn as_inner(&self) -> &fs_imp::File {
701 impl FromInner<fs_imp::File> for File {
702 fn from_inner(f: fs_imp::File) -> File {
706 impl IntoInner<fs_imp::File> for File {
707 fn into_inner(self) -> fs_imp::File {
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl fmt::Debug for File {
714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 /// Indicates how much extra capacity is needed to read the rest of the file.
720 fn buffer_capacity_required(mut file: &File) -> usize {
721 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
722 let pos = file.stream_position().unwrap_or(0);
723 // Don't worry about `usize` overflow because reading will fail regardless
725 size.saturating_sub(pos) as usize
728 #[stable(feature = "rust1", since = "1.0.0")]
730 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
734 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
735 self.inner.read_vectored(bufs)
738 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
739 self.inner.read_buf(cursor)
743 fn is_read_vectored(&self) -> bool {
744 self.inner.is_read_vectored()
747 // Reserves space in the buffer based on the file size when available.
748 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
749 buf.reserve(buffer_capacity_required(self));
750 io::default_read_to_end(self, buf)
753 // Reserves space in the buffer based on the file size when available.
754 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
755 buf.reserve(buffer_capacity_required(self));
756 io::default_read_to_string(self, buf)
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl Write for File {
761 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
762 self.inner.write(buf)
765 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
766 self.inner.write_vectored(bufs)
770 fn is_write_vectored(&self) -> bool {
771 self.inner.is_write_vectored()
774 fn flush(&mut self) -> io::Result<()> {
778 #[stable(feature = "rust1", since = "1.0.0")]
780 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
784 #[stable(feature = "rust1", since = "1.0.0")]
785 impl Read for &File {
786 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
790 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
791 self.inner.read_buf(cursor)
794 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
795 self.inner.read_vectored(bufs)
799 fn is_read_vectored(&self) -> bool {
800 self.inner.is_read_vectored()
803 // Reserves space in the buffer based on the file size when available.
804 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
805 buf.reserve(buffer_capacity_required(self));
806 io::default_read_to_end(self, buf)
809 // Reserves space in the buffer based on the file size when available.
810 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
811 buf.reserve(buffer_capacity_required(self));
812 io::default_read_to_string(self, buf)
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl Write for &File {
817 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
818 self.inner.write(buf)
821 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
822 self.inner.write_vectored(bufs)
826 fn is_write_vectored(&self) -> bool {
827 self.inner.is_write_vectored()
830 fn flush(&mut self) -> io::Result<()> {
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl Seek for &File {
836 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
842 /// Creates a blank new set of options ready for configuration.
844 /// All options are initially set to `false`.
849 /// use std::fs::OpenOptions;
851 /// let mut options = OpenOptions::new();
852 /// let file = options.read(true).open("foo.txt");
854 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn new() -> Self {
857 OpenOptions(fs_imp::OpenOptions::new())
860 /// Sets the option for read access.
862 /// This option, when true, will indicate that the file should be
863 /// `read`-able if opened.
868 /// use std::fs::OpenOptions;
870 /// let file = OpenOptions::new().read(true).open("foo.txt");
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn read(&mut self, read: bool) -> &mut Self {
878 /// Sets the option for write access.
880 /// This option, when true, will indicate that the file should be
881 /// `write`-able if opened.
883 /// If the file already exists, any write calls on it will overwrite its
884 /// contents, without truncating it.
889 /// use std::fs::OpenOptions;
891 /// let file = OpenOptions::new().write(true).open("foo.txt");
893 #[stable(feature = "rust1", since = "1.0.0")]
894 pub fn write(&mut self, write: bool) -> &mut Self {
899 /// Sets the option for the append mode.
901 /// This option, when true, means that writes will append to a file instead
902 /// of overwriting previous contents.
903 /// Note that setting `.write(true).append(true)` has the same effect as
904 /// setting only `.append(true)`.
906 /// For most filesystems, the operating system guarantees that all writes are
907 /// atomic: no writes get mangled because another process writes at the same
910 /// One maybe obvious note when using append-mode: make sure that all data
911 /// that belongs together is written to the file in one operation. This
912 /// can be done by concatenating strings before passing them to [`write()`],
913 /// or using a buffered writer (with a buffer of adequate size),
914 /// and calling [`flush()`] when the message is complete.
916 /// If a file is opened with both read and append access, beware that after
917 /// opening, and after every write, the position for reading may be set at the
918 /// end of the file. So, before writing, save the current position (using
919 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
923 /// This function doesn't create the file if it doesn't exist. Use the
924 /// [`OpenOptions::create`] method to do so.
926 /// [`write()`]: Write::write "io::Write::write"
927 /// [`flush()`]: Write::flush "io::Write::flush"
928 /// [seek]: Seek::seek "io::Seek::seek"
929 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
934 /// use std::fs::OpenOptions;
936 /// let file = OpenOptions::new().append(true).open("foo.txt");
938 #[stable(feature = "rust1", since = "1.0.0")]
939 pub fn append(&mut self, append: bool) -> &mut Self {
940 self.0.append(append);
944 /// Sets the option for truncating a previous file.
946 /// If a file is successfully opened with this option set it will truncate
947 /// the file to 0 length if it already exists.
949 /// The file must be opened with write access for truncate to work.
954 /// use std::fs::OpenOptions;
956 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
958 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
960 self.0.truncate(truncate);
964 /// Sets the option to create a new file, or open it if it already exists.
966 /// In order for the file to be created, [`OpenOptions::write`] or
967 /// [`OpenOptions::append`] access must be used.
972 /// use std::fs::OpenOptions;
974 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn create(&mut self, create: bool) -> &mut Self {
978 self.0.create(create);
982 /// Sets the option to create a new file, failing if it already exists.
984 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
985 /// way, if the call succeeds, the file returned is guaranteed to be new.
987 /// This option is useful because it is atomic. Otherwise between checking
988 /// whether a file exists and creating a new one, the file may have been
989 /// created by another process (a TOCTOU race condition / attack).
991 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
994 /// The file must be opened with write or append access in order to create
997 /// [`.create()`]: OpenOptions::create
998 /// [`.truncate()`]: OpenOptions::truncate
1003 /// use std::fs::OpenOptions;
1005 /// let file = OpenOptions::new().write(true)
1006 /// .create_new(true)
1007 /// .open("foo.txt");
1009 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1010 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1011 self.0.create_new(create_new);
1015 /// Opens a file at `path` with the options specified by `self`.
1019 /// This function will return an error under a number of different
1020 /// circumstances. Some of these error conditions are listed here, together
1021 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1022 /// part of the compatibility contract of the function.
1024 /// * [`NotFound`]: The specified file does not exist and neither `create`
1025 /// or `create_new` is set.
1026 /// * [`NotFound`]: One of the directory components of the file path does
1028 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1029 /// access rights for the file.
1030 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1031 /// directory components of the specified path.
1032 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1034 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1035 /// without write access, no access mode set, etc.).
1037 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1038 /// * One of the directory components of the specified file path
1039 /// was not, in fact, a directory.
1040 /// * Filesystem-level errors: full disk, write permission
1041 /// requested on a read-only file system, exceeded disk quota, too many
1042 /// open files, too long filename, too many symbolic links in the
1043 /// specified path (Unix-like systems only), etc.
1048 /// use std::fs::OpenOptions;
1050 /// let file = OpenOptions::new().read(true).open("foo.txt");
1053 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1054 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1055 /// [`NotFound`]: io::ErrorKind::NotFound
1056 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1059 self._open(path.as_ref())
1062 fn _open(&self, path: &Path) -> io::Result<File> {
1063 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1067 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1068 fn as_inner(&self) -> &fs_imp::OpenOptions {
1073 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1074 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1080 /// Returns the file type for this metadata.
1085 /// fn main() -> std::io::Result<()> {
1088 /// let metadata = fs::metadata("foo.txt")?;
1090 /// println!("{:?}", metadata.file_type());
1095 #[stable(feature = "file_type", since = "1.1.0")]
1096 pub fn file_type(&self) -> FileType {
1097 FileType(self.0.file_type())
1100 /// Returns `true` if this metadata is for a directory. The
1101 /// result is mutually exclusive to the result of
1102 /// [`Metadata::is_file`], and will be false for symlink metadata
1103 /// obtained from [`symlink_metadata`].
1108 /// fn main() -> std::io::Result<()> {
1111 /// let metadata = fs::metadata("foo.txt")?;
1113 /// assert!(!metadata.is_dir());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn is_dir(&self) -> bool {
1120 self.file_type().is_dir()
1123 /// Returns `true` if this metadata is for a regular file. The
1124 /// result is mutually exclusive to the result of
1125 /// [`Metadata::is_dir`], and will be false for symlink metadata
1126 /// obtained from [`symlink_metadata`].
1128 /// When the goal is simply to read from (or write to) the source, the most
1129 /// reliable way to test the source can be read (or written to) is to open
1130 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1131 /// a Unix-like system for example. See [`File::open`] or
1132 /// [`OpenOptions::open`] for more information.
1139 /// fn main() -> std::io::Result<()> {
1140 /// let metadata = fs::metadata("foo.txt")?;
1142 /// assert!(metadata.is_file());
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 pub fn is_file(&self) -> bool {
1149 self.file_type().is_file()
1152 /// Returns `true` if this metadata is for a symbolic link.
1156 #[cfg_attr(unix, doc = "```no_run")]
1157 #[cfg_attr(not(unix), doc = "```ignore")]
1159 /// use std::path::Path;
1160 /// use std::os::unix::fs::symlink;
1162 /// fn main() -> std::io::Result<()> {
1163 /// let link_path = Path::new("link");
1164 /// symlink("/origin_does_not_exist/", link_path)?;
1166 /// let metadata = fs::symlink_metadata(link_path)?;
1168 /// assert!(metadata.is_symlink());
1173 #[stable(feature = "is_symlink", since = "1.58.0")]
1174 pub fn is_symlink(&self) -> bool {
1175 self.file_type().is_symlink()
1178 /// Returns the size of the file, in bytes, this metadata is for.
1185 /// fn main() -> std::io::Result<()> {
1186 /// let metadata = fs::metadata("foo.txt")?;
1188 /// assert_eq!(0, metadata.len());
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn len(&self) -> u64 {
1198 /// Returns the permissions of the file this metadata is for.
1205 /// fn main() -> std::io::Result<()> {
1206 /// let metadata = fs::metadata("foo.txt")?;
1208 /// assert!(!metadata.permissions().readonly());
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub fn permissions(&self) -> Permissions {
1215 Permissions(self.0.perm())
1218 /// Returns the last modification time listed in this metadata.
1220 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1221 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1225 /// This field might not be available on all platforms, and will return an
1226 /// `Err` on platforms where it is not available.
1233 /// fn main() -> std::io::Result<()> {
1234 /// let metadata = fs::metadata("foo.txt")?;
1236 /// if let Ok(time) = metadata.modified() {
1237 /// println!("{time:?}");
1239 /// println!("Not supported on this platform");
1244 #[stable(feature = "fs_time", since = "1.10.0")]
1245 pub fn modified(&self) -> io::Result<SystemTime> {
1246 self.0.modified().map(FromInner::from_inner)
1249 /// Returns the last access time of this metadata.
1251 /// The returned value corresponds to the `atime` field of `stat` on Unix
1252 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1254 /// Note that not all platforms will keep this field update in a file's
1255 /// metadata, for example Windows has an option to disable updating this
1256 /// time when files are accessed and Linux similarly has `noatime`.
1260 /// This field might not be available on all platforms, and will return an
1261 /// `Err` on platforms where it is not available.
1268 /// fn main() -> std::io::Result<()> {
1269 /// let metadata = fs::metadata("foo.txt")?;
1271 /// if let Ok(time) = metadata.accessed() {
1272 /// println!("{time:?}");
1274 /// println!("Not supported on this platform");
1279 #[stable(feature = "fs_time", since = "1.10.0")]
1280 pub fn accessed(&self) -> io::Result<SystemTime> {
1281 self.0.accessed().map(FromInner::from_inner)
1284 /// Returns the creation time listed in this metadata.
1286 /// The returned value corresponds to the `btime` field of `statx` on
1287 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1288 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1292 /// This field might not be available on all platforms, and will return an
1293 /// `Err` on platforms or filesystems where it is not available.
1300 /// fn main() -> std::io::Result<()> {
1301 /// let metadata = fs::metadata("foo.txt")?;
1303 /// if let Ok(time) = metadata.created() {
1304 /// println!("{time:?}");
1306 /// println!("Not supported on this platform or filesystem");
1311 #[stable(feature = "fs_time", since = "1.10.0")]
1312 pub fn created(&self) -> io::Result<SystemTime> {
1313 self.0.created().map(FromInner::from_inner)
1317 #[stable(feature = "std_debug", since = "1.16.0")]
1318 impl fmt::Debug for Metadata {
1319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320 f.debug_struct("Metadata")
1321 .field("file_type", &self.file_type())
1322 .field("is_dir", &self.is_dir())
1323 .field("is_file", &self.is_file())
1324 .field("permissions", &self.permissions())
1325 .field("modified", &self.modified())
1326 .field("accessed", &self.accessed())
1327 .field("created", &self.created())
1328 .finish_non_exhaustive()
1332 impl AsInner<fs_imp::FileAttr> for Metadata {
1333 fn as_inner(&self) -> &fs_imp::FileAttr {
1338 impl FromInner<fs_imp::FileAttr> for Metadata {
1339 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1345 /// Create a new `FileTimes` with no times set.
1347 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
1348 #[unstable(feature = "file_set_times", issue = "98245")]
1349 pub fn new() -> Self {
1353 /// Set the last access time of a file.
1354 #[unstable(feature = "file_set_times", issue = "98245")]
1355 pub fn set_accessed(mut self, t: SystemTime) -> Self {
1356 self.0.set_accessed(t.into_inner());
1360 /// Set the last modified time of a file.
1361 #[unstable(feature = "file_set_times", issue = "98245")]
1362 pub fn set_modified(mut self, t: SystemTime) -> Self {
1363 self.0.set_modified(t.into_inner());
1369 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1373 /// This function does not take Access Control Lists (ACLs) or Unix group
1374 /// membership into account.
1378 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1379 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1380 /// but the user may still have permission to change this flag. If
1381 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
1382 /// to lack of write permission.
1383 /// The behavior of this attribute for directories depends on the Windows
1386 /// # Unix (including macOS)
1388 /// On Unix-based platforms this checks if *any* of the owner, group or others
1389 /// write permission bits are set. It does not check if the current
1390 /// user is in the file's assigned group. It also does not check ACLs.
1391 /// Therefore even if this returns true you may not be able to write to the
1392 /// file, and vice versa. The [`PermissionsExt`] trait gives direct access
1393 /// to the permission bits but also does not read ACLs. If you need to
1394 /// accurately know whether or not a file is writable use the `access()`
1395 /// function from libc.
1397 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1402 /// use std::fs::File;
1404 /// fn main() -> std::io::Result<()> {
1405 /// let mut f = File::create("foo.txt")?;
1406 /// let metadata = f.metadata()?;
1408 /// assert_eq!(false, metadata.permissions().readonly());
1412 #[must_use = "call `set_readonly` to modify the readonly flag"]
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub fn readonly(&self) -> bool {
1418 /// Modifies the readonly flag for this set of permissions. If the
1419 /// `readonly` argument is `true`, using the resulting `Permission` will
1420 /// update file permissions to forbid writing. Conversely, if it's `false`,
1421 /// using the resulting `Permission` will update file permissions to allow
1424 /// This operation does **not** modify the files attributes. This only
1425 /// changes the in-memory value of these attributes for this `Permissions`
1426 /// instance. To modify the files attributes use the [`set_permissions`]
1427 /// function which commits these attribute changes to the file.
1431 /// `set_readonly(false)` makes the file *world-writable* on Unix.
1432 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
1434 /// It also does not take Access Control Lists (ACLs) or Unix group
1435 /// membership into account.
1439 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1440 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1441 /// but the user may still have permission to change this flag. If
1442 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
1443 /// the user does not have permission to write to the file.
1445 /// In Windows 7 and earlier this attribute prevents deleting empty
1446 /// directories. It does not prevent modifying the directory contents.
1447 /// On later versions of Windows this attribute is ignored for directories.
1449 /// # Unix (including macOS)
1451 /// On Unix-based platforms this sets or clears the write access bit for
1452 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
1453 /// or `chmod a-w <file>` respectively. The latter will grant write access
1454 /// to all users! You can use the [`PermissionsExt`] trait on Unix
1455 /// to avoid this issue.
1457 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1462 /// use std::fs::File;
1464 /// fn main() -> std::io::Result<()> {
1465 /// let f = File::create("foo.txt")?;
1466 /// let metadata = f.metadata()?;
1467 /// let mut permissions = metadata.permissions();
1469 /// permissions.set_readonly(true);
1471 /// // filesystem doesn't change, only the in memory state of the
1472 /// // readonly permission
1473 /// assert_eq!(false, metadata.permissions().readonly());
1475 /// // just this particular `permissions`.
1476 /// assert_eq!(true, permissions.readonly());
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub fn set_readonly(&mut self, readonly: bool) {
1482 self.0.set_readonly(readonly)
1487 /// Tests whether this file type represents a directory. The
1488 /// result is mutually exclusive to the results of
1489 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1492 /// [`is_file`]: FileType::is_file
1493 /// [`is_symlink`]: FileType::is_symlink
1498 /// fn main() -> std::io::Result<()> {
1501 /// let metadata = fs::metadata("foo.txt")?;
1502 /// let file_type = metadata.file_type();
1504 /// assert_eq!(file_type.is_dir(), false);
1509 #[stable(feature = "file_type", since = "1.1.0")]
1510 pub fn is_dir(&self) -> bool {
1514 /// Tests whether this file type represents a regular file.
1515 /// The result is mutually exclusive to the results of
1516 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1519 /// When the goal is simply to read from (or write to) the source, the most
1520 /// reliable way to test the source can be read (or written to) is to open
1521 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1522 /// a Unix-like system for example. See [`File::open`] or
1523 /// [`OpenOptions::open`] for more information.
1525 /// [`is_dir`]: FileType::is_dir
1526 /// [`is_symlink`]: FileType::is_symlink
1531 /// fn main() -> std::io::Result<()> {
1534 /// let metadata = fs::metadata("foo.txt")?;
1535 /// let file_type = metadata.file_type();
1537 /// assert_eq!(file_type.is_file(), true);
1542 #[stable(feature = "file_type", since = "1.1.0")]
1543 pub fn is_file(&self) -> bool {
1547 /// Tests whether this file type represents a symbolic link.
1548 /// The result is mutually exclusive to the results of
1549 /// [`is_dir`] and [`is_file`]; only zero or one of these
1552 /// The underlying [`Metadata`] struct needs to be retrieved
1553 /// with the [`fs::symlink_metadata`] function and not the
1554 /// [`fs::metadata`] function. The [`fs::metadata`] function
1555 /// follows symbolic links, so [`is_symlink`] would always
1556 /// return `false` for the target file.
1558 /// [`fs::metadata`]: metadata
1559 /// [`fs::symlink_metadata`]: symlink_metadata
1560 /// [`is_dir`]: FileType::is_dir
1561 /// [`is_file`]: FileType::is_file
1562 /// [`is_symlink`]: FileType::is_symlink
1569 /// fn main() -> std::io::Result<()> {
1570 /// let metadata = fs::symlink_metadata("foo.txt")?;
1571 /// let file_type = metadata.file_type();
1573 /// assert_eq!(file_type.is_symlink(), false);
1578 #[stable(feature = "file_type", since = "1.1.0")]
1579 pub fn is_symlink(&self) -> bool {
1584 impl AsInner<fs_imp::FileType> for FileType {
1585 fn as_inner(&self) -> &fs_imp::FileType {
1590 impl FromInner<fs_imp::FilePermissions> for Permissions {
1591 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1596 impl AsInner<fs_imp::FilePermissions> for Permissions {
1597 fn as_inner(&self) -> &fs_imp::FilePermissions {
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 impl Iterator for ReadDir {
1604 type Item = io::Result<DirEntry>;
1606 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1607 self.0.next().map(|entry| entry.map(DirEntry))
1612 /// Returns the full path to the file that this entry represents.
1614 /// The full path is created by joining the original path to `read_dir`
1615 /// with the filename of this entry.
1622 /// fn main() -> std::io::Result<()> {
1623 /// for entry in fs::read_dir(".")? {
1624 /// let dir = entry?;
1625 /// println!("{:?}", dir.path());
1631 /// This prints output like:
1634 /// "./whatever.txt"
1636 /// "./hello_world.rs"
1639 /// The exact text, of course, depends on what files you have in `.`.
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub fn path(&self) -> PathBuf {
1646 /// Returns the metadata for the file that this entry points at.
1648 /// This function will not traverse symlinks if this entry points at a
1649 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1651 /// [`fs::metadata`]: metadata
1652 /// [`fs::File::metadata`]: File::metadata
1654 /// # Platform-specific behavior
1656 /// On Windows this function is cheap to call (no extra system calls
1657 /// needed), but on Unix platforms this function is the equivalent of
1658 /// calling `symlink_metadata` on the path.
1665 /// if let Ok(entries) = fs::read_dir(".") {
1666 /// for entry in entries {
1667 /// if let Ok(entry) = entry {
1668 /// // Here, `entry` is a `DirEntry`.
1669 /// if let Ok(metadata) = entry.metadata() {
1670 /// // Now let's show our entry's permissions!
1671 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1673 /// println!("Couldn't get metadata for {:?}", entry.path());
1679 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1680 pub fn metadata(&self) -> io::Result<Metadata> {
1681 self.0.metadata().map(Metadata)
1684 /// Returns the file type for the file that this entry points at.
1686 /// This function will not traverse symlinks if this entry points at a
1689 /// # Platform-specific behavior
1691 /// On Windows and most Unix platforms this function is free (no extra
1692 /// system calls needed), but some Unix platforms may require the equivalent
1693 /// call to `symlink_metadata` to learn about the target file type.
1700 /// if let Ok(entries) = fs::read_dir(".") {
1701 /// for entry in entries {
1702 /// if let Ok(entry) = entry {
1703 /// // Here, `entry` is a `DirEntry`.
1704 /// if let Ok(file_type) = entry.file_type() {
1705 /// // Now let's show our entry's file type!
1706 /// println!("{:?}: {:?}", entry.path(), file_type);
1708 /// println!("Couldn't get file type for {:?}", entry.path());
1714 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1715 pub fn file_type(&self) -> io::Result<FileType> {
1716 self.0.file_type().map(FileType)
1719 /// Returns the bare file name of this directory entry without any other
1720 /// leading path component.
1727 /// if let Ok(entries) = fs::read_dir(".") {
1728 /// for entry in entries {
1729 /// if let Ok(entry) = entry {
1730 /// // Here, `entry` is a `DirEntry`.
1731 /// println!("{:?}", entry.file_name());
1737 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1738 pub fn file_name(&self) -> OsString {
1743 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1744 impl fmt::Debug for DirEntry {
1745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 f.debug_tuple("DirEntry").field(&self.path()).finish()
1750 impl AsInner<fs_imp::DirEntry> for DirEntry {
1751 fn as_inner(&self) -> &fs_imp::DirEntry {
1756 /// Removes a file from the filesystem.
1758 /// Note that there is no
1759 /// guarantee that the file is immediately deleted (e.g., depending on
1760 /// platform, other open file descriptors may prevent immediate removal).
1762 /// # Platform-specific behavior
1764 /// This function currently corresponds to the `unlink` function on Unix
1765 /// and the `DeleteFile` function on Windows.
1766 /// Note that, this [may change in the future][changes].
1768 /// [changes]: io#platform-specific-behavior
1772 /// This function will return an error in the following situations, but is not
1773 /// limited to just these cases:
1775 /// * `path` points to a directory.
1776 /// * The file doesn't exist.
1777 /// * The user lacks permissions to remove the file.
1784 /// fn main() -> std::io::Result<()> {
1785 /// fs::remove_file("a.txt")?;
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1791 fs_imp::unlink(path.as_ref())
1794 /// Given a path, query the file system to get information about a file,
1797 /// This function will traverse symbolic links to query information about the
1798 /// destination file.
1800 /// # Platform-specific behavior
1802 /// This function currently corresponds to the `stat` function on Unix
1803 /// and the `GetFileInformationByHandle` function on Windows.
1804 /// Note that, this [may change in the future][changes].
1806 /// [changes]: io#platform-specific-behavior
1810 /// This function will return an error in the following situations, but is not
1811 /// limited to just these cases:
1813 /// * The user lacks permissions to perform `metadata` call on `path`.
1814 /// * `path` does not exist.
1821 /// fn main() -> std::io::Result<()> {
1822 /// let attr = fs::metadata("/some/file/path.txt")?;
1823 /// // inspect attr ...
1827 #[stable(feature = "rust1", since = "1.0.0")]
1828 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1829 fs_imp::stat(path.as_ref()).map(Metadata)
1832 /// Query the metadata about a file without following symlinks.
1834 /// # Platform-specific behavior
1836 /// This function currently corresponds to the `lstat` function on Unix
1837 /// and the `GetFileInformationByHandle` function on Windows.
1838 /// Note that, this [may change in the future][changes].
1840 /// [changes]: io#platform-specific-behavior
1844 /// This function will return an error in the following situations, but is not
1845 /// limited to just these cases:
1847 /// * The user lacks permissions to perform `metadata` call on `path`.
1848 /// * `path` does not exist.
1855 /// fn main() -> std::io::Result<()> {
1856 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1857 /// // inspect attr ...
1861 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1862 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1863 fs_imp::lstat(path.as_ref()).map(Metadata)
1866 /// Rename a file or directory to a new name, replacing the original file if
1867 /// `to` already exists.
1869 /// This will not work if the new name is on a different mount point.
1871 /// # Platform-specific behavior
1873 /// This function currently corresponds to the `rename` function on Unix
1874 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1876 /// Because of this, the behavior when both `from` and `to` exist differs. On
1877 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1878 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1879 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1881 /// Note that, this [may change in the future][changes].
1883 /// [changes]: io#platform-specific-behavior
1887 /// This function will return an error in the following situations, but is not
1888 /// limited to just these cases:
1890 /// * `from` does not exist.
1891 /// * The user lacks permissions to view contents.
1892 /// * `from` and `to` are on separate filesystems.
1899 /// fn main() -> std::io::Result<()> {
1900 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1906 fs_imp::rename(from.as_ref(), to.as_ref())
1909 /// Copies the contents of one file to another. This function will also
1910 /// copy the permission bits of the original file to the destination file.
1912 /// This function will **overwrite** the contents of `to`.
1914 /// Note that if `from` and `to` both point to the same file, then the file
1915 /// will likely get truncated by this operation.
1917 /// On success, the total number of bytes copied is returned and it is equal to
1918 /// the length of the `to` file as reported by `metadata`.
1920 /// If you’re wanting to copy the contents of one file to another and you’re
1921 /// working with [`File`]s, see the [`io::copy()`] function.
1923 /// # Platform-specific behavior
1925 /// This function currently corresponds to the `open` function in Unix
1926 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1927 /// `O_CLOEXEC` is set for returned file descriptors.
1929 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1930 /// and falls back to reading and writing if that is not possible.
1932 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1933 /// NTFS streams are copied but only the size of the main stream is returned by
1936 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1938 /// Note that platform-specific behavior [may change in the future][changes].
1940 /// [changes]: io#platform-specific-behavior
1944 /// This function will return an error in the following situations, but is not
1945 /// limited to just these cases:
1947 /// * `from` is neither a regular file nor a symlink to a regular file.
1948 /// * `from` does not exist.
1949 /// * The current process does not have the permission rights to read
1950 /// `from` or write `to`.
1957 /// fn main() -> std::io::Result<()> {
1958 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1964 fs_imp::copy(from.as_ref(), to.as_ref())
1967 /// Creates a new hard link on the filesystem.
1969 /// The `link` path will be a link pointing to the `original` path. Note that
1970 /// systems often require these two paths to both be located on the same
1973 /// If `original` names a symbolic link, it is platform-specific whether the
1974 /// symbolic link is followed. On platforms where it's possible to not follow
1975 /// it, it is not followed, and the created hard link points to the symbolic
1978 /// # Platform-specific behavior
1980 /// This function currently corresponds the `CreateHardLink` function on Windows.
1981 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1982 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1983 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1984 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1985 /// Note that, this [may change in the future][changes].
1987 /// [changes]: io#platform-specific-behavior
1991 /// This function will return an error in the following situations, but is not
1992 /// limited to just these cases:
1994 /// * The `original` path is not a file or doesn't exist.
2001 /// fn main() -> std::io::Result<()> {
2002 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2008 fs_imp::link(original.as_ref(), link.as_ref())
2011 /// Creates a new symbolic link on the filesystem.
2013 /// The `link` path will be a symbolic link pointing to the `original` path.
2014 /// On Windows, this will be a file symlink, not a directory symlink;
2015 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2016 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2017 /// used instead to make the intent explicit.
2019 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2020 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2021 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2028 /// fn main() -> std::io::Result<()> {
2029 /// fs::soft_link("a.txt", "b.txt")?;
2033 #[stable(feature = "rust1", since = "1.0.0")]
2036 note = "replaced with std::os::unix::fs::symlink and \
2037 std::os::windows::fs::{symlink_file, symlink_dir}"
2039 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2040 fs_imp::symlink(original.as_ref(), link.as_ref())
2043 /// Reads a symbolic link, returning the file that the link points to.
2045 /// # Platform-specific behavior
2047 /// This function currently corresponds to the `readlink` function on Unix
2048 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2049 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2050 /// Note that, this [may change in the future][changes].
2052 /// [changes]: io#platform-specific-behavior
2056 /// This function will return an error in the following situations, but is not
2057 /// limited to just these cases:
2059 /// * `path` is not a symbolic link.
2060 /// * `path` does not exist.
2067 /// fn main() -> std::io::Result<()> {
2068 /// let path = fs::read_link("a.txt")?;
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2074 fs_imp::readlink(path.as_ref())
2077 /// Returns the canonical, absolute form of a path with all intermediate
2078 /// components normalized and symbolic links resolved.
2080 /// # Platform-specific behavior
2082 /// This function currently corresponds to the `realpath` function on Unix
2083 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2084 /// Note that, this [may change in the future][changes].
2086 /// On Windows, this converts the path to use [extended length path][path]
2087 /// syntax, which allows your program to use longer path names, but means you
2088 /// can only join backslash-delimited paths to it, and it may be incompatible
2089 /// with other applications (if passed to the application on the command-line,
2090 /// or written to a file another application may read).
2092 /// [changes]: io#platform-specific-behavior
2093 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2097 /// This function will return an error in the following situations, but is not
2098 /// limited to just these cases:
2100 /// * `path` does not exist.
2101 /// * A non-final component in path is not a directory.
2108 /// fn main() -> std::io::Result<()> {
2109 /// let path = fs::canonicalize("../a/../foo.txt")?;
2113 #[doc(alias = "realpath")]
2114 #[doc(alias = "GetFinalPathNameByHandle")]
2115 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
2116 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2117 fs_imp::canonicalize(path.as_ref())
2120 /// Creates a new, empty directory at the provided path
2122 /// # Platform-specific behavior
2124 /// This function currently corresponds to the `mkdir` function on Unix
2125 /// and the `CreateDirectory` function on Windows.
2126 /// Note that, this [may change in the future][changes].
2128 /// [changes]: io#platform-specific-behavior
2130 /// **NOTE**: If a parent of the given path doesn't exist, this function will
2131 /// return an error. To create a directory and all its missing parents at the
2132 /// same time, use the [`create_dir_all`] function.
2136 /// This function will return an error in the following situations, but is not
2137 /// limited to just these cases:
2139 /// * User lacks permissions to create directory at `path`.
2140 /// * A parent of the given path doesn't exist. (To create a directory and all
2141 /// its missing parents at the same time, use the [`create_dir_all`]
2143 /// * `path` already exists.
2150 /// fn main() -> std::io::Result<()> {
2151 /// fs::create_dir("/some/dir")?;
2155 #[doc(alias = "mkdir")]
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2158 DirBuilder::new().create(path.as_ref())
2161 /// Recursively create a directory and all of its parent components if they
2164 /// # Platform-specific behavior
2166 /// This function currently corresponds to the `mkdir` function on Unix
2167 /// and the `CreateDirectory` function on Windows.
2168 /// Note that, this [may change in the future][changes].
2170 /// [changes]: io#platform-specific-behavior
2174 /// This function will return an error in the following situations, but is not
2175 /// limited to just these cases:
2177 /// * If any directory in the path specified by `path`
2178 /// does not already exist and it could not be created otherwise. The specific
2179 /// error conditions for when a directory is being created (after it is
2180 /// determined to not exist) are outlined by [`fs::create_dir`].
2182 /// Notable exception is made for situations where any of the directories
2183 /// specified in the `path` could not be created as it was being created concurrently.
2184 /// Such cases are considered to be successful. That is, calling `create_dir_all`
2185 /// concurrently from multiple threads or processes is guaranteed not to fail
2186 /// due to a race condition with itself.
2188 /// [`fs::create_dir`]: create_dir
2195 /// fn main() -> std::io::Result<()> {
2196 /// fs::create_dir_all("/some/dir")?;
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2202 DirBuilder::new().recursive(true).create(path.as_ref())
2205 /// Removes an empty directory.
2207 /// # Platform-specific behavior
2209 /// This function currently corresponds to the `rmdir` function on Unix
2210 /// and the `RemoveDirectory` function on Windows.
2211 /// Note that, this [may change in the future][changes].
2213 /// [changes]: io#platform-specific-behavior
2217 /// This function will return an error in the following situations, but is not
2218 /// limited to just these cases:
2220 /// * `path` doesn't exist.
2221 /// * `path` isn't a directory.
2222 /// * The user lacks permissions to remove the directory at the provided `path`.
2223 /// * The directory isn't empty.
2230 /// fn main() -> std::io::Result<()> {
2231 /// fs::remove_dir("/some/dir")?;
2235 #[doc(alias = "rmdir")]
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2238 fs_imp::rmdir(path.as_ref())
2241 /// Removes a directory at this path, after removing all its contents. Use
2244 /// This function does **not** follow symbolic links and it will simply remove the
2245 /// symbolic link itself.
2247 /// # Platform-specific behavior
2249 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2250 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2251 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2252 /// Windows. Note that, this [may change in the future][changes].
2254 /// [changes]: io#platform-specific-behavior
2256 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2257 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2258 /// should not be used in security-sensitive code on those platforms. All other platforms are
2263 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2265 /// [`fs::remove_file`]: remove_file
2266 /// [`fs::remove_dir`]: remove_dir
2273 /// fn main() -> std::io::Result<()> {
2274 /// fs::remove_dir_all("/some/dir")?;
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2280 fs_imp::remove_dir_all(path.as_ref())
2283 /// Returns an iterator over the entries within a directory.
2285 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2286 /// New errors may be encountered after an iterator is initially constructed.
2287 /// Entries for the current and parent directories (typically `.` and `..`) are
2290 /// # Platform-specific behavior
2292 /// This function currently corresponds to the `opendir` function on Unix
2293 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2294 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2295 /// Note that, this [may change in the future][changes].
2297 /// [changes]: io#platform-specific-behavior
2299 /// The order in which this iterator returns entries is platform and filesystem
2304 /// This function will return an error in the following situations, but is not
2305 /// limited to just these cases:
2307 /// * The provided `path` doesn't exist.
2308 /// * The process lacks permissions to view the contents.
2309 /// * The `path` points at a non-directory file.
2315 /// use std::fs::{self, DirEntry};
2316 /// use std::path::Path;
2318 /// // one possible implementation of walking a directory only visiting files
2319 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2320 /// if dir.is_dir() {
2321 /// for entry in fs::read_dir(dir)? {
2322 /// let entry = entry?;
2323 /// let path = entry.path();
2324 /// if path.is_dir() {
2325 /// visit_dirs(&path, cb)?;
2336 /// use std::{fs, io};
2338 /// fn main() -> io::Result<()> {
2339 /// let mut entries = fs::read_dir(".")?
2340 /// .map(|res| res.map(|e| e.path()))
2341 /// .collect::<Result<Vec<_>, io::Error>>()?;
2343 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2344 /// // ordering is required the entries should be explicitly sorted.
2348 /// // The entries have now been sorted by their path.
2353 #[stable(feature = "rust1", since = "1.0.0")]
2354 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2355 fs_imp::readdir(path.as_ref()).map(ReadDir)
2358 /// Changes the permissions found on a file or a directory.
2360 /// # Platform-specific behavior
2362 /// This function currently corresponds to the `chmod` function on Unix
2363 /// and the `SetFileAttributes` function on Windows.
2364 /// Note that, this [may change in the future][changes].
2366 /// [changes]: io#platform-specific-behavior
2370 /// This function will return an error in the following situations, but is not
2371 /// limited to just these cases:
2373 /// * `path` does not exist.
2374 /// * The user lacks the permission to change attributes of the file.
2381 /// fn main() -> std::io::Result<()> {
2382 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2383 /// perms.set_readonly(true);
2384 /// fs::set_permissions("foo.txt", perms)?;
2388 #[stable(feature = "set_permissions", since = "1.1.0")]
2389 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2390 fs_imp::set_perm(path.as_ref(), perm.0)
2394 /// Creates a new set of options with default mode/security settings for all
2395 /// platforms and also non-recursive.
2400 /// use std::fs::DirBuilder;
2402 /// let builder = DirBuilder::new();
2404 #[stable(feature = "dir_builder", since = "1.6.0")]
2406 pub fn new() -> DirBuilder {
2407 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2410 /// Indicates that directories should be created recursively, creating all
2411 /// parent directories. Parents that do not exist are created with the same
2412 /// security and permissions settings.
2414 /// This option defaults to `false`.
2419 /// use std::fs::DirBuilder;
2421 /// let mut builder = DirBuilder::new();
2422 /// builder.recursive(true);
2424 #[stable(feature = "dir_builder", since = "1.6.0")]
2425 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2426 self.recursive = recursive;
2430 /// Creates the specified directory with the options configured in this
2433 /// It is considered an error if the directory already exists unless
2434 /// recursive mode is enabled.
2439 /// use std::fs::{self, DirBuilder};
2441 /// let path = "/tmp/foo/bar/baz";
2442 /// DirBuilder::new()
2443 /// .recursive(true)
2444 /// .create(path).unwrap();
2446 /// assert!(fs::metadata(path).unwrap().is_dir());
2448 #[stable(feature = "dir_builder", since = "1.6.0")]
2449 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2450 self._create(path.as_ref())
2453 fn _create(&self, path: &Path) -> io::Result<()> {
2454 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2457 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2458 if path == Path::new("") {
2462 match self.inner.mkdir(path) {
2463 Ok(()) => return Ok(()),
2464 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2465 Err(_) if path.is_dir() => return Ok(()),
2466 Err(e) => return Err(e),
2468 match path.parent() {
2469 Some(p) => self.create_dir_all(p)?,
2471 return Err(io::const_io_error!(
2472 io::ErrorKind::Uncategorized,
2473 "failed to create whole tree",
2477 match self.inner.mkdir(path) {
2479 Err(_) if path.is_dir() => Ok(()),
2485 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2486 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2491 /// Returns `Ok(true)` if the path points at an existing entity.
2493 /// This function will traverse symbolic links to query information about the
2494 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2496 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2497 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2498 /// denied on some of the parent directories.)
2500 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2501 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2502 /// where those bugs are not an issue.
2507 /// #![feature(fs_try_exists)]
2510 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2511 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2514 /// [`Path::exists`]: crate::path::Path::exists
2515 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2517 #[unstable(feature = "fs_try_exists", issue = "83186")]
2519 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2520 fs_imp::try_exists(path.as_ref())