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 mut bytes = Vec::new();
253 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
254 bytes.reserve(size as usize);
255 io::default_read_to_end(&mut file, &mut bytes)?;
261 /// Read the entire contents of a file into a string.
263 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
264 /// with fewer imports and without an intermediate variable.
266 /// [`read_to_string`]: Read::read_to_string
270 /// This function will return an error if `path` does not already exist.
271 /// Other errors may also be returned according to [`OpenOptions::open`].
273 /// It will also return an error if it encounters while reading an error
274 /// of a kind other than [`io::ErrorKind::Interrupted`],
275 /// or if the contents of the file are not valid UTF-8.
281 /// use std::net::SocketAddr;
282 /// use std::error::Error;
284 /// fn main() -> Result<(), Box<dyn Error>> {
285 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
289 #[stable(feature = "fs_read_write", since = "1.26.0")]
290 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
291 fn inner(path: &Path) -> io::Result<String> {
292 let mut file = File::open(path)?;
293 let mut string = String::new();
294 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
295 string.reserve(size as usize);
296 io::default_read_to_string(&mut file, &mut string)?;
302 /// Write a slice as the entire contents of a file.
304 /// This function will create a file if it does not exist,
305 /// and will entirely replace its contents if it does.
307 /// Depending on the platform, this function may fail if the
308 /// full directory path does not exist.
310 /// This is a convenience function for using [`File::create`] and [`write_all`]
311 /// with fewer imports.
313 /// [`write_all`]: Write::write_all
320 /// fn main() -> std::io::Result<()> {
321 /// fs::write("foo.txt", b"Lorem ipsum")?;
322 /// fs::write("bar.txt", "dolor sit")?;
326 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
327 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
328 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
329 File::create(path)?.write_all(contents)
331 inner(path.as_ref(), contents.as_ref())
335 /// Attempts to open a file in read-only mode.
337 /// See the [`OpenOptions::open`] method for more details.
341 /// This function will return an error if `path` does not already exist.
342 /// Other errors may also be returned according to [`OpenOptions::open`].
347 /// use std::fs::File;
349 /// fn main() -> std::io::Result<()> {
350 /// let mut f = File::open("foo.txt")?;
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
356 OpenOptions::new().read(true).open(path.as_ref())
359 /// Opens a file in write-only mode.
361 /// This function will create a file if it does not exist,
362 /// and will truncate it if it does.
364 /// Depending on the platform, this function may fail if the
365 /// full directory path does not exist.
367 /// See the [`OpenOptions::open`] function for more details.
372 /// use std::fs::File;
374 /// fn main() -> std::io::Result<()> {
375 /// let mut f = File::create("foo.txt")?;
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
381 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
384 /// Creates a new file in read-write mode; error if the file exists.
386 /// This function will create a file if it does not exist, or return an error if it does. This
387 /// way, if the call succeeds, the file returned is guaranteed to be new.
389 /// This option is useful because it is atomic. Otherwise between checking whether a file
390 /// exists and creating a new one, the file may have been created by another process (a TOCTOU
391 /// race condition / attack).
393 /// This can also be written using
394 /// `File::options().read(true).write(true).create_new(true).open(...)`.
399 /// #![feature(file_create_new)]
401 /// use std::fs::File;
403 /// fn main() -> std::io::Result<()> {
404 /// let mut f = File::create_new("foo.txt")?;
408 #[unstable(feature = "file_create_new", issue = "105135")]
409 pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
410 OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
413 /// Returns a new OpenOptions object.
415 /// This function returns a new OpenOptions object that you can use to
416 /// open or create a file with specific options if `open()` or `create()`
417 /// are not appropriate.
419 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
420 /// readable code. Instead of
421 /// `OpenOptions::new().append(true).open("example.log")`,
422 /// you can write `File::options().append(true).open("example.log")`. This
423 /// also avoids the need to import `OpenOptions`.
425 /// See the [`OpenOptions::new`] function for more details.
430 /// use std::fs::File;
432 /// fn main() -> std::io::Result<()> {
433 /// let mut f = File::options().append(true).open("example.log")?;
438 #[stable(feature = "with_options", since = "1.58.0")]
439 pub fn options() -> OpenOptions {
443 /// Attempts to sync all OS-internal metadata to disk.
445 /// This function will attempt to ensure that all in-memory data reaches the
446 /// filesystem before returning.
448 /// This can be used to handle errors that would otherwise only be caught
449 /// when the `File` is closed. Dropping a file will ignore errors in
450 /// synchronizing this in-memory data.
455 /// use std::fs::File;
456 /// use std::io::prelude::*;
458 /// fn main() -> std::io::Result<()> {
459 /// let mut f = File::create("foo.txt")?;
460 /// f.write_all(b"Hello, world!")?;
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub fn sync_all(&self) -> io::Result<()> {
471 /// This function is similar to [`sync_all`], except that it might not
472 /// synchronize file metadata to the filesystem.
474 /// This is intended for use cases that must synchronize content, but don't
475 /// need the metadata on disk. The goal of this method is to reduce disk
478 /// Note that some platforms may simply implement this in terms of
481 /// [`sync_all`]: File::sync_all
486 /// use std::fs::File;
487 /// use std::io::prelude::*;
489 /// fn main() -> std::io::Result<()> {
490 /// let mut f = File::create("foo.txt")?;
491 /// f.write_all(b"Hello, world!")?;
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn sync_data(&self) -> io::Result<()> {
499 self.inner.datasync()
502 /// Truncates or extends the underlying file, updating the size of
503 /// this file to become `size`.
505 /// If the `size` is less than the current file's size, then the file will
506 /// be shrunk. If it is greater than the current file's size, then the file
507 /// will be extended to `size` and have all of the intermediate data filled
510 /// The file's cursor isn't changed. In particular, if the cursor was at the
511 /// end and the file is shrunk using this operation, the cursor will now be
516 /// This function will return an error if the file is not opened for writing.
517 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
518 /// will be returned if the desired length would cause an overflow due to
519 /// the implementation specifics.
524 /// use std::fs::File;
526 /// fn main() -> std::io::Result<()> {
527 /// let mut f = File::create("foo.txt")?;
533 /// Note that this method alters the content of the underlying file, even
534 /// though it takes `&self` rather than `&mut self`.
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn set_len(&self, size: u64) -> io::Result<()> {
537 self.inner.truncate(size)
540 /// Queries metadata about the underlying file.
545 /// use std::fs::File;
547 /// fn main() -> std::io::Result<()> {
548 /// let mut f = File::open("foo.txt")?;
549 /// let metadata = f.metadata()?;
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn metadata(&self) -> io::Result<Metadata> {
555 self.inner.file_attr().map(Metadata)
558 /// Creates a new `File` instance that shares the same underlying file handle
559 /// as the existing `File` instance. Reads, writes, and seeks will affect
560 /// both `File` instances simultaneously.
564 /// Creates two handles for a file named `foo.txt`:
567 /// use std::fs::File;
569 /// fn main() -> std::io::Result<()> {
570 /// let mut file = File::open("foo.txt")?;
571 /// let file_copy = file.try_clone()?;
576 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
577 /// two handles, seek one of them, and read the remaining bytes from the
581 /// use std::fs::File;
582 /// use std::io::SeekFrom;
583 /// use std::io::prelude::*;
585 /// fn main() -> std::io::Result<()> {
586 /// let mut file = File::open("foo.txt")?;
587 /// let mut file_copy = file.try_clone()?;
589 /// file.seek(SeekFrom::Start(3))?;
591 /// let mut contents = vec![];
592 /// file_copy.read_to_end(&mut contents)?;
593 /// assert_eq!(contents, b"def\n");
597 #[stable(feature = "file_try_clone", since = "1.9.0")]
598 pub fn try_clone(&self) -> io::Result<File> {
599 Ok(File { inner: self.inner.duplicate()? })
602 /// Changes the permissions on the underlying file.
604 /// # Platform-specific behavior
606 /// This function currently corresponds to the `fchmod` function on Unix and
607 /// the `SetFileInformationByHandle` function on Windows. Note that, this
608 /// [may change in the future][changes].
610 /// [changes]: io#platform-specific-behavior
614 /// This function will return an error if the user lacks permission change
615 /// attributes on the underlying file. It may also return an error in other
616 /// os-specific unspecified cases.
621 /// fn main() -> std::io::Result<()> {
622 /// use std::fs::File;
624 /// let file = File::open("foo.txt")?;
625 /// let mut perms = file.metadata()?.permissions();
626 /// perms.set_readonly(true);
627 /// file.set_permissions(perms)?;
632 /// Note that this method alters the permissions of the underlying file,
633 /// even though it takes `&self` rather than `&mut self`.
634 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
635 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
636 self.inner.set_permissions(perm.0)
639 /// Changes the timestamps of the underlying file.
641 /// # Platform-specific behavior
643 /// This function currently corresponds to the `futimens` function on Unix (falling back to
644 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
645 /// [may change in the future][changes].
647 /// [changes]: io#platform-specific-behavior
651 /// This function will return an error if the user lacks permission to change timestamps on the
652 /// underlying file. It may also return an error in other os-specific unspecified cases.
654 /// This function may return an error if the operating system lacks support to change one or
655 /// more of the timestamps set in the `FileTimes` structure.
660 /// #![feature(file_set_times)]
662 /// fn main() -> std::io::Result<()> {
663 /// use std::fs::{self, File, FileTimes};
665 /// let src = fs::metadata("src")?;
666 /// let dest = File::options().write(true).open("dest")?;
667 /// let times = FileTimes::new()
668 /// .set_accessed(src.accessed()?)
669 /// .set_modified(src.modified()?);
670 /// dest.set_times(times)?;
674 #[unstable(feature = "file_set_times", issue = "98245")]
675 #[doc(alias = "futimens")]
676 #[doc(alias = "futimes")]
677 #[doc(alias = "SetFileTime")]
678 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
679 self.inner.set_times(times.0)
682 /// Changes the modification time of the underlying file.
684 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
685 #[unstable(feature = "file_set_times", issue = "98245")]
687 pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
688 self.set_times(FileTimes::new().set_modified(time))
692 // In addition to the `impl`s here, `File` also has `impl`s for
693 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
694 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
695 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
696 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
698 impl AsInner<fs_imp::File> for File {
699 fn as_inner(&self) -> &fs_imp::File {
703 impl FromInner<fs_imp::File> for File {
704 fn from_inner(f: fs_imp::File) -> File {
708 impl IntoInner<fs_imp::File> for File {
709 fn into_inner(self) -> fs_imp::File {
714 #[stable(feature = "rust1", since = "1.0.0")]
715 impl fmt::Debug for File {
716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721 /// Indicates how much extra capacity is needed to read the rest of the file.
722 fn buffer_capacity_required(mut file: &File) -> usize {
723 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
724 let pos = file.stream_position().unwrap_or(0);
725 // Don't worry about `usize` overflow because reading will fail regardless
727 size.saturating_sub(pos) as usize
730 #[stable(feature = "rust1", since = "1.0.0")]
732 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
736 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
737 self.inner.read_vectored(bufs)
740 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
741 self.inner.read_buf(cursor)
745 fn is_read_vectored(&self) -> bool {
746 self.inner.is_read_vectored()
749 // Reserves space in the buffer based on the file size when available.
750 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
751 buf.reserve(buffer_capacity_required(self));
752 io::default_read_to_end(self, buf)
755 // Reserves space in the buffer based on the file size when available.
756 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
757 buf.reserve(buffer_capacity_required(self));
758 io::default_read_to_string(self, buf)
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl Write for File {
763 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
764 self.inner.write(buf)
767 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
768 self.inner.write_vectored(bufs)
772 fn is_write_vectored(&self) -> bool {
773 self.inner.is_write_vectored()
776 fn flush(&mut self) -> io::Result<()> {
780 #[stable(feature = "rust1", since = "1.0.0")]
782 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl Read for &File {
788 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
792 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
793 self.inner.read_buf(cursor)
796 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
797 self.inner.read_vectored(bufs)
801 fn is_read_vectored(&self) -> bool {
802 self.inner.is_read_vectored()
805 // Reserves space in the buffer based on the file size when available.
806 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
807 buf.reserve(buffer_capacity_required(self));
808 io::default_read_to_end(self, buf)
811 // Reserves space in the buffer based on the file size when available.
812 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
813 buf.reserve(buffer_capacity_required(self));
814 io::default_read_to_string(self, buf)
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl Write for &File {
819 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
820 self.inner.write(buf)
823 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
824 self.inner.write_vectored(bufs)
828 fn is_write_vectored(&self) -> bool {
829 self.inner.is_write_vectored()
832 fn flush(&mut self) -> io::Result<()> {
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl Seek for &File {
838 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
844 /// Creates a blank new set of options ready for configuration.
846 /// All options are initially set to `false`.
851 /// use std::fs::OpenOptions;
853 /// let mut options = OpenOptions::new();
854 /// let file = options.read(true).open("foo.txt");
856 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn new() -> Self {
859 OpenOptions(fs_imp::OpenOptions::new())
862 /// Sets the option for read access.
864 /// This option, when true, will indicate that the file should be
865 /// `read`-able if opened.
870 /// use std::fs::OpenOptions;
872 /// let file = OpenOptions::new().read(true).open("foo.txt");
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn read(&mut self, read: bool) -> &mut Self {
880 /// Sets the option for write access.
882 /// This option, when true, will indicate that the file should be
883 /// `write`-able if opened.
885 /// If the file already exists, any write calls on it will overwrite its
886 /// contents, without truncating it.
891 /// use std::fs::OpenOptions;
893 /// let file = OpenOptions::new().write(true).open("foo.txt");
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn write(&mut self, write: bool) -> &mut Self {
901 /// Sets the option for the append mode.
903 /// This option, when true, means that writes will append to a file instead
904 /// of overwriting previous contents.
905 /// Note that setting `.write(true).append(true)` has the same effect as
906 /// setting only `.append(true)`.
908 /// For most filesystems, the operating system guarantees that all writes are
909 /// atomic: no writes get mangled because another process writes at the same
912 /// One maybe obvious note when using append-mode: make sure that all data
913 /// that belongs together is written to the file in one operation. This
914 /// can be done by concatenating strings before passing them to [`write()`],
915 /// or using a buffered writer (with a buffer of adequate size),
916 /// and calling [`flush()`] when the message is complete.
918 /// If a file is opened with both read and append access, beware that after
919 /// opening, and after every write, the position for reading may be set at the
920 /// end of the file. So, before writing, save the current position (using
921 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
925 /// This function doesn't create the file if it doesn't exist. Use the
926 /// [`OpenOptions::create`] method to do so.
928 /// [`write()`]: Write::write "io::Write::write"
929 /// [`flush()`]: Write::flush "io::Write::flush"
930 /// [seek]: Seek::seek "io::Seek::seek"
931 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
936 /// use std::fs::OpenOptions;
938 /// let file = OpenOptions::new().append(true).open("foo.txt");
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn append(&mut self, append: bool) -> &mut Self {
942 self.0.append(append);
946 /// Sets the option for truncating a previous file.
948 /// If a file is successfully opened with this option set it will truncate
949 /// the file to 0 length if it already exists.
951 /// The file must be opened with write access for truncate to work.
956 /// use std::fs::OpenOptions;
958 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
962 self.0.truncate(truncate);
966 /// Sets the option to create a new file, or open it if it already exists.
968 /// In order for the file to be created, [`OpenOptions::write`] or
969 /// [`OpenOptions::append`] access must be used.
974 /// use std::fs::OpenOptions;
976 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn create(&mut self, create: bool) -> &mut Self {
980 self.0.create(create);
984 /// Sets the option to create a new file, failing if it already exists.
986 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
987 /// way, if the call succeeds, the file returned is guaranteed to be new.
989 /// This option is useful because it is atomic. Otherwise between checking
990 /// whether a file exists and creating a new one, the file may have been
991 /// created by another process (a TOCTOU race condition / attack).
993 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
996 /// The file must be opened with write or append access in order to create
999 /// [`.create()`]: OpenOptions::create
1000 /// [`.truncate()`]: OpenOptions::truncate
1005 /// use std::fs::OpenOptions;
1007 /// let file = OpenOptions::new().write(true)
1008 /// .create_new(true)
1009 /// .open("foo.txt");
1011 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1012 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1013 self.0.create_new(create_new);
1017 /// Opens a file at `path` with the options specified by `self`.
1021 /// This function will return an error under a number of different
1022 /// circumstances. Some of these error conditions are listed here, together
1023 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1024 /// part of the compatibility contract of the function.
1026 /// * [`NotFound`]: The specified file does not exist and neither `create`
1027 /// or `create_new` is set.
1028 /// * [`NotFound`]: One of the directory components of the file path does
1030 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1031 /// access rights for the file.
1032 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1033 /// directory components of the specified path.
1034 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1036 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1037 /// without write access, no access mode set, etc.).
1039 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1040 /// * One of the directory components of the specified file path
1041 /// was not, in fact, a directory.
1042 /// * Filesystem-level errors: full disk, write permission
1043 /// requested on a read-only file system, exceeded disk quota, too many
1044 /// open files, too long filename, too many symbolic links in the
1045 /// specified path (Unix-like systems only), etc.
1050 /// use std::fs::OpenOptions;
1052 /// let file = OpenOptions::new().read(true).open("foo.txt");
1055 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1056 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1057 /// [`NotFound`]: io::ErrorKind::NotFound
1058 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1061 self._open(path.as_ref())
1064 fn _open(&self, path: &Path) -> io::Result<File> {
1065 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1069 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1070 fn as_inner(&self) -> &fs_imp::OpenOptions {
1075 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1076 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1082 /// Returns the file type for this metadata.
1087 /// fn main() -> std::io::Result<()> {
1090 /// let metadata = fs::metadata("foo.txt")?;
1092 /// println!("{:?}", metadata.file_type());
1097 #[stable(feature = "file_type", since = "1.1.0")]
1098 pub fn file_type(&self) -> FileType {
1099 FileType(self.0.file_type())
1102 /// Returns `true` if this metadata is for a directory. The
1103 /// result is mutually exclusive to the result of
1104 /// [`Metadata::is_file`], and will be false for symlink metadata
1105 /// obtained from [`symlink_metadata`].
1110 /// fn main() -> std::io::Result<()> {
1113 /// let metadata = fs::metadata("foo.txt")?;
1115 /// assert!(!metadata.is_dir());
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 pub fn is_dir(&self) -> bool {
1122 self.file_type().is_dir()
1125 /// Returns `true` if this metadata is for a regular file. The
1126 /// result is mutually exclusive to the result of
1127 /// [`Metadata::is_dir`], and will be false for symlink metadata
1128 /// obtained from [`symlink_metadata`].
1130 /// When the goal is simply to read from (or write to) the source, the most
1131 /// reliable way to test the source can be read (or written to) is to open
1132 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1133 /// a Unix-like system for example. See [`File::open`] or
1134 /// [`OpenOptions::open`] for more information.
1141 /// fn main() -> std::io::Result<()> {
1142 /// let metadata = fs::metadata("foo.txt")?;
1144 /// assert!(metadata.is_file());
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub fn is_file(&self) -> bool {
1151 self.file_type().is_file()
1154 /// Returns `true` if this metadata is for a symbolic link.
1158 #[cfg_attr(unix, doc = "```no_run")]
1159 #[cfg_attr(not(unix), doc = "```ignore")]
1161 /// use std::path::Path;
1162 /// use std::os::unix::fs::symlink;
1164 /// fn main() -> std::io::Result<()> {
1165 /// let link_path = Path::new("link");
1166 /// symlink("/origin_does_not_exist/", link_path)?;
1168 /// let metadata = fs::symlink_metadata(link_path)?;
1170 /// assert!(metadata.is_symlink());
1175 #[stable(feature = "is_symlink", since = "1.58.0")]
1176 pub fn is_symlink(&self) -> bool {
1177 self.file_type().is_symlink()
1180 /// Returns the size of the file, in bytes, this metadata is for.
1187 /// fn main() -> std::io::Result<()> {
1188 /// let metadata = fs::metadata("foo.txt")?;
1190 /// assert_eq!(0, metadata.len());
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn len(&self) -> u64 {
1200 /// Returns the permissions of the file this metadata is for.
1207 /// fn main() -> std::io::Result<()> {
1208 /// let metadata = fs::metadata("foo.txt")?;
1210 /// assert!(!metadata.permissions().readonly());
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn permissions(&self) -> Permissions {
1217 Permissions(self.0.perm())
1220 /// Returns the last modification time listed in this metadata.
1222 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1223 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1227 /// This field might not be available on all platforms, and will return an
1228 /// `Err` on platforms where it is not available.
1235 /// fn main() -> std::io::Result<()> {
1236 /// let metadata = fs::metadata("foo.txt")?;
1238 /// if let Ok(time) = metadata.modified() {
1239 /// println!("{time:?}");
1241 /// println!("Not supported on this platform");
1246 #[stable(feature = "fs_time", since = "1.10.0")]
1247 pub fn modified(&self) -> io::Result<SystemTime> {
1248 self.0.modified().map(FromInner::from_inner)
1251 /// Returns the last access time of this metadata.
1253 /// The returned value corresponds to the `atime` field of `stat` on Unix
1254 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1256 /// Note that not all platforms will keep this field update in a file's
1257 /// metadata, for example Windows has an option to disable updating this
1258 /// time when files are accessed and Linux similarly has `noatime`.
1262 /// This field might not be available on all platforms, and will return an
1263 /// `Err` on platforms where it is not available.
1270 /// fn main() -> std::io::Result<()> {
1271 /// let metadata = fs::metadata("foo.txt")?;
1273 /// if let Ok(time) = metadata.accessed() {
1274 /// println!("{time:?}");
1276 /// println!("Not supported on this platform");
1281 #[stable(feature = "fs_time", since = "1.10.0")]
1282 pub fn accessed(&self) -> io::Result<SystemTime> {
1283 self.0.accessed().map(FromInner::from_inner)
1286 /// Returns the creation time listed in this metadata.
1288 /// The returned value corresponds to the `btime` field of `statx` on
1289 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1290 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1294 /// This field might not be available on all platforms, and will return an
1295 /// `Err` on platforms or filesystems where it is not available.
1302 /// fn main() -> std::io::Result<()> {
1303 /// let metadata = fs::metadata("foo.txt")?;
1305 /// if let Ok(time) = metadata.created() {
1306 /// println!("{time:?}");
1308 /// println!("Not supported on this platform or filesystem");
1313 #[stable(feature = "fs_time", since = "1.10.0")]
1314 pub fn created(&self) -> io::Result<SystemTime> {
1315 self.0.created().map(FromInner::from_inner)
1319 #[stable(feature = "std_debug", since = "1.16.0")]
1320 impl fmt::Debug for Metadata {
1321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1322 f.debug_struct("Metadata")
1323 .field("file_type", &self.file_type())
1324 .field("is_dir", &self.is_dir())
1325 .field("is_file", &self.is_file())
1326 .field("permissions", &self.permissions())
1327 .field("modified", &self.modified())
1328 .field("accessed", &self.accessed())
1329 .field("created", &self.created())
1330 .finish_non_exhaustive()
1334 impl AsInner<fs_imp::FileAttr> for Metadata {
1335 fn as_inner(&self) -> &fs_imp::FileAttr {
1340 impl FromInner<fs_imp::FileAttr> for Metadata {
1341 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1347 /// Create a new `FileTimes` with no times set.
1349 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
1350 #[unstable(feature = "file_set_times", issue = "98245")]
1351 pub fn new() -> Self {
1355 /// Set the last access time of a file.
1356 #[unstable(feature = "file_set_times", issue = "98245")]
1357 pub fn set_accessed(mut self, t: SystemTime) -> Self {
1358 self.0.set_accessed(t.into_inner());
1362 /// Set the last modified time of a file.
1363 #[unstable(feature = "file_set_times", issue = "98245")]
1364 pub fn set_modified(mut self, t: SystemTime) -> Self {
1365 self.0.set_modified(t.into_inner());
1371 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1375 /// This function does not take Access Control Lists (ACLs) or Unix group
1376 /// membership into account.
1380 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1381 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1382 /// but the user may still have permission to change this flag. If
1383 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
1384 /// to lack of write permission.
1385 /// The behavior of this attribute for directories depends on the Windows
1388 /// # Unix (including macOS)
1390 /// On Unix-based platforms this checks if *any* of the owner, group or others
1391 /// write permission bits are set. It does not check if the current
1392 /// user is in the file's assigned group. It also does not check ACLs.
1393 /// Therefore even if this returns true you may not be able to write to the
1394 /// file, and vice versa. The [`PermissionsExt`] trait gives direct access
1395 /// to the permission bits but also does not read ACLs. If you need to
1396 /// accurately know whether or not a file is writable use the `access()`
1397 /// function from libc.
1399 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1404 /// use std::fs::File;
1406 /// fn main() -> std::io::Result<()> {
1407 /// let mut f = File::create("foo.txt")?;
1408 /// let metadata = f.metadata()?;
1410 /// assert_eq!(false, metadata.permissions().readonly());
1414 #[must_use = "call `set_readonly` to modify the readonly flag"]
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 pub fn readonly(&self) -> bool {
1420 /// Modifies the readonly flag for this set of permissions. If the
1421 /// `readonly` argument is `true`, using the resulting `Permission` will
1422 /// update file permissions to forbid writing. Conversely, if it's `false`,
1423 /// using the resulting `Permission` will update file permissions to allow
1426 /// This operation does **not** modify the files attributes. This only
1427 /// changes the in-memory value of these attributes for this `Permissions`
1428 /// instance. To modify the files attributes use the [`set_permissions`]
1429 /// function which commits these attribute changes to the file.
1433 /// `set_readonly(false)` makes the file *world-writable* on Unix.
1434 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
1436 /// It also does not take Access Control Lists (ACLs) or Unix group
1437 /// membership into account.
1441 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1442 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1443 /// but the user may still have permission to change this flag. If
1444 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
1445 /// the user does not have permission to write to the file.
1447 /// In Windows 7 and earlier this attribute prevents deleting empty
1448 /// directories. It does not prevent modifying the directory contents.
1449 /// On later versions of Windows this attribute is ignored for directories.
1451 /// # Unix (including macOS)
1453 /// On Unix-based platforms this sets or clears the write access bit for
1454 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
1455 /// or `chmod a-w <file>` respectively. The latter will grant write access
1456 /// to all users! You can use the [`PermissionsExt`] trait on Unix
1457 /// to avoid this issue.
1459 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1464 /// use std::fs::File;
1466 /// fn main() -> std::io::Result<()> {
1467 /// let f = File::create("foo.txt")?;
1468 /// let metadata = f.metadata()?;
1469 /// let mut permissions = metadata.permissions();
1471 /// permissions.set_readonly(true);
1473 /// // filesystem doesn't change, only the in memory state of the
1474 /// // readonly permission
1475 /// assert_eq!(false, metadata.permissions().readonly());
1477 /// // just this particular `permissions`.
1478 /// assert_eq!(true, permissions.readonly());
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub fn set_readonly(&mut self, readonly: bool) {
1484 self.0.set_readonly(readonly)
1489 /// Tests whether this file type represents a directory. The
1490 /// result is mutually exclusive to the results of
1491 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1494 /// [`is_file`]: FileType::is_file
1495 /// [`is_symlink`]: FileType::is_symlink
1500 /// fn main() -> std::io::Result<()> {
1503 /// let metadata = fs::metadata("foo.txt")?;
1504 /// let file_type = metadata.file_type();
1506 /// assert_eq!(file_type.is_dir(), false);
1511 #[stable(feature = "file_type", since = "1.1.0")]
1512 pub fn is_dir(&self) -> bool {
1516 /// Tests whether this file type represents a regular file.
1517 /// The result is mutually exclusive to the results of
1518 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1521 /// When the goal is simply to read from (or write to) the source, the most
1522 /// reliable way to test the source can be read (or written to) is to open
1523 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1524 /// a Unix-like system for example. See [`File::open`] or
1525 /// [`OpenOptions::open`] for more information.
1527 /// [`is_dir`]: FileType::is_dir
1528 /// [`is_symlink`]: FileType::is_symlink
1533 /// fn main() -> std::io::Result<()> {
1536 /// let metadata = fs::metadata("foo.txt")?;
1537 /// let file_type = metadata.file_type();
1539 /// assert_eq!(file_type.is_file(), true);
1544 #[stable(feature = "file_type", since = "1.1.0")]
1545 pub fn is_file(&self) -> bool {
1549 /// Tests whether this file type represents a symbolic link.
1550 /// The result is mutually exclusive to the results of
1551 /// [`is_dir`] and [`is_file`]; only zero or one of these
1554 /// The underlying [`Metadata`] struct needs to be retrieved
1555 /// with the [`fs::symlink_metadata`] function and not the
1556 /// [`fs::metadata`] function. The [`fs::metadata`] function
1557 /// follows symbolic links, so [`is_symlink`] would always
1558 /// return `false` for the target file.
1560 /// [`fs::metadata`]: metadata
1561 /// [`fs::symlink_metadata`]: symlink_metadata
1562 /// [`is_dir`]: FileType::is_dir
1563 /// [`is_file`]: FileType::is_file
1564 /// [`is_symlink`]: FileType::is_symlink
1571 /// fn main() -> std::io::Result<()> {
1572 /// let metadata = fs::symlink_metadata("foo.txt")?;
1573 /// let file_type = metadata.file_type();
1575 /// assert_eq!(file_type.is_symlink(), false);
1580 #[stable(feature = "file_type", since = "1.1.0")]
1581 pub fn is_symlink(&self) -> bool {
1586 impl AsInner<fs_imp::FileType> for FileType {
1587 fn as_inner(&self) -> &fs_imp::FileType {
1592 impl FromInner<fs_imp::FilePermissions> for Permissions {
1593 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1598 impl AsInner<fs_imp::FilePermissions> for Permissions {
1599 fn as_inner(&self) -> &fs_imp::FilePermissions {
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl Iterator for ReadDir {
1606 type Item = io::Result<DirEntry>;
1608 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1609 self.0.next().map(|entry| entry.map(DirEntry))
1614 /// Returns the full path to the file that this entry represents.
1616 /// The full path is created by joining the original path to `read_dir`
1617 /// with the filename of this entry.
1624 /// fn main() -> std::io::Result<()> {
1625 /// for entry in fs::read_dir(".")? {
1626 /// let dir = entry?;
1627 /// println!("{:?}", dir.path());
1633 /// This prints output like:
1636 /// "./whatever.txt"
1638 /// "./hello_world.rs"
1641 /// The exact text, of course, depends on what files you have in `.`.
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 pub fn path(&self) -> PathBuf {
1648 /// Returns the metadata for the file that this entry points at.
1650 /// This function will not traverse symlinks if this entry points at a
1651 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1653 /// [`fs::metadata`]: metadata
1654 /// [`fs::File::metadata`]: File::metadata
1656 /// # Platform-specific behavior
1658 /// On Windows this function is cheap to call (no extra system calls
1659 /// needed), but on Unix platforms this function is the equivalent of
1660 /// calling `symlink_metadata` on the path.
1667 /// if let Ok(entries) = fs::read_dir(".") {
1668 /// for entry in entries {
1669 /// if let Ok(entry) = entry {
1670 /// // Here, `entry` is a `DirEntry`.
1671 /// if let Ok(metadata) = entry.metadata() {
1672 /// // Now let's show our entry's permissions!
1673 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1675 /// println!("Couldn't get metadata for {:?}", entry.path());
1681 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1682 pub fn metadata(&self) -> io::Result<Metadata> {
1683 self.0.metadata().map(Metadata)
1686 /// Returns the file type for the file that this entry points at.
1688 /// This function will not traverse symlinks if this entry points at a
1691 /// # Platform-specific behavior
1693 /// On Windows and most Unix platforms this function is free (no extra
1694 /// system calls needed), but some Unix platforms may require the equivalent
1695 /// call to `symlink_metadata` to learn about the target file type.
1702 /// if let Ok(entries) = fs::read_dir(".") {
1703 /// for entry in entries {
1704 /// if let Ok(entry) = entry {
1705 /// // Here, `entry` is a `DirEntry`.
1706 /// if let Ok(file_type) = entry.file_type() {
1707 /// // Now let's show our entry's file type!
1708 /// println!("{:?}: {:?}", entry.path(), file_type);
1710 /// println!("Couldn't get file type for {:?}", entry.path());
1716 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1717 pub fn file_type(&self) -> io::Result<FileType> {
1718 self.0.file_type().map(FileType)
1721 /// Returns the bare file name of this directory entry without any other
1722 /// leading path component.
1729 /// if let Ok(entries) = fs::read_dir(".") {
1730 /// for entry in entries {
1731 /// if let Ok(entry) = entry {
1732 /// // Here, `entry` is a `DirEntry`.
1733 /// println!("{:?}", entry.file_name());
1739 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1740 pub fn file_name(&self) -> OsString {
1745 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1746 impl fmt::Debug for DirEntry {
1747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1748 f.debug_tuple("DirEntry").field(&self.path()).finish()
1752 impl AsInner<fs_imp::DirEntry> for DirEntry {
1753 fn as_inner(&self) -> &fs_imp::DirEntry {
1758 /// Removes a file from the filesystem.
1760 /// Note that there is no
1761 /// guarantee that the file is immediately deleted (e.g., depending on
1762 /// platform, other open file descriptors may prevent immediate removal).
1764 /// # Platform-specific behavior
1766 /// This function currently corresponds to the `unlink` function on Unix
1767 /// and the `DeleteFile` function on Windows.
1768 /// Note that, this [may change in the future][changes].
1770 /// [changes]: io#platform-specific-behavior
1774 /// This function will return an error in the following situations, but is not
1775 /// limited to just these cases:
1777 /// * `path` points to a directory.
1778 /// * The file doesn't exist.
1779 /// * The user lacks permissions to remove the file.
1786 /// fn main() -> std::io::Result<()> {
1787 /// fs::remove_file("a.txt")?;
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1793 fs_imp::unlink(path.as_ref())
1796 /// Given a path, query the file system to get information about a file,
1799 /// This function will traverse symbolic links to query information about the
1800 /// destination file.
1802 /// # Platform-specific behavior
1804 /// This function currently corresponds to the `stat` function on Unix
1805 /// and the `GetFileInformationByHandle` function on Windows.
1806 /// Note that, this [may change in the future][changes].
1808 /// [changes]: io#platform-specific-behavior
1812 /// This function will return an error in the following situations, but is not
1813 /// limited to just these cases:
1815 /// * The user lacks permissions to perform `metadata` call on `path`.
1816 /// * `path` does not exist.
1823 /// fn main() -> std::io::Result<()> {
1824 /// let attr = fs::metadata("/some/file/path.txt")?;
1825 /// // inspect attr ...
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1831 fs_imp::stat(path.as_ref()).map(Metadata)
1834 /// Query the metadata about a file without following symlinks.
1836 /// # Platform-specific behavior
1838 /// This function currently corresponds to the `lstat` function on Unix
1839 /// and the `GetFileInformationByHandle` function on Windows.
1840 /// Note that, this [may change in the future][changes].
1842 /// [changes]: io#platform-specific-behavior
1846 /// This function will return an error in the following situations, but is not
1847 /// limited to just these cases:
1849 /// * The user lacks permissions to perform `metadata` call on `path`.
1850 /// * `path` does not exist.
1857 /// fn main() -> std::io::Result<()> {
1858 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1859 /// // inspect attr ...
1863 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1864 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1865 fs_imp::lstat(path.as_ref()).map(Metadata)
1868 /// Rename a file or directory to a new name, replacing the original file if
1869 /// `to` already exists.
1871 /// This will not work if the new name is on a different mount point.
1873 /// # Platform-specific behavior
1875 /// This function currently corresponds to the `rename` function on Unix
1876 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1878 /// Because of this, the behavior when both `from` and `to` exist differs. On
1879 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1880 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1881 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1883 /// Note that, this [may change in the future][changes].
1885 /// [changes]: io#platform-specific-behavior
1889 /// This function will return an error in the following situations, but is not
1890 /// limited to just these cases:
1892 /// * `from` does not exist.
1893 /// * The user lacks permissions to view contents.
1894 /// * `from` and `to` are on separate filesystems.
1901 /// fn main() -> std::io::Result<()> {
1902 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1908 fs_imp::rename(from.as_ref(), to.as_ref())
1911 /// Copies the contents of one file to another. This function will also
1912 /// copy the permission bits of the original file to the destination file.
1914 /// This function will **overwrite** the contents of `to`.
1916 /// Note that if `from` and `to` both point to the same file, then the file
1917 /// will likely get truncated by this operation.
1919 /// On success, the total number of bytes copied is returned and it is equal to
1920 /// the length of the `to` file as reported by `metadata`.
1922 /// If you’re wanting to copy the contents of one file to another and you’re
1923 /// working with [`File`]s, see the [`io::copy()`] function.
1925 /// # Platform-specific behavior
1927 /// This function currently corresponds to the `open` function in Unix
1928 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1929 /// `O_CLOEXEC` is set for returned file descriptors.
1931 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1932 /// and falls back to reading and writing if that is not possible.
1934 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1935 /// NTFS streams are copied but only the size of the main stream is returned by
1938 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1940 /// Note that platform-specific behavior [may change in the future][changes].
1942 /// [changes]: io#platform-specific-behavior
1946 /// This function will return an error in the following situations, but is not
1947 /// limited to just these cases:
1949 /// * `from` is neither a regular file nor a symlink to a regular file.
1950 /// * `from` does not exist.
1951 /// * The current process does not have the permission rights to read
1952 /// `from` or write `to`.
1959 /// fn main() -> std::io::Result<()> {
1960 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1966 fs_imp::copy(from.as_ref(), to.as_ref())
1969 /// Creates a new hard link on the filesystem.
1971 /// The `link` path will be a link pointing to the `original` path. Note that
1972 /// systems often require these two paths to both be located on the same
1975 /// If `original` names a symbolic link, it is platform-specific whether the
1976 /// symbolic link is followed. On platforms where it's possible to not follow
1977 /// it, it is not followed, and the created hard link points to the symbolic
1980 /// # Platform-specific behavior
1982 /// This function currently corresponds the `CreateHardLink` function on Windows.
1983 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1984 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1985 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1986 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1987 /// Note that, this [may change in the future][changes].
1989 /// [changes]: io#platform-specific-behavior
1993 /// This function will return an error in the following situations, but is not
1994 /// limited to just these cases:
1996 /// * The `original` path is not a file or doesn't exist.
2003 /// fn main() -> std::io::Result<()> {
2004 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2010 fs_imp::link(original.as_ref(), link.as_ref())
2013 /// Creates a new symbolic link on the filesystem.
2015 /// The `link` path will be a symbolic link pointing to the `original` path.
2016 /// On Windows, this will be a file symlink, not a directory symlink;
2017 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2018 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2019 /// used instead to make the intent explicit.
2021 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2022 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2023 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2030 /// fn main() -> std::io::Result<()> {
2031 /// fs::soft_link("a.txt", "b.txt")?;
2035 #[stable(feature = "rust1", since = "1.0.0")]
2038 note = "replaced with std::os::unix::fs::symlink and \
2039 std::os::windows::fs::{symlink_file, symlink_dir}"
2041 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2042 fs_imp::symlink(original.as_ref(), link.as_ref())
2045 /// Reads a symbolic link, returning the file that the link points to.
2047 /// # Platform-specific behavior
2049 /// This function currently corresponds to the `readlink` function on Unix
2050 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2051 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2052 /// Note that, this [may change in the future][changes].
2054 /// [changes]: io#platform-specific-behavior
2058 /// This function will return an error in the following situations, but is not
2059 /// limited to just these cases:
2061 /// * `path` is not a symbolic link.
2062 /// * `path` does not exist.
2069 /// fn main() -> std::io::Result<()> {
2070 /// let path = fs::read_link("a.txt")?;
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2076 fs_imp::readlink(path.as_ref())
2079 /// Returns the canonical, absolute form of a path with all intermediate
2080 /// components normalized and symbolic links resolved.
2082 /// # Platform-specific behavior
2084 /// This function currently corresponds to the `realpath` function on Unix
2085 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2086 /// Note that, this [may change in the future][changes].
2088 /// On Windows, this converts the path to use [extended length path][path]
2089 /// syntax, which allows your program to use longer path names, but means you
2090 /// can only join backslash-delimited paths to it, and it may be incompatible
2091 /// with other applications (if passed to the application on the command-line,
2092 /// or written to a file another application may read).
2094 /// [changes]: io#platform-specific-behavior
2095 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2099 /// This function will return an error in the following situations, but is not
2100 /// limited to just these cases:
2102 /// * `path` does not exist.
2103 /// * A non-final component in path is not a directory.
2110 /// fn main() -> std::io::Result<()> {
2111 /// let path = fs::canonicalize("../a/../foo.txt")?;
2115 #[doc(alias = "realpath")]
2116 #[doc(alias = "GetFinalPathNameByHandle")]
2117 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
2118 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2119 fs_imp::canonicalize(path.as_ref())
2122 /// Creates a new, empty directory at the provided path
2124 /// # Platform-specific behavior
2126 /// This function currently corresponds to the `mkdir` function on Unix
2127 /// and the `CreateDirectory` function on Windows.
2128 /// Note that, this [may change in the future][changes].
2130 /// [changes]: io#platform-specific-behavior
2132 /// **NOTE**: If a parent of the given path doesn't exist, this function will
2133 /// return an error. To create a directory and all its missing parents at the
2134 /// same time, use the [`create_dir_all`] function.
2138 /// This function will return an error in the following situations, but is not
2139 /// limited to just these cases:
2141 /// * User lacks permissions to create directory at `path`.
2142 /// * A parent of the given path doesn't exist. (To create a directory and all
2143 /// its missing parents at the same time, use the [`create_dir_all`]
2145 /// * `path` already exists.
2152 /// fn main() -> std::io::Result<()> {
2153 /// fs::create_dir("/some/dir")?;
2157 #[doc(alias = "mkdir")]
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2160 DirBuilder::new().create(path.as_ref())
2163 /// Recursively create a directory and all of its parent components if they
2166 /// # Platform-specific behavior
2168 /// This function currently corresponds to the `mkdir` function on Unix
2169 /// and the `CreateDirectory` function on Windows.
2170 /// Note that, this [may change in the future][changes].
2172 /// [changes]: io#platform-specific-behavior
2176 /// This function will return an error in the following situations, but is not
2177 /// limited to just these cases:
2179 /// * If any directory in the path specified by `path`
2180 /// does not already exist and it could not be created otherwise. The specific
2181 /// error conditions for when a directory is being created (after it is
2182 /// determined to not exist) are outlined by [`fs::create_dir`].
2184 /// Notable exception is made for situations where any of the directories
2185 /// specified in the `path` could not be created as it was being created concurrently.
2186 /// Such cases are considered to be successful. That is, calling `create_dir_all`
2187 /// concurrently from multiple threads or processes is guaranteed not to fail
2188 /// due to a race condition with itself.
2190 /// [`fs::create_dir`]: create_dir
2197 /// fn main() -> std::io::Result<()> {
2198 /// fs::create_dir_all("/some/dir")?;
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2204 DirBuilder::new().recursive(true).create(path.as_ref())
2207 /// Removes an empty directory.
2209 /// # Platform-specific behavior
2211 /// This function currently corresponds to the `rmdir` function on Unix
2212 /// and the `RemoveDirectory` function on Windows.
2213 /// Note that, this [may change in the future][changes].
2215 /// [changes]: io#platform-specific-behavior
2219 /// This function will return an error in the following situations, but is not
2220 /// limited to just these cases:
2222 /// * `path` doesn't exist.
2223 /// * `path` isn't a directory.
2224 /// * The user lacks permissions to remove the directory at the provided `path`.
2225 /// * The directory isn't empty.
2232 /// fn main() -> std::io::Result<()> {
2233 /// fs::remove_dir("/some/dir")?;
2237 #[doc(alias = "rmdir")]
2238 #[stable(feature = "rust1", since = "1.0.0")]
2239 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2240 fs_imp::rmdir(path.as_ref())
2243 /// Removes a directory at this path, after removing all its contents. Use
2246 /// This function does **not** follow symbolic links and it will simply remove the
2247 /// symbolic link itself.
2249 /// # Platform-specific behavior
2251 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2252 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2253 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2254 /// Windows. Note that, this [may change in the future][changes].
2256 /// [changes]: io#platform-specific-behavior
2258 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2259 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2260 /// should not be used in security-sensitive code on those platforms. All other platforms are
2265 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2267 /// [`fs::remove_file`]: remove_file
2268 /// [`fs::remove_dir`]: remove_dir
2275 /// fn main() -> std::io::Result<()> {
2276 /// fs::remove_dir_all("/some/dir")?;
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2282 fs_imp::remove_dir_all(path.as_ref())
2285 /// Returns an iterator over the entries within a directory.
2287 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2288 /// New errors may be encountered after an iterator is initially constructed.
2289 /// Entries for the current and parent directories (typically `.` and `..`) are
2292 /// # Platform-specific behavior
2294 /// This function currently corresponds to the `opendir` function on Unix
2295 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2296 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2297 /// Note that, this [may change in the future][changes].
2299 /// [changes]: io#platform-specific-behavior
2301 /// The order in which this iterator returns entries is platform and filesystem
2306 /// This function will return an error in the following situations, but is not
2307 /// limited to just these cases:
2309 /// * The provided `path` doesn't exist.
2310 /// * The process lacks permissions to view the contents.
2311 /// * The `path` points at a non-directory file.
2317 /// use std::fs::{self, DirEntry};
2318 /// use std::path::Path;
2320 /// // one possible implementation of walking a directory only visiting files
2321 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2322 /// if dir.is_dir() {
2323 /// for entry in fs::read_dir(dir)? {
2324 /// let entry = entry?;
2325 /// let path = entry.path();
2326 /// if path.is_dir() {
2327 /// visit_dirs(&path, cb)?;
2338 /// use std::{fs, io};
2340 /// fn main() -> io::Result<()> {
2341 /// let mut entries = fs::read_dir(".")?
2342 /// .map(|res| res.map(|e| e.path()))
2343 /// .collect::<Result<Vec<_>, io::Error>>()?;
2345 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2346 /// // ordering is required the entries should be explicitly sorted.
2350 /// // The entries have now been sorted by their path.
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2357 fs_imp::readdir(path.as_ref()).map(ReadDir)
2360 /// Changes the permissions found on a file or a directory.
2362 /// # Platform-specific behavior
2364 /// This function currently corresponds to the `chmod` function on Unix
2365 /// and the `SetFileAttributes` function on Windows.
2366 /// Note that, this [may change in the future][changes].
2368 /// [changes]: io#platform-specific-behavior
2372 /// This function will return an error in the following situations, but is not
2373 /// limited to just these cases:
2375 /// * `path` does not exist.
2376 /// * The user lacks the permission to change attributes of the file.
2383 /// fn main() -> std::io::Result<()> {
2384 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2385 /// perms.set_readonly(true);
2386 /// fs::set_permissions("foo.txt", perms)?;
2390 #[stable(feature = "set_permissions", since = "1.1.0")]
2391 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2392 fs_imp::set_perm(path.as_ref(), perm.0)
2396 /// Creates a new set of options with default mode/security settings for all
2397 /// platforms and also non-recursive.
2402 /// use std::fs::DirBuilder;
2404 /// let builder = DirBuilder::new();
2406 #[stable(feature = "dir_builder", since = "1.6.0")]
2408 pub fn new() -> DirBuilder {
2409 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2412 /// Indicates that directories should be created recursively, creating all
2413 /// parent directories. Parents that do not exist are created with the same
2414 /// security and permissions settings.
2416 /// This option defaults to `false`.
2421 /// use std::fs::DirBuilder;
2423 /// let mut builder = DirBuilder::new();
2424 /// builder.recursive(true);
2426 #[stable(feature = "dir_builder", since = "1.6.0")]
2427 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2428 self.recursive = recursive;
2432 /// Creates the specified directory with the options configured in this
2435 /// It is considered an error if the directory already exists unless
2436 /// recursive mode is enabled.
2441 /// use std::fs::{self, DirBuilder};
2443 /// let path = "/tmp/foo/bar/baz";
2444 /// DirBuilder::new()
2445 /// .recursive(true)
2446 /// .create(path).unwrap();
2448 /// assert!(fs::metadata(path).unwrap().is_dir());
2450 #[stable(feature = "dir_builder", since = "1.6.0")]
2451 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2452 self._create(path.as_ref())
2455 fn _create(&self, path: &Path) -> io::Result<()> {
2456 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2459 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2460 if path == Path::new("") {
2464 match self.inner.mkdir(path) {
2465 Ok(()) => return Ok(()),
2466 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2467 Err(_) if path.is_dir() => return Ok(()),
2468 Err(e) => return Err(e),
2470 match path.parent() {
2471 Some(p) => self.create_dir_all(p)?,
2473 return Err(io::const_io_error!(
2474 io::ErrorKind::Uncategorized,
2475 "failed to create whole tree",
2479 match self.inner.mkdir(path) {
2481 Err(_) if path.is_dir() => Ok(()),
2487 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2488 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2493 /// Returns `Ok(true)` if the path points at an existing entity.
2495 /// This function will traverse symbolic links to query information about the
2496 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2498 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2499 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2500 /// denied on some of the parent directories.)
2502 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2503 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2504 /// where those bugs are not an issue.
2509 /// #![feature(fs_try_exists)]
2512 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2513 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2516 /// [`Path::exists`]: crate::path::Path::exists
2517 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2519 #[unstable(feature = "fs_try_exists", issue = "83186")]
2521 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2522 fs_imp::try_exists(path.as_ref())