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.
337 /// If you only need to read the entire file contents,
338 /// consider [`std::fs::read()`][self::read] or
339 /// [`std::fs::read_to_string()`][self::read_to_string] instead.
343 /// This function will return an error if `path` does not already exist.
344 /// Other errors may also be returned according to [`OpenOptions::open`].
349 /// use std::fs::File;
350 /// use std::io::Read;
352 /// fn main() -> std::io::Result<()> {
353 /// let mut f = File::open("foo.txt")?;
354 /// let mut data = vec![];
355 /// f.read_to_end(&mut data)?;
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn open
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<File
> {
361 OpenOptions
::new().read(true).open(path
.as_ref())
364 /// Opens a file in write-only mode.
366 /// This function will create a file if it does not exist,
367 /// and will truncate it if it does.
369 /// Depending on the platform, this function may fail if the
370 /// full directory path does not exist.
371 /// See the [`OpenOptions::open`] function for more details.
373 /// See also [`std::fs::write()`][self::write] for a simple function to
374 /// create a file with a given data.
379 /// use std::fs::File;
380 /// use std::io::Write;
382 /// fn main() -> std::io::Result<()> {
383 /// let mut f = File::create("foo.txt")?;
384 /// f.write_all(&1234_u32.to_be_bytes())?;
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn create
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<File
> {
390 OpenOptions
::new().write(true).create(true).truncate(true).open(path
.as_ref())
393 /// Creates a new file in read-write mode; error if the file exists.
395 /// This function will create a file if it does not exist, or return an error if it does. This
396 /// way, if the call succeeds, the file returned is guaranteed to be new.
398 /// This option is useful because it is atomic. Otherwise between checking whether a file
399 /// exists and creating a new one, the file may have been created by another process (a TOCTOU
400 /// race condition / attack).
402 /// This can also be written using
403 /// `File::options().read(true).write(true).create_new(true).open(...)`.
408 /// #![feature(file_create_new)]
410 /// use std::fs::File;
411 /// use std::io::Write;
413 /// fn main() -> std::io::Result<()> {
414 /// let mut f = File::create_new("foo.txt")?;
415 /// f.write_all("Hello, world!".as_bytes())?;
419 #[unstable(feature = "file_create_new", issue = "105135")]
420 pub fn create_new
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<File
> {
421 OpenOptions
::new().read(true).write(true).create_new(true).open(path
.as_ref())
424 /// Returns a new OpenOptions object.
426 /// This function returns a new OpenOptions object that you can use to
427 /// open or create a file with specific options if `open()` or `create()`
428 /// are not appropriate.
430 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
431 /// readable code. Instead of
432 /// `OpenOptions::new().append(true).open("example.log")`,
433 /// you can write `File::options().append(true).open("example.log")`. This
434 /// also avoids the need to import `OpenOptions`.
436 /// See the [`OpenOptions::new`] function for more details.
441 /// use std::fs::File;
442 /// use std::io::Write;
444 /// fn main() -> std::io::Result<()> {
445 /// let mut f = File::options().append(true).open("example.log")?;
446 /// writeln!(&mut f, "new line")?;
451 #[stable(feature = "with_options", since = "1.58.0")]
452 pub fn options() -> OpenOptions
{
456 /// Attempts to sync all OS-internal metadata to disk.
458 /// This function will attempt to ensure that all in-memory data reaches the
459 /// filesystem before returning.
461 /// This can be used to handle errors that would otherwise only be caught
462 /// when the `File` is closed. Dropping a file will ignore errors in
463 /// synchronizing this in-memory data.
468 /// use std::fs::File;
469 /// use std::io::prelude::*;
471 /// fn main() -> std::io::Result<()> {
472 /// let mut f = File::create("foo.txt")?;
473 /// f.write_all(b"Hello, world!")?;
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn sync_all(&self) -> io
::Result
<()> {
484 /// This function is similar to [`sync_all`], except that it might not
485 /// synchronize file metadata to the filesystem.
487 /// This is intended for use cases that must synchronize content, but don't
488 /// need the metadata on disk. The goal of this method is to reduce disk
491 /// Note that some platforms may simply implement this in terms of
494 /// [`sync_all`]: File::sync_all
499 /// use std::fs::File;
500 /// use std::io::prelude::*;
502 /// fn main() -> std::io::Result<()> {
503 /// let mut f = File::create("foo.txt")?;
504 /// f.write_all(b"Hello, world!")?;
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn sync_data(&self) -> io
::Result
<()> {
512 self.inner
.datasync()
515 /// Truncates or extends the underlying file, updating the size of
516 /// this file to become `size`.
518 /// If the `size` is less than the current file's size, then the file will
519 /// be shrunk. If it is greater than the current file's size, then the file
520 /// will be extended to `size` and have all of the intermediate data filled
523 /// The file's cursor isn't changed. In particular, if the cursor was at the
524 /// end and the file is shrunk using this operation, the cursor will now be
529 /// This function will return an error if the file is not opened for writing.
530 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
531 /// will be returned if the desired length would cause an overflow due to
532 /// the implementation specifics.
537 /// use std::fs::File;
539 /// fn main() -> std::io::Result<()> {
540 /// let mut f = File::create("foo.txt")?;
546 /// Note that this method alters the content of the underlying file, even
547 /// though it takes `&self` rather than `&mut self`.
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn set_len(&self, size
: u64) -> io
::Result
<()> {
550 self.inner
.truncate(size
)
553 /// Queries metadata about the underlying file.
558 /// use std::fs::File;
560 /// fn main() -> std::io::Result<()> {
561 /// let mut f = File::open("foo.txt")?;
562 /// let metadata = f.metadata()?;
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn metadata(&self) -> io
::Result
<Metadata
> {
568 self.inner
.file_attr().map(Metadata
)
571 /// Creates a new `File` instance that shares the same underlying file handle
572 /// as the existing `File` instance. Reads, writes, and seeks will affect
573 /// both `File` instances simultaneously.
577 /// Creates two handles for a file named `foo.txt`:
580 /// use std::fs::File;
582 /// fn main() -> std::io::Result<()> {
583 /// let mut file = File::open("foo.txt")?;
584 /// let file_copy = file.try_clone()?;
589 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
590 /// two handles, seek one of them, and read the remaining bytes from the
594 /// use std::fs::File;
595 /// use std::io::SeekFrom;
596 /// use std::io::prelude::*;
598 /// fn main() -> std::io::Result<()> {
599 /// let mut file = File::open("foo.txt")?;
600 /// let mut file_copy = file.try_clone()?;
602 /// file.seek(SeekFrom::Start(3))?;
604 /// let mut contents = vec![];
605 /// file_copy.read_to_end(&mut contents)?;
606 /// assert_eq!(contents, b"def\n");
610 #[stable(feature = "file_try_clone", since = "1.9.0")]
611 pub fn try_clone(&self) -> io
::Result
<File
> {
612 Ok(File { inner: self.inner.duplicate()? }
)
615 /// Changes the permissions on the underlying file.
617 /// # Platform-specific behavior
619 /// This function currently corresponds to the `fchmod` function on Unix and
620 /// the `SetFileInformationByHandle` function on Windows. Note that, this
621 /// [may change in the future][changes].
623 /// [changes]: io#platform-specific-behavior
627 /// This function will return an error if the user lacks permission change
628 /// attributes on the underlying file. It may also return an error in other
629 /// os-specific unspecified cases.
634 /// fn main() -> std::io::Result<()> {
635 /// use std::fs::File;
637 /// let file = File::open("foo.txt")?;
638 /// let mut perms = file.metadata()?.permissions();
639 /// perms.set_readonly(true);
640 /// file.set_permissions(perms)?;
645 /// Note that this method alters the permissions of the underlying file,
646 /// even though it takes `&self` rather than `&mut self`.
647 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
648 pub fn set_permissions(&self, perm
: Permissions
) -> io
::Result
<()> {
649 self.inner
.set_permissions(perm
.0)
652 /// Changes the timestamps of the underlying file.
654 /// # Platform-specific behavior
656 /// This function currently corresponds to the `futimens` function on Unix (falling back to
657 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
658 /// [may change in the future][changes].
660 /// [changes]: io#platform-specific-behavior
664 /// This function will return an error if the user lacks permission to change timestamps on the
665 /// underlying file. It may also return an error in other os-specific unspecified cases.
667 /// This function may return an error if the operating system lacks support to change one or
668 /// more of the timestamps set in the `FileTimes` structure.
673 /// #![feature(file_set_times)]
675 /// fn main() -> std::io::Result<()> {
676 /// use std::fs::{self, File, FileTimes};
678 /// let src = fs::metadata("src")?;
679 /// let dest = File::options().write(true).open("dest")?;
680 /// let times = FileTimes::new()
681 /// .set_accessed(src.accessed()?)
682 /// .set_modified(src.modified()?);
683 /// dest.set_times(times)?;
687 #[unstable(feature = "file_set_times", issue = "98245")]
688 #[doc(alias = "futimens")]
689 #[doc(alias = "futimes")]
690 #[doc(alias = "SetFileTime")]
691 pub fn set_times(&self, times
: FileTimes
) -> io
::Result
<()> {
692 self.inner
.set_times(times
.0)
695 /// Changes the modification time of the underlying file.
697 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
698 #[unstable(feature = "file_set_times", issue = "98245")]
700 pub fn set_modified(&self, time
: SystemTime
) -> io
::Result
<()> {
701 self.set_times(FileTimes
::new().set_modified(time
))
705 // In addition to the `impl`s here, `File` also has `impl`s for
706 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
707 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
708 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
709 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
711 impl AsInner
<fs_imp
::File
> for File
{
712 fn as_inner(&self) -> &fs_imp
::File
{
716 impl FromInner
<fs_imp
::File
> for File
{
717 fn from_inner(f
: fs_imp
::File
) -> File
{
721 impl IntoInner
<fs_imp
::File
> for File
{
722 fn into_inner(self) -> fs_imp
::File
{
727 #[stable(feature = "rust1", since = "1.0.0")]
728 impl fmt
::Debug
for File
{
729 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
734 /// Indicates how much extra capacity is needed to read the rest of the file.
735 fn buffer_capacity_required(mut file
: &File
) -> usize {
736 let size
= file
.metadata().map(|m
| m
.len()).unwrap_or(0);
737 let pos
= file
.stream_position().unwrap_or(0);
738 // Don't worry about `usize` overflow because reading will fail regardless
740 size
.saturating_sub(pos
) as usize
743 #[stable(feature = "rust1", since = "1.0.0")]
745 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
749 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> io
::Result
<usize> {
750 self.inner
.read_vectored(bufs
)
753 fn read_buf(&mut self, cursor
: BorrowedCursor
<'_
>) -> io
::Result
<()> {
754 self.inner
.read_buf(cursor
)
758 fn is_read_vectored(&self) -> bool
{
759 self.inner
.is_read_vectored()
762 // Reserves space in the buffer based on the file size when available.
763 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> io
::Result
<usize> {
764 buf
.reserve(buffer_capacity_required(self));
765 io
::default_read_to_end(self, buf
)
768 // Reserves space in the buffer based on the file size when available.
769 fn read_to_string(&mut self, buf
: &mut String
) -> io
::Result
<usize> {
770 buf
.reserve(buffer_capacity_required(self));
771 io
::default_read_to_string(self, buf
)
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl Write
for File
{
776 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
777 self.inner
.write(buf
)
780 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> io
::Result
<usize> {
781 self.inner
.write_vectored(bufs
)
785 fn is_write_vectored(&self) -> bool
{
786 self.inner
.is_write_vectored()
789 fn flush(&mut self) -> io
::Result
<()> {
793 #[stable(feature = "rust1", since = "1.0.0")]
795 fn seek(&mut self, pos
: SeekFrom
) -> io
::Result
<u64> {
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl Read
for &File
{
801 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
805 fn read_buf(&mut self, cursor
: BorrowedCursor
<'_
>) -> io
::Result
<()> {
806 self.inner
.read_buf(cursor
)
809 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> io
::Result
<usize> {
810 self.inner
.read_vectored(bufs
)
814 fn is_read_vectored(&self) -> bool
{
815 self.inner
.is_read_vectored()
818 // Reserves space in the buffer based on the file size when available.
819 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> io
::Result
<usize> {
820 buf
.reserve(buffer_capacity_required(self));
821 io
::default_read_to_end(self, buf
)
824 // Reserves space in the buffer based on the file size when available.
825 fn read_to_string(&mut self, buf
: &mut String
) -> io
::Result
<usize> {
826 buf
.reserve(buffer_capacity_required(self));
827 io
::default_read_to_string(self, buf
)
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl Write
for &File
{
832 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
833 self.inner
.write(buf
)
836 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> io
::Result
<usize> {
837 self.inner
.write_vectored(bufs
)
841 fn is_write_vectored(&self) -> bool
{
842 self.inner
.is_write_vectored()
845 fn flush(&mut self) -> io
::Result
<()> {
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl Seek
for &File
{
851 fn seek(&mut self, pos
: SeekFrom
) -> io
::Result
<u64> {
857 /// Creates a blank new set of options ready for configuration.
859 /// All options are initially set to `false`.
864 /// use std::fs::OpenOptions;
866 /// let mut options = OpenOptions::new();
867 /// let file = options.read(true).open("foo.txt");
869 #[stable(feature = "rust1", since = "1.0.0")]
871 pub fn new() -> Self {
872 OpenOptions(fs_imp
::OpenOptions
::new())
875 /// Sets the option for read access.
877 /// This option, when true, will indicate that the file should be
878 /// `read`-able if opened.
883 /// use std::fs::OpenOptions;
885 /// let file = OpenOptions::new().read(true).open("foo.txt");
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn read(&mut self, read
: bool
) -> &mut Self {
893 /// Sets the option for write access.
895 /// This option, when true, will indicate that the file should be
896 /// `write`-able if opened.
898 /// If the file already exists, any write calls on it will overwrite its
899 /// contents, without truncating it.
904 /// use std::fs::OpenOptions;
906 /// let file = OpenOptions::new().write(true).open("foo.txt");
908 #[stable(feature = "rust1", since = "1.0.0")]
909 pub fn write(&mut self, write
: bool
) -> &mut Self {
914 /// Sets the option for the append mode.
916 /// This option, when true, means that writes will append to a file instead
917 /// of overwriting previous contents.
918 /// Note that setting `.write(true).append(true)` has the same effect as
919 /// setting only `.append(true)`.
921 /// For most filesystems, the operating system guarantees that all writes are
922 /// atomic: no writes get mangled because another process writes at the same
925 /// One maybe obvious note when using append-mode: make sure that all data
926 /// that belongs together is written to the file in one operation. This
927 /// can be done by concatenating strings before passing them to [`write()`],
928 /// or using a buffered writer (with a buffer of adequate size),
929 /// and calling [`flush()`] when the message is complete.
931 /// If a file is opened with both read and append access, beware that after
932 /// opening, and after every write, the position for reading may be set at the
933 /// end of the file. So, before writing, save the current position (using
934 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
938 /// This function doesn't create the file if it doesn't exist. Use the
939 /// [`OpenOptions::create`] method to do so.
941 /// [`write()`]: Write::write "io::Write::write"
942 /// [`flush()`]: Write::flush "io::Write::flush"
943 /// [seek]: Seek::seek "io::Seek::seek"
944 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
949 /// use std::fs::OpenOptions;
951 /// let file = OpenOptions::new().append(true).open("foo.txt");
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn append(&mut self, append
: bool
) -> &mut Self {
955 self.0.append(append
);
959 /// Sets the option for truncating a previous file.
961 /// If a file is successfully opened with this option set it will truncate
962 /// the file to 0 length if it already exists.
964 /// The file must be opened with write access for truncate to work.
969 /// use std::fs::OpenOptions;
971 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
973 #[stable(feature = "rust1", since = "1.0.0")]
974 pub fn truncate(&mut self, truncate
: bool
) -> &mut Self {
975 self.0.truncate(truncate
);
979 /// Sets the option to create a new file, or open it if it already exists.
981 /// In order for the file to be created, [`OpenOptions::write`] or
982 /// [`OpenOptions::append`] access must be used.
984 /// See also [`std::fs::write()`][self::write] for a simple function to
985 /// create a file with a given data.
990 /// use std::fs::OpenOptions;
992 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn create(&mut self, create
: bool
) -> &mut Self {
996 self.0.create(create
);
1000 /// Sets the option to create a new file, failing if it already exists.
1002 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1003 /// way, if the call succeeds, the file returned is guaranteed to be new.
1005 /// This option is useful because it is atomic. Otherwise between checking
1006 /// whether a file exists and creating a new one, the file may have been
1007 /// created by another process (a TOCTOU race condition / attack).
1009 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1012 /// The file must be opened with write or append access in order to create
1015 /// [`.create()`]: OpenOptions::create
1016 /// [`.truncate()`]: OpenOptions::truncate
1021 /// use std::fs::OpenOptions;
1023 /// let file = OpenOptions::new().write(true)
1024 /// .create_new(true)
1025 /// .open("foo.txt");
1027 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1028 pub fn create_new(&mut self, create_new
: bool
) -> &mut Self {
1029 self.0.create_new(create_new
);
1033 /// Opens a file at `path` with the options specified by `self`.
1037 /// This function will return an error under a number of different
1038 /// circumstances. Some of these error conditions are listed here, together
1039 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1040 /// part of the compatibility contract of the function.
1042 /// * [`NotFound`]: The specified file does not exist and neither `create`
1043 /// or `create_new` is set.
1044 /// * [`NotFound`]: One of the directory components of the file path does
1046 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1047 /// access rights for the file.
1048 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1049 /// directory components of the specified path.
1050 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1052 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1053 /// without write access, no access mode set, etc.).
1055 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1056 /// * One of the directory components of the specified file path
1057 /// was not, in fact, a directory.
1058 /// * Filesystem-level errors: full disk, write permission
1059 /// requested on a read-only file system, exceeded disk quota, too many
1060 /// open files, too long filename, too many symbolic links in the
1061 /// specified path (Unix-like systems only), etc.
1066 /// use std::fs::OpenOptions;
1068 /// let file = OpenOptions::new().read(true).open("foo.txt");
1071 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1072 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1073 /// [`NotFound`]: io::ErrorKind::NotFound
1074 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn open
<P
: AsRef
<Path
>>(&self, path
: P
) -> io
::Result
<File
> {
1077 self._open(path
.as_ref())
1080 fn _open(&self, path
: &Path
) -> io
::Result
<File
> {
1081 fs_imp
::File
::open(path
, &self.0).map(|inner
| File { inner }
)
1085 impl AsInner
<fs_imp
::OpenOptions
> for OpenOptions
{
1086 fn as_inner(&self) -> &fs_imp
::OpenOptions
{
1091 impl AsInnerMut
<fs_imp
::OpenOptions
> for OpenOptions
{
1092 fn as_inner_mut(&mut self) -> &mut fs_imp
::OpenOptions
{
1098 /// Returns the file type for this metadata.
1103 /// fn main() -> std::io::Result<()> {
1106 /// let metadata = fs::metadata("foo.txt")?;
1108 /// println!("{:?}", metadata.file_type());
1113 #[stable(feature = "file_type", since = "1.1.0")]
1114 pub fn file_type(&self) -> FileType
{
1115 FileType(self.0.file_type
())
1118 /// Returns `true` if this metadata is for a directory. The
1119 /// result is mutually exclusive to the result of
1120 /// [`Metadata::is_file`], and will be false for symlink metadata
1121 /// obtained from [`symlink_metadata`].
1126 /// fn main() -> std::io::Result<()> {
1129 /// let metadata = fs::metadata("foo.txt")?;
1131 /// assert!(!metadata.is_dir());
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn is_dir(&self) -> bool
{
1138 self.file_type().is_dir()
1141 /// Returns `true` if this metadata is for a regular file. The
1142 /// result is mutually exclusive to the result of
1143 /// [`Metadata::is_dir`], and will be false for symlink metadata
1144 /// obtained from [`symlink_metadata`].
1146 /// When the goal is simply to read from (or write to) the source, the most
1147 /// reliable way to test the source can be read (or written to) is to open
1148 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1149 /// a Unix-like system for example. See [`File::open`] or
1150 /// [`OpenOptions::open`] for more information.
1157 /// fn main() -> std::io::Result<()> {
1158 /// let metadata = fs::metadata("foo.txt")?;
1160 /// assert!(metadata.is_file());
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub fn is_file(&self) -> bool
{
1167 self.file_type().is_file()
1170 /// Returns `true` if this metadata is for a symbolic link.
1174 #[cfg_attr(unix, doc = "```no_run")]
1175 #[cfg_attr(not(unix), doc = "```ignore")]
1177 /// use std::path::Path;
1178 /// use std::os::unix::fs::symlink;
1180 /// fn main() -> std::io::Result<()> {
1181 /// let link_path = Path::new("link");
1182 /// symlink("/origin_does_not_exist/", link_path)?;
1184 /// let metadata = fs::symlink_metadata(link_path)?;
1186 /// assert!(metadata.is_symlink());
1191 #[stable(feature = "is_symlink", since = "1.58.0")]
1192 pub fn is_symlink(&self) -> bool
{
1193 self.file_type().is_symlink()
1196 /// Returns the size of the file, in bytes, this metadata is for.
1203 /// fn main() -> std::io::Result<()> {
1204 /// let metadata = fs::metadata("foo.txt")?;
1206 /// assert_eq!(0, metadata.len());
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub fn len(&self) -> u64 {
1216 /// Returns the permissions of the file this metadata is for.
1223 /// fn main() -> std::io::Result<()> {
1224 /// let metadata = fs::metadata("foo.txt")?;
1226 /// assert!(!metadata.permissions().readonly());
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn permissions(&self) -> Permissions
{
1233 Permissions(self.0.perm())
1236 /// Returns the last modification time listed in this metadata.
1238 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1239 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1243 /// This field might not be available on all platforms, and will return an
1244 /// `Err` on platforms where it is not available.
1251 /// fn main() -> std::io::Result<()> {
1252 /// let metadata = fs::metadata("foo.txt")?;
1254 /// if let Ok(time) = metadata.modified() {
1255 /// println!("{time:?}");
1257 /// println!("Not supported on this platform");
1262 #[stable(feature = "fs_time", since = "1.10.0")]
1263 pub fn modified(&self) -> io
::Result
<SystemTime
> {
1264 self.0.modified().map(FromInner
::from_inner
)
1267 /// Returns the last access time of this metadata.
1269 /// The returned value corresponds to the `atime` field of `stat` on Unix
1270 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1272 /// Note that not all platforms will keep this field update in a file's
1273 /// metadata, for example Windows has an option to disable updating this
1274 /// time when files are accessed and Linux similarly has `noatime`.
1278 /// This field might not be available on all platforms, and will return an
1279 /// `Err` on platforms where it is not available.
1286 /// fn main() -> std::io::Result<()> {
1287 /// let metadata = fs::metadata("foo.txt")?;
1289 /// if let Ok(time) = metadata.accessed() {
1290 /// println!("{time:?}");
1292 /// println!("Not supported on this platform");
1297 #[stable(feature = "fs_time", since = "1.10.0")]
1298 pub fn accessed(&self) -> io
::Result
<SystemTime
> {
1299 self.0.accessed().map(FromInner
::from_inner
)
1302 /// Returns the creation time listed in this metadata.
1304 /// The returned value corresponds to the `btime` field of `statx` on
1305 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1306 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1310 /// This field might not be available on all platforms, and will return an
1311 /// `Err` on platforms or filesystems where it is not available.
1318 /// fn main() -> std::io::Result<()> {
1319 /// let metadata = fs::metadata("foo.txt")?;
1321 /// if let Ok(time) = metadata.created() {
1322 /// println!("{time:?}");
1324 /// println!("Not supported on this platform or filesystem");
1329 #[stable(feature = "fs_time", since = "1.10.0")]
1330 pub fn created(&self) -> io
::Result
<SystemTime
> {
1331 self.0.created().map(FromInner
::from_inner
)
1335 #[stable(feature = "std_debug", since = "1.16.0")]
1336 impl fmt
::Debug
for Metadata
{
1337 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1338 f
.debug_struct("Metadata")
1339 .field("file_type", &self.file_type())
1340 .field("is_dir", &self.is_dir())
1341 .field("is_file", &self.is_file())
1342 .field("permissions", &self.permissions())
1343 .field("modified", &self.modified())
1344 .field("accessed", &self.accessed())
1345 .field("created", &self.created())
1346 .finish_non_exhaustive()
1350 impl AsInner
<fs_imp
::FileAttr
> for Metadata
{
1351 fn as_inner(&self) -> &fs_imp
::FileAttr
{
1356 impl FromInner
<fs_imp
::FileAttr
> for Metadata
{
1357 fn from_inner(attr
: fs_imp
::FileAttr
) -> Metadata
{
1363 /// Create a new `FileTimes` with no times set.
1365 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
1366 #[unstable(feature = "file_set_times", issue = "98245")]
1367 pub fn new() -> Self {
1371 /// Set the last access time of a file.
1372 #[unstable(feature = "file_set_times", issue = "98245")]
1373 pub fn set_accessed(mut self, t
: SystemTime
) -> Self {
1374 self.0.set_accessed(t
.into_inner());
1378 /// Set the last modified time of a file.
1379 #[unstable(feature = "file_set_times", issue = "98245")]
1380 pub fn set_modified(mut self, t
: SystemTime
) -> Self {
1381 self.0.set_modified(t
.into_inner());
1387 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1391 /// This function does not take Access Control Lists (ACLs) or Unix group
1392 /// membership into account.
1396 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1397 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1398 /// but the user may still have permission to change this flag. If
1399 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
1400 /// to lack of write permission.
1401 /// The behavior of this attribute for directories depends on the Windows
1404 /// # Unix (including macOS)
1406 /// On Unix-based platforms this checks if *any* of the owner, group or others
1407 /// write permission bits are set. It does not check if the current
1408 /// user is in the file's assigned group. It also does not check ACLs.
1409 /// Therefore even if this returns true you may not be able to write to the
1410 /// file, and vice versa. The [`PermissionsExt`] trait gives direct access
1411 /// to the permission bits but also does not read ACLs. If you need to
1412 /// accurately know whether or not a file is writable use the `access()`
1413 /// function from libc.
1415 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1420 /// use std::fs::File;
1422 /// fn main() -> std::io::Result<()> {
1423 /// let mut f = File::create("foo.txt")?;
1424 /// let metadata = f.metadata()?;
1426 /// assert_eq!(false, metadata.permissions().readonly());
1430 #[must_use = "call `set_readonly` to modify the readonly flag"]
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn readonly(&self) -> bool
{
1436 /// Modifies the readonly flag for this set of permissions. If the
1437 /// `readonly` argument is `true`, using the resulting `Permission` will
1438 /// update file permissions to forbid writing. Conversely, if it's `false`,
1439 /// using the resulting `Permission` will update file permissions to allow
1442 /// This operation does **not** modify the files attributes. This only
1443 /// changes the in-memory value of these attributes for this `Permissions`
1444 /// instance. To modify the files attributes use the [`set_permissions`]
1445 /// function which commits these attribute changes to the file.
1449 /// `set_readonly(false)` makes the file *world-writable* on Unix.
1450 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
1452 /// It also does not take Access Control Lists (ACLs) or Unix group
1453 /// membership into account.
1457 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1458 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1459 /// but the user may still have permission to change this flag. If
1460 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
1461 /// the user does not have permission to write to the file.
1463 /// In Windows 7 and earlier this attribute prevents deleting empty
1464 /// directories. It does not prevent modifying the directory contents.
1465 /// On later versions of Windows this attribute is ignored for directories.
1467 /// # Unix (including macOS)
1469 /// On Unix-based platforms this sets or clears the write access bit for
1470 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
1471 /// or `chmod a-w <file>` respectively. The latter will grant write access
1472 /// to all users! You can use the [`PermissionsExt`] trait on Unix
1473 /// to avoid this issue.
1475 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1480 /// use std::fs::File;
1482 /// fn main() -> std::io::Result<()> {
1483 /// let f = File::create("foo.txt")?;
1484 /// let metadata = f.metadata()?;
1485 /// let mut permissions = metadata.permissions();
1487 /// permissions.set_readonly(true);
1489 /// // filesystem doesn't change, only the in memory state of the
1490 /// // readonly permission
1491 /// assert_eq!(false, metadata.permissions().readonly());
1493 /// // just this particular `permissions`.
1494 /// assert_eq!(true, permissions.readonly());
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn set_readonly(&mut self, readonly
: bool
) {
1500 self.0.set_readonly(readonly
)
1505 /// Tests whether this file type represents a directory. The
1506 /// result is mutually exclusive to the results of
1507 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1510 /// [`is_file`]: FileType::is_file
1511 /// [`is_symlink`]: FileType::is_symlink
1516 /// fn main() -> std::io::Result<()> {
1519 /// let metadata = fs::metadata("foo.txt")?;
1520 /// let file_type = metadata.file_type();
1522 /// assert_eq!(file_type.is_dir(), false);
1527 #[stable(feature = "file_type", since = "1.1.0")]
1528 pub fn is_dir(&self) -> bool
{
1532 /// Tests whether this file type represents a regular file.
1533 /// The result is mutually exclusive to the results of
1534 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1537 /// When the goal is simply to read from (or write to) the source, the most
1538 /// reliable way to test the source can be read (or written to) is to open
1539 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1540 /// a Unix-like system for example. See [`File::open`] or
1541 /// [`OpenOptions::open`] for more information.
1543 /// [`is_dir`]: FileType::is_dir
1544 /// [`is_symlink`]: FileType::is_symlink
1549 /// fn main() -> std::io::Result<()> {
1552 /// let metadata = fs::metadata("foo.txt")?;
1553 /// let file_type = metadata.file_type();
1555 /// assert_eq!(file_type.is_file(), true);
1560 #[stable(feature = "file_type", since = "1.1.0")]
1561 pub fn is_file(&self) -> bool
{
1565 /// Tests whether this file type represents a symbolic link.
1566 /// The result is mutually exclusive to the results of
1567 /// [`is_dir`] and [`is_file`]; only zero or one of these
1570 /// The underlying [`Metadata`] struct needs to be retrieved
1571 /// with the [`fs::symlink_metadata`] function and not the
1572 /// [`fs::metadata`] function. The [`fs::metadata`] function
1573 /// follows symbolic links, so [`is_symlink`] would always
1574 /// return `false` for the target file.
1576 /// [`fs::metadata`]: metadata
1577 /// [`fs::symlink_metadata`]: symlink_metadata
1578 /// [`is_dir`]: FileType::is_dir
1579 /// [`is_file`]: FileType::is_file
1580 /// [`is_symlink`]: FileType::is_symlink
1587 /// fn main() -> std::io::Result<()> {
1588 /// let metadata = fs::symlink_metadata("foo.txt")?;
1589 /// let file_type = metadata.file_type();
1591 /// assert_eq!(file_type.is_symlink(), false);
1596 #[stable(feature = "file_type", since = "1.1.0")]
1597 pub fn is_symlink(&self) -> bool
{
1602 impl AsInner
<fs_imp
::FileType
> for FileType
{
1603 fn as_inner(&self) -> &fs_imp
::FileType
{
1608 impl FromInner
<fs_imp
::FilePermissions
> for Permissions
{
1609 fn from_inner(f
: fs_imp
::FilePermissions
) -> Permissions
{
1614 impl AsInner
<fs_imp
::FilePermissions
> for Permissions
{
1615 fn as_inner(&self) -> &fs_imp
::FilePermissions
{
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl Iterator
for ReadDir
{
1622 type Item
= io
::Result
<DirEntry
>;
1624 fn next(&mut self) -> Option
<io
::Result
<DirEntry
>> {
1625 self.0.next().map(|entry
| entry
.map(DirEntry
))
1630 /// Returns the full path to the file that this entry represents.
1632 /// The full path is created by joining the original path to `read_dir`
1633 /// with the filename of this entry.
1640 /// fn main() -> std::io::Result<()> {
1641 /// for entry in fs::read_dir(".")? {
1642 /// let dir = entry?;
1643 /// println!("{:?}", dir.path());
1649 /// This prints output like:
1652 /// "./whatever.txt"
1654 /// "./hello_world.rs"
1657 /// The exact text, of course, depends on what files you have in `.`.
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 pub fn path(&self) -> PathBuf
{
1664 /// Returns the metadata for the file that this entry points at.
1666 /// This function will not traverse symlinks if this entry points at a
1667 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1669 /// [`fs::metadata`]: metadata
1670 /// [`fs::File::metadata`]: File::metadata
1672 /// # Platform-specific behavior
1674 /// On Windows this function is cheap to call (no extra system calls
1675 /// needed), but on Unix platforms this function is the equivalent of
1676 /// calling `symlink_metadata` on the path.
1683 /// if let Ok(entries) = fs::read_dir(".") {
1684 /// for entry in entries {
1685 /// if let Ok(entry) = entry {
1686 /// // Here, `entry` is a `DirEntry`.
1687 /// if let Ok(metadata) = entry.metadata() {
1688 /// // Now let's show our entry's permissions!
1689 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1691 /// println!("Couldn't get metadata for {:?}", entry.path());
1697 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1698 pub fn metadata(&self) -> io
::Result
<Metadata
> {
1699 self.0.metadata().map(Metadata
)
1702 /// Returns the file type for the file that this entry points at.
1704 /// This function will not traverse symlinks if this entry points at a
1707 /// # Platform-specific behavior
1709 /// On Windows and most Unix platforms this function is free (no extra
1710 /// system calls needed), but some Unix platforms may require the equivalent
1711 /// call to `symlink_metadata` to learn about the target file type.
1718 /// if let Ok(entries) = fs::read_dir(".") {
1719 /// for entry in entries {
1720 /// if let Ok(entry) = entry {
1721 /// // Here, `entry` is a `DirEntry`.
1722 /// if let Ok(file_type) = entry.file_type() {
1723 /// // Now let's show our entry's file type!
1724 /// println!("{:?}: {:?}", entry.path(), file_type);
1726 /// println!("Couldn't get file type for {:?}", entry.path());
1732 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1733 pub fn file_type(&self) -> io
::Result
<FileType
> {
1734 self.0.file_type
().map(FileType
)
1737 /// Returns the bare file name of this directory entry without any other
1738 /// leading path component.
1745 /// if let Ok(entries) = fs::read_dir(".") {
1746 /// for entry in entries {
1747 /// if let Ok(entry) = entry {
1748 /// // Here, `entry` is a `DirEntry`.
1749 /// println!("{:?}", entry.file_name());
1755 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1756 pub fn file_name(&self) -> OsString
{
1761 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1762 impl fmt
::Debug
for DirEntry
{
1763 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1764 f
.debug_tuple("DirEntry").field(&self.path()).finish()
1768 impl AsInner
<fs_imp
::DirEntry
> for DirEntry
{
1769 fn as_inner(&self) -> &fs_imp
::DirEntry
{
1774 /// Removes a file from the filesystem.
1776 /// Note that there is no
1777 /// guarantee that the file is immediately deleted (e.g., depending on
1778 /// platform, other open file descriptors may prevent immediate removal).
1780 /// # Platform-specific behavior
1782 /// This function currently corresponds to the `unlink` function on Unix
1783 /// and the `DeleteFile` function on Windows.
1784 /// Note that, this [may change in the future][changes].
1786 /// [changes]: io#platform-specific-behavior
1790 /// This function will return an error in the following situations, but is not
1791 /// limited to just these cases:
1793 /// * `path` points to a directory.
1794 /// * The file doesn't exist.
1795 /// * The user lacks permissions to remove the file.
1802 /// fn main() -> std::io::Result<()> {
1803 /// fs::remove_file("a.txt")?;
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 pub fn remove_file
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<()> {
1809 fs_imp
::unlink(path
.as_ref())
1812 /// Given a path, query the file system to get information about a file,
1815 /// This function will traverse symbolic links to query information about the
1816 /// destination file.
1818 /// # Platform-specific behavior
1820 /// This function currently corresponds to the `stat` function on Unix
1821 /// and the `GetFileInformationByHandle` function on Windows.
1822 /// Note that, this [may change in the future][changes].
1824 /// [changes]: io#platform-specific-behavior
1828 /// This function will return an error in the following situations, but is not
1829 /// limited to just these cases:
1831 /// * The user lacks permissions to perform `metadata` call on `path`.
1832 /// * `path` does not exist.
1839 /// fn main() -> std::io::Result<()> {
1840 /// let attr = fs::metadata("/some/file/path.txt")?;
1841 /// // inspect attr ...
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 pub fn metadata
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<Metadata
> {
1847 fs_imp
::stat(path
.as_ref()).map(Metadata
)
1850 /// Query the metadata about a file without following symlinks.
1852 /// # Platform-specific behavior
1854 /// This function currently corresponds to the `lstat` function on Unix
1855 /// and the `GetFileInformationByHandle` function on Windows.
1856 /// Note that, this [may change in the future][changes].
1858 /// [changes]: io#platform-specific-behavior
1862 /// This function will return an error in the following situations, but is not
1863 /// limited to just these cases:
1865 /// * The user lacks permissions to perform `metadata` call on `path`.
1866 /// * `path` does not exist.
1873 /// fn main() -> std::io::Result<()> {
1874 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1875 /// // inspect attr ...
1879 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1880 pub fn symlink_metadata
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<Metadata
> {
1881 fs_imp
::lstat(path
.as_ref()).map(Metadata
)
1884 /// Rename a file or directory to a new name, replacing the original file if
1885 /// `to` already exists.
1887 /// This will not work if the new name is on a different mount point.
1889 /// # Platform-specific behavior
1891 /// This function currently corresponds to the `rename` function on Unix
1892 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1894 /// Because of this, the behavior when both `from` and `to` exist differs. On
1895 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1896 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1897 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1899 /// Note that, this [may change in the future][changes].
1901 /// [changes]: io#platform-specific-behavior
1905 /// This function will return an error in the following situations, but is not
1906 /// limited to just these cases:
1908 /// * `from` does not exist.
1909 /// * The user lacks permissions to view contents.
1910 /// * `from` and `to` are on separate filesystems.
1917 /// fn main() -> std::io::Result<()> {
1918 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn rename
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(from
: P
, to
: Q
) -> io
::Result
<()> {
1924 fs_imp
::rename(from
.as_ref(), to
.as_ref())
1927 /// Copies the contents of one file to another. This function will also
1928 /// copy the permission bits of the original file to the destination file.
1930 /// This function will **overwrite** the contents of `to`.
1932 /// Note that if `from` and `to` both point to the same file, then the file
1933 /// will likely get truncated by this operation.
1935 /// On success, the total number of bytes copied is returned and it is equal to
1936 /// the length of the `to` file as reported by `metadata`.
1938 /// If you’re wanting to copy the contents of one file to another and you’re
1939 /// working with [`File`]s, see the [`io::copy()`] function.
1941 /// # Platform-specific behavior
1943 /// This function currently corresponds to the `open` function in Unix
1944 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1945 /// `O_CLOEXEC` is set for returned file descriptors.
1947 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1948 /// and falls back to reading and writing if that is not possible.
1950 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1951 /// NTFS streams are copied but only the size of the main stream is returned by
1954 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1956 /// Note that platform-specific behavior [may change in the future][changes].
1958 /// [changes]: io#platform-specific-behavior
1962 /// This function will return an error in the following situations, but is not
1963 /// limited to just these cases:
1965 /// * `from` is neither a regular file nor a symlink to a regular file.
1966 /// * `from` does not exist.
1967 /// * The current process does not have the permission rights to read
1968 /// `from` or write `to`.
1975 /// fn main() -> std::io::Result<()> {
1976 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 pub fn copy
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(from
: P
, to
: Q
) -> io
::Result
<u64> {
1982 fs_imp
::copy(from
.as_ref(), to
.as_ref())
1985 /// Creates a new hard link on the filesystem.
1987 /// The `link` path will be a link pointing to the `original` path. Note that
1988 /// systems often require these two paths to both be located on the same
1991 /// If `original` names a symbolic link, it is platform-specific whether the
1992 /// symbolic link is followed. On platforms where it's possible to not follow
1993 /// it, it is not followed, and the created hard link points to the symbolic
1996 /// # Platform-specific behavior
1998 /// This function currently corresponds the `CreateHardLink` function on Windows.
1999 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
2000 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2001 /// On MacOS, it uses the `linkat` function if it is available, but on very old
2002 /// systems where `linkat` is not available, `link` is selected at runtime instead.
2003 /// Note that, this [may change in the future][changes].
2005 /// [changes]: io#platform-specific-behavior
2009 /// This function will return an error in the following situations, but is not
2010 /// limited to just these cases:
2012 /// * The `original` path is not a file or doesn't exist.
2019 /// fn main() -> std::io::Result<()> {
2020 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 pub fn hard_link
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(original
: P
, link
: Q
) -> io
::Result
<()> {
2026 fs_imp
::link(original
.as_ref(), link
.as_ref())
2029 /// Creates a new symbolic link on the filesystem.
2031 /// The `link` path will be a symbolic link pointing to the `original` path.
2032 /// On Windows, this will be a file symlink, not a directory symlink;
2033 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2034 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2035 /// used instead to make the intent explicit.
2037 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2038 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2039 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2046 /// fn main() -> std::io::Result<()> {
2047 /// fs::soft_link("a.txt", "b.txt")?;
2051 #[stable(feature = "rust1", since = "1.0.0")]
2054 note
= "replaced with std::os::unix::fs::symlink and \
2055 std::os::windows::fs::{symlink_file, symlink_dir}"
2057 pub fn soft_link
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(original
: P
, link
: Q
) -> io
::Result
<()> {
2058 fs_imp
::symlink(original
.as_ref(), link
.as_ref())
2061 /// Reads a symbolic link, returning the file that the link points to.
2063 /// # Platform-specific behavior
2065 /// This function currently corresponds to the `readlink` function on Unix
2066 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2067 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2068 /// Note that, this [may change in the future][changes].
2070 /// [changes]: io#platform-specific-behavior
2074 /// This function will return an error in the following situations, but is not
2075 /// limited to just these cases:
2077 /// * `path` is not a symbolic link.
2078 /// * `path` does not exist.
2085 /// fn main() -> std::io::Result<()> {
2086 /// let path = fs::read_link("a.txt")?;
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub fn read_link
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<PathBuf
> {
2092 fs_imp
::readlink(path
.as_ref())
2095 /// Returns the canonical, absolute form of a path with all intermediate
2096 /// components normalized and symbolic links resolved.
2098 /// # Platform-specific behavior
2100 /// This function currently corresponds to the `realpath` function on Unix
2101 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2102 /// Note that, this [may change in the future][changes].
2104 /// On Windows, this converts the path to use [extended length path][path]
2105 /// syntax, which allows your program to use longer path names, but means you
2106 /// can only join backslash-delimited paths to it, and it may be incompatible
2107 /// with other applications (if passed to the application on the command-line,
2108 /// or written to a file another application may read).
2110 /// [changes]: io#platform-specific-behavior
2111 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2115 /// This function will return an error in the following situations, but is not
2116 /// limited to just these cases:
2118 /// * `path` does not exist.
2119 /// * A non-final component in path is not a directory.
2126 /// fn main() -> std::io::Result<()> {
2127 /// let path = fs::canonicalize("../a/../foo.txt")?;
2131 #[doc(alias = "realpath")]
2132 #[doc(alias = "GetFinalPathNameByHandle")]
2133 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
2134 pub fn canonicalize
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<PathBuf
> {
2135 fs_imp
::canonicalize(path
.as_ref())
2138 /// Creates a new, empty directory at the provided path
2140 /// # Platform-specific behavior
2142 /// This function currently corresponds to the `mkdir` function on Unix
2143 /// and the `CreateDirectory` function on Windows.
2144 /// Note that, this [may change in the future][changes].
2146 /// [changes]: io#platform-specific-behavior
2148 /// **NOTE**: If a parent of the given path doesn't exist, this function will
2149 /// return an error. To create a directory and all its missing parents at the
2150 /// same time, use the [`create_dir_all`] function.
2154 /// This function will return an error in the following situations, but is not
2155 /// limited to just these cases:
2157 /// * User lacks permissions to create directory at `path`.
2158 /// * A parent of the given path doesn't exist. (To create a directory and all
2159 /// its missing parents at the same time, use the [`create_dir_all`]
2161 /// * `path` already exists.
2168 /// fn main() -> std::io::Result<()> {
2169 /// fs::create_dir("/some/dir")?;
2173 #[doc(alias = "mkdir")]
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 pub fn create_dir
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<()> {
2176 DirBuilder
::new().create(path
.as_ref())
2179 /// Recursively create a directory and all of its parent components if they
2182 /// # Platform-specific behavior
2184 /// This function currently corresponds to the `mkdir` function on Unix
2185 /// and the `CreateDirectory` function on Windows.
2186 /// Note that, this [may change in the future][changes].
2188 /// [changes]: io#platform-specific-behavior
2192 /// This function will return an error in the following situations, but is not
2193 /// limited to just these cases:
2195 /// * If any directory in the path specified by `path`
2196 /// does not already exist and it could not be created otherwise. The specific
2197 /// error conditions for when a directory is being created (after it is
2198 /// determined to not exist) are outlined by [`fs::create_dir`].
2200 /// Notable exception is made for situations where any of the directories
2201 /// specified in the `path` could not be created as it was being created concurrently.
2202 /// Such cases are considered to be successful. That is, calling `create_dir_all`
2203 /// concurrently from multiple threads or processes is guaranteed not to fail
2204 /// due to a race condition with itself.
2206 /// [`fs::create_dir`]: create_dir
2213 /// fn main() -> std::io::Result<()> {
2214 /// fs::create_dir_all("/some/dir")?;
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn create_dir_all
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<()> {
2220 DirBuilder
::new().recursive(true).create(path
.as_ref())
2223 /// Removes an empty directory.
2225 /// # Platform-specific behavior
2227 /// This function currently corresponds to the `rmdir` function on Unix
2228 /// and the `RemoveDirectory` function on Windows.
2229 /// Note that, this [may change in the future][changes].
2231 /// [changes]: io#platform-specific-behavior
2235 /// This function will return an error in the following situations, but is not
2236 /// limited to just these cases:
2238 /// * `path` doesn't exist.
2239 /// * `path` isn't a directory.
2240 /// * The user lacks permissions to remove the directory at the provided `path`.
2241 /// * The directory isn't empty.
2248 /// fn main() -> std::io::Result<()> {
2249 /// fs::remove_dir("/some/dir")?;
2253 #[doc(alias = "rmdir")]
2254 #[stable(feature = "rust1", since = "1.0.0")]
2255 pub fn remove_dir
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<()> {
2256 fs_imp
::rmdir(path
.as_ref())
2259 /// Removes a directory at this path, after removing all its contents. Use
2262 /// This function does **not** follow symbolic links and it will simply remove the
2263 /// symbolic link itself.
2265 /// # Platform-specific behavior
2267 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2268 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2269 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2270 /// Windows. Note that, this [may change in the future][changes].
2272 /// [changes]: io#platform-specific-behavior
2274 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2275 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2276 /// should not be used in security-sensitive code on those platforms. All other platforms are
2281 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2283 /// [`fs::remove_file`]: remove_file
2284 /// [`fs::remove_dir`]: remove_dir
2291 /// fn main() -> std::io::Result<()> {
2292 /// fs::remove_dir_all("/some/dir")?;
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 pub fn remove_dir_all
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<()> {
2298 fs_imp
::remove_dir_all(path
.as_ref())
2301 /// Returns an iterator over the entries within a directory.
2303 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2304 /// New errors may be encountered after an iterator is initially constructed.
2305 /// Entries for the current and parent directories (typically `.` and `..`) are
2308 /// # Platform-specific behavior
2310 /// This function currently corresponds to the `opendir` function on Unix
2311 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2312 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2313 /// Note that, this [may change in the future][changes].
2315 /// [changes]: io#platform-specific-behavior
2317 /// The order in which this iterator returns entries is platform and filesystem
2322 /// This function will return an error in the following situations, but is not
2323 /// limited to just these cases:
2325 /// * The provided `path` doesn't exist.
2326 /// * The process lacks permissions to view the contents.
2327 /// * The `path` points at a non-directory file.
2333 /// use std::fs::{self, DirEntry};
2334 /// use std::path::Path;
2336 /// // one possible implementation of walking a directory only visiting files
2337 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2338 /// if dir.is_dir() {
2339 /// for entry in fs::read_dir(dir)? {
2340 /// let entry = entry?;
2341 /// let path = entry.path();
2342 /// if path.is_dir() {
2343 /// visit_dirs(&path, cb)?;
2354 /// use std::{fs, io};
2356 /// fn main() -> io::Result<()> {
2357 /// let mut entries = fs::read_dir(".")?
2358 /// .map(|res| res.map(|e| e.path()))
2359 /// .collect::<Result<Vec<_>, io::Error>>()?;
2361 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2362 /// // ordering is required the entries should be explicitly sorted.
2366 /// // The entries have now been sorted by their path.
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 pub fn read_dir
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<ReadDir
> {
2373 fs_imp
::readdir(path
.as_ref()).map(ReadDir
)
2376 /// Changes the permissions found on a file or a directory.
2378 /// # Platform-specific behavior
2380 /// This function currently corresponds to the `chmod` function on Unix
2381 /// and the `SetFileAttributes` function on Windows.
2382 /// Note that, this [may change in the future][changes].
2384 /// [changes]: io#platform-specific-behavior
2388 /// This function will return an error in the following situations, but is not
2389 /// limited to just these cases:
2391 /// * `path` does not exist.
2392 /// * The user lacks the permission to change attributes of the file.
2399 /// fn main() -> std::io::Result<()> {
2400 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2401 /// perms.set_readonly(true);
2402 /// fs::set_permissions("foo.txt", perms)?;
2406 #[stable(feature = "set_permissions", since = "1.1.0")]
2407 pub fn set_permissions
<P
: AsRef
<Path
>>(path
: P
, perm
: Permissions
) -> io
::Result
<()> {
2408 fs_imp
::set_perm(path
.as_ref(), perm
.0)
2412 /// Creates a new set of options with default mode/security settings for all
2413 /// platforms and also non-recursive.
2418 /// use std::fs::DirBuilder;
2420 /// let builder = DirBuilder::new();
2422 #[stable(feature = "dir_builder", since = "1.6.0")]
2424 pub fn new() -> DirBuilder
{
2425 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2428 /// Indicates that directories should be created recursively, creating all
2429 /// parent directories. Parents that do not exist are created with the same
2430 /// security and permissions settings.
2432 /// This option defaults to `false`.
2437 /// use std::fs::DirBuilder;
2439 /// let mut builder = DirBuilder::new();
2440 /// builder.recursive(true);
2442 #[stable(feature = "dir_builder", since = "1.6.0")]
2443 pub fn recursive(&mut self, recursive
: bool
) -> &mut Self {
2444 self.recursive
= recursive
;
2448 /// Creates the specified directory with the options configured in this
2451 /// It is considered an error if the directory already exists unless
2452 /// recursive mode is enabled.
2457 /// use std::fs::{self, DirBuilder};
2459 /// let path = "/tmp/foo/bar/baz";
2460 /// DirBuilder::new()
2461 /// .recursive(true)
2462 /// .create(path).unwrap();
2464 /// assert!(fs::metadata(path).unwrap().is_dir());
2466 #[stable(feature = "dir_builder", since = "1.6.0")]
2467 pub fn create
<P
: AsRef
<Path
>>(&self, path
: P
) -> io
::Result
<()> {
2468 self._create(path
.as_ref())
2471 fn _create(&self, path
: &Path
) -> io
::Result
<()> {
2472 if self.recursive { self.create_dir_all(path) }
else { self.inner.mkdir(path) }
2475 fn create_dir_all(&self, path
: &Path
) -> io
::Result
<()> {
2476 if path
== Path
::new("") {
2480 match self.inner
.mkdir(path
) {
2481 Ok(()) => return Ok(()),
2482 Err(ref e
) if e
.kind() == io
::ErrorKind
::NotFound
=> {}
2483 Err(_
) if path
.is_dir() => return Ok(()),
2484 Err(e
) => return Err(e
),
2486 match path
.parent() {
2487 Some(p
) => self.create_dir_all(p
)?
,
2489 return Err(io
::const_io_error
!(
2490 io
::ErrorKind
::Uncategorized
,
2491 "failed to create whole tree",
2495 match self.inner
.mkdir(path
) {
2497 Err(_
) if path
.is_dir() => Ok(()),
2503 impl AsInnerMut
<fs_imp
::DirBuilder
> for DirBuilder
{
2504 fn as_inner_mut(&mut self) -> &mut fs_imp
::DirBuilder
{
2509 /// Returns `Ok(true)` if the path points at an existing entity.
2511 /// This function will traverse symbolic links to query information about the
2512 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2514 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2515 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2516 /// denied on some of the parent directories.)
2518 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2519 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2520 /// where those bugs are not an issue.
2525 /// #![feature(fs_try_exists)]
2528 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2529 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2532 /// [`Path::exists`]: crate::path::Path::exists
2533 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2535 #[unstable(feature = "fs_try_exists", issue = "83186")]
2537 pub fn try_exists
<P
: AsRef
<Path
>>(path
: P
) -> io
::Result
<bool
> {
2538 fs_imp
::try_exists(path
.as_ref())