std/fs.rs
1//! Filesystem manipulation operations.
2//!
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`.
7//!
8//! # Time of Check to Time of Use (TOCTOU)
9//!
10//! Many filesystem operations are subject to a race condition known as "Time of Check to Time of Use"
11//! (TOCTOU). This occurs when a program checks a condition (like file existence or permissions)
12//! and then uses the result of that check to make a decision, but the condition may have changed
13//! between the check and the use.
14//!
15//! For example, checking if a file exists and then creating it if it doesn't is vulnerable to
16//! TOCTOU - another process could create the file between your check and creation attempt.
17//!
18//! Another example is with symbolic links: when removing a directory, if another process replaces
19//! the directory with a symbolic link between the check and the removal operation, the removal
20//! might affect the wrong location. This is why operations like [`remove_dir_all`] need to use
21//! atomic operations to prevent such race conditions.
22//!
23//! To avoid TOCTOU issues:
24//! - Be aware that metadata operations (like [`metadata`] or [`symlink_metadata`]) may be affected by
25//! changes made by other processes.
26//! - Use atomic operations when possible (like [`File::create_new`] instead of checking existence then creating).
27//! - Keep file open for the duration of operations.
28
29#![stable(feature = "rust1", since = "1.0.0")]
30#![deny(unsafe_op_in_unsafe_fn)]
31
32#[cfg(all(
33 test,
34 not(any(
35 target_os = "emscripten",
36 target_os = "wasi",
37 target_env = "sgx",
38 target_os = "xous",
39 target_os = "trusty",
40 ))
41))]
42mod tests;
43
44use crate::ffi::OsString;
45use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
46use crate::path::{Path, PathBuf};
47use crate::sealed::Sealed;
48use crate::sync::Arc;
49use crate::sys::fs as fs_imp;
50use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
51use crate::time::SystemTime;
52use crate::{error, fmt};
53
54/// An object providing access to an open file on the filesystem.
55///
56/// An instance of a `File` can be read and/or written depending on what options
57/// it was opened with. Files also implement [`Seek`] to alter the logical cursor
58/// that the file contains internally.
59///
60/// Files are automatically closed when they go out of scope. Errors detected
61/// on closing are ignored by the implementation of `Drop`. Use the method
62/// [`sync_all`] if these errors must be manually handled.
63///
64/// `File` does not buffer reads and writes. For efficiency, consider wrapping the
65/// file in a [`BufReader`] or [`BufWriter`] when performing many small [`read`]
66/// or [`write`] calls, unless unbuffered reads and writes are required.
67///
68/// # Examples
69///
70/// Creates a new file and write bytes to it (you can also use [`write`]):
71///
72/// ```no_run
73/// use std::fs::File;
74/// use std::io::prelude::*;
75///
76/// fn main() -> std::io::Result<()> {
77/// let mut file = File::create("foo.txt")?;
78/// file.write_all(b"Hello, world!")?;
79/// Ok(())
80/// }
81/// ```
82///
83/// Reads the contents of a file into a [`String`] (you can also use [`read`]):
84///
85/// ```no_run
86/// use std::fs::File;
87/// use std::io::prelude::*;
88///
89/// fn main() -> std::io::Result<()> {
90/// let mut file = File::open("foo.txt")?;
91/// let mut contents = String::new();
92/// file.read_to_string(&mut contents)?;
93/// assert_eq!(contents, "Hello, world!");
94/// Ok(())
95/// }
96/// ```
97///
98/// Using a buffered [`Read`]er:
99///
100/// ```no_run
101/// use std::fs::File;
102/// use std::io::BufReader;
103/// use std::io::prelude::*;
104///
105/// fn main() -> std::io::Result<()> {
106/// let file = File::open("foo.txt")?;
107/// let mut buf_reader = BufReader::new(file);
108/// let mut contents = String::new();
109/// buf_reader.read_to_string(&mut contents)?;
110/// assert_eq!(contents, "Hello, world!");
111/// Ok(())
112/// }
113/// ```
114///
115/// Note that, although read and write methods require a `&mut File`, because
116/// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
117/// still modify the file, either through methods that take `&File` or by
118/// retrieving the underlying OS object and modifying the file that way.
119/// Additionally, many operating systems allow concurrent modification of files
120/// by different processes. Avoid assuming that holding a `&File` means that the
121/// file will not change.
122///
123/// # Platform-specific behavior
124///
125/// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
126/// perform synchronous I/O operations. Therefore the underlying file must not
127/// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
128///
129/// [`BufReader`]: io::BufReader
130/// [`BufWriter`]: io::BufWriter
131/// [`sync_all`]: File::sync_all
132/// [`write`]: File::write
133/// [`read`]: File::read
134#[stable(feature = "rust1", since = "1.0.0")]
135#[cfg_attr(not(test), rustc_diagnostic_item = "File")]
136pub struct File {
137 inner: fs_imp::File,
138}
139
140/// An enumeration of possible errors which can occur while trying to acquire a lock
141/// from the [`try_lock`] method and [`try_lock_shared`] method on a [`File`].
142///
143/// [`try_lock`]: File::try_lock
144/// [`try_lock_shared`]: File::try_lock_shared
145#[stable(feature = "file_lock", since = "1.89.0")]
146pub enum TryLockError {
147 /// The lock could not be acquired due to an I/O error on the file. The standard library will
148 /// not return an [`ErrorKind::WouldBlock`] error inside [`TryLockError::Error`]
149 ///
150 /// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
151 Error(io::Error),
152 /// The lock could not be acquired at this time because it is held by another handle/process.
153 WouldBlock,
154}
155
156/// Metadata information about a file.
157///
158/// This structure is returned from the [`metadata`] or
159/// [`symlink_metadata`] function or method and represents known
160/// metadata about a file such as its permissions, size, modification
161/// times, etc.
162#[stable(feature = "rust1", since = "1.0.0")]
163#[derive(Clone)]
164pub struct Metadata(fs_imp::FileAttr);
165
166/// Iterator over the entries in a directory.
167///
168/// This iterator is returned from the [`read_dir`] function of this module and
169/// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
170/// information like the entry's path and possibly other metadata can be
171/// learned.
172///
173/// The order in which this iterator returns entries is platform and filesystem
174/// dependent.
175///
176/// # Errors
177/// This [`io::Result`] will be an [`Err`] if an error occurred while fetching
178/// the next entry from the OS.
179#[stable(feature = "rust1", since = "1.0.0")]
180#[derive(Debug)]
181pub struct ReadDir(fs_imp::ReadDir);
182
183/// Entries returned by the [`ReadDir`] iterator.
184///
185/// An instance of `DirEntry` represents an entry inside of a directory on the
186/// filesystem. Each entry can be inspected via methods to learn about the full
187/// path or possibly other metadata through per-platform extension traits.
188///
189/// # Platform-specific behavior
190///
191/// On Unix, the `DirEntry` struct contains an internal reference to the open
192/// directory. Holding `DirEntry` objects will consume a file handle even
193/// after the `ReadDir` iterator is dropped.
194///
195/// Note that this [may change in the future][changes].
196///
197/// [changes]: io#platform-specific-behavior
198#[stable(feature = "rust1", since = "1.0.0")]
199pub struct DirEntry(fs_imp::DirEntry);
200
201/// Options and flags which can be used to configure how a file is opened.
202///
203/// This builder exposes the ability to configure how a [`File`] is opened and
204/// what operations are permitted on the open file. The [`File::open`] and
205/// [`File::create`] methods are aliases for commonly used options using this
206/// builder.
207///
208/// Generally speaking, when using `OpenOptions`, you'll first call
209/// [`OpenOptions::new`], then chain calls to methods to set each option, then
210/// call [`OpenOptions::open`], passing the path of the file you're trying to
211/// open. This will give you a [`io::Result`] with a [`File`] inside that you
212/// can further operate on.
213///
214/// # Examples
215///
216/// Opening a file to read:
217///
218/// ```no_run
219/// use std::fs::OpenOptions;
220///
221/// let file = OpenOptions::new().read(true).open("foo.txt");
222/// ```
223///
224/// Opening a file for both reading and writing, as well as creating it if it
225/// doesn't exist:
226///
227/// ```no_run
228/// use std::fs::OpenOptions;
229///
230/// let file = OpenOptions::new()
231/// .read(true)
232/// .write(true)
233/// .create(true)
234/// .open("foo.txt");
235/// ```
236#[derive(Clone, Debug)]
237#[stable(feature = "rust1", since = "1.0.0")]
238#[cfg_attr(not(test), rustc_diagnostic_item = "FsOpenOptions")]
239pub struct OpenOptions(fs_imp::OpenOptions);
240
241/// Representation of the various timestamps on a file.
242#[derive(Copy, Clone, Debug, Default)]
243#[stable(feature = "file_set_times", since = "1.75.0")]
244pub struct FileTimes(fs_imp::FileTimes);
245
246/// Representation of the various permissions on a file.
247///
248/// This module only currently provides one bit of information,
249/// [`Permissions::readonly`], which is exposed on all currently supported
250/// platforms. Unix-specific functionality, such as mode bits, is available
251/// through the [`PermissionsExt`] trait.
252///
253/// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
254#[derive(Clone, PartialEq, Eq, Debug)]
255#[stable(feature = "rust1", since = "1.0.0")]
256#[cfg_attr(not(test), rustc_diagnostic_item = "FsPermissions")]
257pub struct Permissions(fs_imp::FilePermissions);
258
259/// A structure representing a type of file with accessors for each file type.
260/// It is returned by [`Metadata::file_type`] method.
261#[stable(feature = "file_type", since = "1.1.0")]
262#[derive(Copy, Clone, PartialEq, Eq, Hash)]
263#[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
264pub struct FileType(fs_imp::FileType);
265
266/// A builder used to create directories in various manners.
267///
268/// This builder also supports platform-specific options.
269#[stable(feature = "dir_builder", since = "1.6.0")]
270#[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
271#[derive(Debug)]
272pub struct DirBuilder {
273 inner: fs_imp::DirBuilder,
274 recursive: bool,
275}
276
277/// Reads the entire contents of a file into a bytes vector.
278///
279/// This is a convenience function for using [`File::open`] and [`read_to_end`]
280/// with fewer imports and without an intermediate variable.
281///
282/// [`read_to_end`]: Read::read_to_end
283///
284/// # Errors
285///
286/// This function will return an error if `path` does not already exist.
287/// Other errors may also be returned according to [`OpenOptions::open`].
288///
289/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
290/// with automatic retries. See [io::Read] documentation for details.
291///
292/// # Examples
293///
294/// ```no_run
295/// use std::fs;
296///
297/// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
298/// let data: Vec<u8> = fs::read("image.jpg")?;
299/// assert_eq!(data[0..3], [0xFF, 0xD8, 0xFF]);
300/// Ok(())
301/// }
302/// ```
303#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
304pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
305 fn inner(path: &Path) -> io::Result<Vec<u8>> {
306 let mut file = File::open(path)?;
307 let size = file.metadata().map(|m| m.len() as usize).ok();
308 let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?;
309 io::default_read_to_end(&mut file, &mut bytes, size)?;
310 Ok(bytes)
311 }
312 inner(path.as_ref())
313}
314
315/// Reads the entire contents of a file into a string.
316///
317/// This is a convenience function for using [`File::open`] and [`read_to_string`]
318/// with fewer imports and without an intermediate variable.
319///
320/// [`read_to_string`]: Read::read_to_string
321///
322/// # Errors
323///
324/// This function will return an error if `path` does not already exist.
325/// Other errors may also be returned according to [`OpenOptions::open`].
326///
327/// If the contents of the file are not valid UTF-8, then an error will also be
328/// returned.
329///
330/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
331/// with automatic retries. See [io::Read] documentation for details.
332///
333/// # Examples
334///
335/// ```no_run
336/// use std::fs;
337/// use std::error::Error;
338///
339/// fn main() -> Result<(), Box<dyn Error>> {
340/// let message: String = fs::read_to_string("message.txt")?;
341/// println!("{}", message);
342/// Ok(())
343/// }
344/// ```
345#[stable(feature = "fs_read_write", since = "1.26.0")]
346pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
347 fn inner(path: &Path) -> io::Result<String> {
348 let mut file = File::open(path)?;
349 let size = file.metadata().map(|m| m.len() as usize).ok();
350 let mut string = String::new();
351 string.try_reserve_exact(size.unwrap_or(0))?;
352 io::default_read_to_string(&mut file, &mut string, size)?;
353 Ok(string)
354 }
355 inner(path.as_ref())
356}
357
358/// Writes a slice as the entire contents of a file.
359///
360/// This function will create a file if it does not exist,
361/// and will entirely replace its contents if it does.
362///
363/// Depending on the platform, this function may fail if the
364/// full directory path does not exist.
365///
366/// This is a convenience function for using [`File::create`] and [`write_all`]
367/// with fewer imports.
368///
369/// [`write_all`]: Write::write_all
370///
371/// # Examples
372///
373/// ```no_run
374/// use std::fs;
375///
376/// fn main() -> std::io::Result<()> {
377/// fs::write("foo.txt", b"Lorem ipsum")?;
378/// fs::write("bar.txt", "dolor sit")?;
379/// Ok(())
380/// }
381/// ```
382#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
383pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
384 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
385 File::create(path)?.write_all(contents)
386 }
387 inner(path.as_ref(), contents.as_ref())
388}
389
390#[stable(feature = "file_lock", since = "1.89.0")]
391impl error::Error for TryLockError {}
392
393#[stable(feature = "file_lock", since = "1.89.0")]
394impl fmt::Debug for TryLockError {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 match self {
397 TryLockError::Error(err) => err.fmt(f),
398 TryLockError::WouldBlock => "WouldBlock".fmt(f),
399 }
400 }
401}
402
403#[stable(feature = "file_lock", since = "1.89.0")]
404impl fmt::Display for TryLockError {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 match self {
407 TryLockError::Error(_) => "lock acquisition failed due to I/O error",
408 TryLockError::WouldBlock => "lock acquisition failed because the operation would block",
409 }
410 .fmt(f)
411 }
412}
413
414#[stable(feature = "file_lock", since = "1.89.0")]
415impl From<TryLockError> for io::Error {
416 fn from(err: TryLockError) -> io::Error {
417 match err {
418 TryLockError::Error(err) => err,
419 TryLockError::WouldBlock => io::ErrorKind::WouldBlock.into(),
420 }
421 }
422}
423
424impl File {
425 /// Attempts to open a file in read-only mode.
426 ///
427 /// See the [`OpenOptions::open`] method for more details.
428 ///
429 /// If you only need to read the entire file contents,
430 /// consider [`std::fs::read()`][self::read] or
431 /// [`std::fs::read_to_string()`][self::read_to_string] instead.
432 ///
433 /// # Errors
434 ///
435 /// This function will return an error if `path` does not already exist.
436 /// Other errors may also be returned according to [`OpenOptions::open`].
437 ///
438 /// # Examples
439 ///
440 /// ```no_run
441 /// use std::fs::File;
442 /// use std::io::Read;
443 ///
444 /// fn main() -> std::io::Result<()> {
445 /// let mut f = File::open("foo.txt")?;
446 /// let mut data = vec![];
447 /// f.read_to_end(&mut data)?;
448 /// Ok(())
449 /// }
450 /// ```
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
453 OpenOptions::new().read(true).open(path.as_ref())
454 }
455
456 /// Attempts to open a file in read-only mode with buffering.
457 ///
458 /// See the [`OpenOptions::open`] method, the [`BufReader`][io::BufReader] type,
459 /// and the [`BufRead`][io::BufRead] trait for more details.
460 ///
461 /// If you only need to read the entire file contents,
462 /// consider [`std::fs::read()`][self::read] or
463 /// [`std::fs::read_to_string()`][self::read_to_string] instead.
464 ///
465 /// # Errors
466 ///
467 /// This function will return an error if `path` does not already exist,
468 /// or if memory allocation fails for the new buffer.
469 /// Other errors may also be returned according to [`OpenOptions::open`].
470 ///
471 /// # Examples
472 ///
473 /// ```no_run
474 /// #![feature(file_buffered)]
475 /// use std::fs::File;
476 /// use std::io::BufRead;
477 ///
478 /// fn main() -> std::io::Result<()> {
479 /// let mut f = File::open_buffered("foo.txt")?;
480 /// assert!(f.capacity() > 0);
481 /// for (line, i) in f.lines().zip(1..) {
482 /// println!("{i:6}: {}", line?);
483 /// }
484 /// Ok(())
485 /// }
486 /// ```
487 #[unstable(feature = "file_buffered", issue = "130804")]
488 pub fn open_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufReader<File>> {
489 // Allocate the buffer *first* so we don't affect the filesystem otherwise.
490 let buffer = io::BufReader::<Self>::try_new_buffer()?;
491 let file = File::open(path)?;
492 Ok(io::BufReader::with_buffer(file, buffer))
493 }
494
495 /// Opens a file in write-only mode.
496 ///
497 /// This function will create a file if it does not exist,
498 /// and will truncate it if it does.
499 ///
500 /// Depending on the platform, this function may fail if the
501 /// full directory path does not exist.
502 /// See the [`OpenOptions::open`] function for more details.
503 ///
504 /// See also [`std::fs::write()`][self::write] for a simple function to
505 /// create a file with some given data.
506 ///
507 /// # Examples
508 ///
509 /// ```no_run
510 /// use std::fs::File;
511 /// use std::io::Write;
512 ///
513 /// fn main() -> std::io::Result<()> {
514 /// let mut f = File::create("foo.txt")?;
515 /// f.write_all(&1234_u32.to_be_bytes())?;
516 /// Ok(())
517 /// }
518 /// ```
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
521 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
522 }
523
524 /// Opens a file in write-only mode with buffering.
525 ///
526 /// This function will create a file if it does not exist,
527 /// and will truncate it if it does.
528 ///
529 /// Depending on the platform, this function may fail if the
530 /// full directory path does not exist.
531 ///
532 /// See the [`OpenOptions::open`] method and the
533 /// [`BufWriter`][io::BufWriter] type for more details.
534 ///
535 /// See also [`std::fs::write()`][self::write] for a simple function to
536 /// create a file with some given data.
537 ///
538 /// # Examples
539 ///
540 /// ```no_run
541 /// #![feature(file_buffered)]
542 /// use std::fs::File;
543 /// use std::io::Write;
544 ///
545 /// fn main() -> std::io::Result<()> {
546 /// let mut f = File::create_buffered("foo.txt")?;
547 /// assert!(f.capacity() > 0);
548 /// for i in 0..100 {
549 /// writeln!(&mut f, "{i}")?;
550 /// }
551 /// f.flush()?;
552 /// Ok(())
553 /// }
554 /// ```
555 #[unstable(feature = "file_buffered", issue = "130804")]
556 pub fn create_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufWriter<File>> {
557 // Allocate the buffer *first* so we don't affect the filesystem otherwise.
558 let buffer = io::BufWriter::<Self>::try_new_buffer()?;
559 let file = File::create(path)?;
560 Ok(io::BufWriter::with_buffer(file, buffer))
561 }
562
563 /// Creates a new file in read-write mode; error if the file exists.
564 ///
565 /// This function will create a file if it does not exist, or return an error if it does. This
566 /// way, if the call succeeds, the file returned is guaranteed to be new.
567 /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
568 /// or another error based on the situation. See [`OpenOptions::open`] for a
569 /// non-exhaustive list of likely errors.
570 ///
571 /// This option is useful because it is atomic. Otherwise between checking whether a file
572 /// exists and creating a new one, the file may have been created by another process (a [TOCTOU]
573 /// race condition / attack).
574 ///
575 /// This can also be written using
576 /// `File::options().read(true).write(true).create_new(true).open(...)`.
577 ///
578 /// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
579 /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
580 ///
581 /// # Examples
582 ///
583 /// ```no_run
584 /// use std::fs::File;
585 /// use std::io::Write;
586 ///
587 /// fn main() -> std::io::Result<()> {
588 /// let mut f = File::create_new("foo.txt")?;
589 /// f.write_all("Hello, world!".as_bytes())?;
590 /// Ok(())
591 /// }
592 /// ```
593 #[stable(feature = "file_create_new", since = "1.77.0")]
594 pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
595 OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
596 }
597
598 /// Returns a new OpenOptions object.
599 ///
600 /// This function returns a new OpenOptions object that you can use to
601 /// open or create a file with specific options if `open()` or `create()`
602 /// are not appropriate.
603 ///
604 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
605 /// readable code. Instead of
606 /// `OpenOptions::new().append(true).open("example.log")`,
607 /// you can write `File::options().append(true).open("example.log")`. This
608 /// also avoids the need to import `OpenOptions`.
609 ///
610 /// See the [`OpenOptions::new`] function for more details.
611 ///
612 /// # Examples
613 ///
614 /// ```no_run
615 /// use std::fs::File;
616 /// use std::io::Write;
617 ///
618 /// fn main() -> std::io::Result<()> {
619 /// let mut f = File::options().append(true).open("example.log")?;
620 /// writeln!(&mut f, "new line")?;
621 /// Ok(())
622 /// }
623 /// ```
624 #[must_use]
625 #[stable(feature = "with_options", since = "1.58.0")]
626 #[cfg_attr(not(test), rustc_diagnostic_item = "file_options")]
627 pub fn options() -> OpenOptions {
628 OpenOptions::new()
629 }
630
631 /// Attempts to sync all OS-internal file content and metadata to disk.
632 ///
633 /// This function will attempt to ensure that all in-memory data reaches the
634 /// filesystem before returning.
635 ///
636 /// This can be used to handle errors that would otherwise only be caught
637 /// when the `File` is closed, as dropping a `File` will ignore all errors.
638 /// Note, however, that `sync_all` is generally more expensive than closing
639 /// a file by dropping it, because the latter is not required to block until
640 /// the data has been written to the filesystem.
641 ///
642 /// If synchronizing the metadata is not required, use [`sync_data`] instead.
643 ///
644 /// [`sync_data`]: File::sync_data
645 ///
646 /// # Examples
647 ///
648 /// ```no_run
649 /// use std::fs::File;
650 /// use std::io::prelude::*;
651 ///
652 /// fn main() -> std::io::Result<()> {
653 /// let mut f = File::create("foo.txt")?;
654 /// f.write_all(b"Hello, world!")?;
655 ///
656 /// f.sync_all()?;
657 /// Ok(())
658 /// }
659 /// ```
660 #[stable(feature = "rust1", since = "1.0.0")]
661 #[doc(alias = "fsync")]
662 pub fn sync_all(&self) -> io::Result<()> {
663 self.inner.fsync()
664 }
665
666 /// This function is similar to [`sync_all`], except that it might not
667 /// synchronize file metadata to the filesystem.
668 ///
669 /// This is intended for use cases that must synchronize content, but don't
670 /// need the metadata on disk. The goal of this method is to reduce disk
671 /// operations.
672 ///
673 /// Note that some platforms may simply implement this in terms of
674 /// [`sync_all`].
675 ///
676 /// [`sync_all`]: File::sync_all
677 ///
678 /// # Examples
679 ///
680 /// ```no_run
681 /// use std::fs::File;
682 /// use std::io::prelude::*;
683 ///
684 /// fn main() -> std::io::Result<()> {
685 /// let mut f = File::create("foo.txt")?;
686 /// f.write_all(b"Hello, world!")?;
687 ///
688 /// f.sync_data()?;
689 /// Ok(())
690 /// }
691 /// ```
692 #[stable(feature = "rust1", since = "1.0.0")]
693 #[doc(alias = "fdatasync")]
694 pub fn sync_data(&self) -> io::Result<()> {
695 self.inner.datasync()
696 }
697
698 /// Acquire an exclusive lock on the file. Blocks until the lock can be acquired.
699 ///
700 /// This acquires an exclusive lock; no other file handle to this file may acquire another lock.
701 ///
702 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
703 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
704 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
705 /// cause non-lockholders to block.
706 ///
707 /// If this file handle/descriptor, or a clone of it, already holds a lock the exact behavior
708 /// is unspecified and platform dependent, including the possibility that it will deadlock.
709 /// However, if this method returns, then an exclusive lock is held.
710 ///
711 /// If the file is not open for writing, it is unspecified whether this function returns an error.
712 ///
713 /// The lock will be released when this file (along with any other file descriptors/handles
714 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
715 ///
716 /// # Platform-specific behavior
717 ///
718 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
719 /// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
720 /// this [may change in the future][changes].
721 ///
722 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
723 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
724 ///
725 /// [changes]: io#platform-specific-behavior
726 ///
727 /// [`lock`]: File::lock
728 /// [`lock_shared`]: File::lock_shared
729 /// [`try_lock`]: File::try_lock
730 /// [`try_lock_shared`]: File::try_lock_shared
731 /// [`unlock`]: File::unlock
732 /// [`read`]: Read::read
733 /// [`write`]: Write::write
734 ///
735 /// # Examples
736 ///
737 /// ```no_run
738 /// use std::fs::File;
739 ///
740 /// fn main() -> std::io::Result<()> {
741 /// let f = File::create("foo.txt")?;
742 /// f.lock()?;
743 /// Ok(())
744 /// }
745 /// ```
746 #[stable(feature = "file_lock", since = "1.89.0")]
747 pub fn lock(&self) -> io::Result<()> {
748 self.inner.lock()
749 }
750
751 /// Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.
752 ///
753 /// This acquires a shared lock; more than one file handle may hold a shared lock, but none may
754 /// hold an exclusive lock at the same time.
755 ///
756 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
757 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
758 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
759 /// cause non-lockholders to block.
760 ///
761 /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
762 /// is unspecified and platform dependent, including the possibility that it will deadlock.
763 /// However, if this method returns, then a shared lock is held.
764 ///
765 /// The lock will be released when this file (along with any other file descriptors/handles
766 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
767 ///
768 /// # Platform-specific behavior
769 ///
770 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
771 /// and the `LockFileEx` function on Windows. Note that, this
772 /// [may change in the future][changes].
773 ///
774 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
775 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
776 ///
777 /// [changes]: io#platform-specific-behavior
778 ///
779 /// [`lock`]: File::lock
780 /// [`lock_shared`]: File::lock_shared
781 /// [`try_lock`]: File::try_lock
782 /// [`try_lock_shared`]: File::try_lock_shared
783 /// [`unlock`]: File::unlock
784 /// [`read`]: Read::read
785 /// [`write`]: Write::write
786 ///
787 /// # Examples
788 ///
789 /// ```no_run
790 /// use std::fs::File;
791 ///
792 /// fn main() -> std::io::Result<()> {
793 /// let f = File::open("foo.txt")?;
794 /// f.lock_shared()?;
795 /// Ok(())
796 /// }
797 /// ```
798 #[stable(feature = "file_lock", since = "1.89.0")]
799 pub fn lock_shared(&self) -> io::Result<()> {
800 self.inner.lock_shared()
801 }
802
803 /// Try to acquire an exclusive lock on the file.
804 ///
805 /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
806 /// (via another handle/descriptor).
807 ///
808 /// This acquires an exclusive lock; no other file handle to this file may acquire another lock.
809 ///
810 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
811 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
812 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
813 /// cause non-lockholders to block.
814 ///
815 /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
816 /// is unspecified and platform dependent, including the possibility that it will deadlock.
817 /// However, if this method returns `Ok(())`, then it has acquired an exclusive lock.
818 ///
819 /// If the file is not open for writing, it is unspecified whether this function returns an error.
820 ///
821 /// The lock will be released when this file (along with any other file descriptors/handles
822 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
823 ///
824 /// # Platform-specific behavior
825 ///
826 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
827 /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
828 /// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
829 /// [may change in the future][changes].
830 ///
831 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
832 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
833 ///
834 /// [changes]: io#platform-specific-behavior
835 ///
836 /// [`lock`]: File::lock
837 /// [`lock_shared`]: File::lock_shared
838 /// [`try_lock`]: File::try_lock
839 /// [`try_lock_shared`]: File::try_lock_shared
840 /// [`unlock`]: File::unlock
841 /// [`read`]: Read::read
842 /// [`write`]: Write::write
843 ///
844 /// # Examples
845 ///
846 /// ```no_run
847 /// use std::fs::{File, TryLockError};
848 ///
849 /// fn main() -> std::io::Result<()> {
850 /// let f = File::create("foo.txt")?;
851 /// // Explicit handling of the WouldBlock error
852 /// match f.try_lock() {
853 /// Ok(_) => (),
854 /// Err(TryLockError::WouldBlock) => (), // Lock not acquired
855 /// Err(TryLockError::Error(err)) => return Err(err),
856 /// }
857 /// // Alternately, propagate the error as an io::Error
858 /// f.try_lock()?;
859 /// Ok(())
860 /// }
861 /// ```
862 #[stable(feature = "file_lock", since = "1.89.0")]
863 pub fn try_lock(&self) -> Result<(), TryLockError> {
864 self.inner.try_lock()
865 }
866
867 /// Try to acquire a shared (non-exclusive) lock on the file.
868 ///
869 /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
870 /// (via another handle/descriptor).
871 ///
872 /// This acquires a shared lock; more than one file handle may hold a shared lock, but none may
873 /// hold an exclusive lock at the same time.
874 ///
875 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
876 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
877 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
878 /// cause non-lockholders to block.
879 ///
880 /// If this file handle, or a clone of it, already holds a lock, the exact behavior is
881 /// unspecified and platform dependent, including the possibility that it will deadlock.
882 /// However, if this method returns `Ok(())`, then it has acquired a shared lock.
883 ///
884 /// The lock will be released when this file (along with any other file descriptors/handles
885 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
886 ///
887 /// # Platform-specific behavior
888 ///
889 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
890 /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
891 /// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
892 /// [may change in the future][changes].
893 ///
894 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
895 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
896 ///
897 /// [changes]: io#platform-specific-behavior
898 ///
899 /// [`lock`]: File::lock
900 /// [`lock_shared`]: File::lock_shared
901 /// [`try_lock`]: File::try_lock
902 /// [`try_lock_shared`]: File::try_lock_shared
903 /// [`unlock`]: File::unlock
904 /// [`read`]: Read::read
905 /// [`write`]: Write::write
906 ///
907 /// # Examples
908 ///
909 /// ```no_run
910 /// use std::fs::{File, TryLockError};
911 ///
912 /// fn main() -> std::io::Result<()> {
913 /// let f = File::open("foo.txt")?;
914 /// // Explicit handling of the WouldBlock error
915 /// match f.try_lock_shared() {
916 /// Ok(_) => (),
917 /// Err(TryLockError::WouldBlock) => (), // Lock not acquired
918 /// Err(TryLockError::Error(err)) => return Err(err),
919 /// }
920 /// // Alternately, propagate the error as an io::Error
921 /// f.try_lock_shared()?;
922 ///
923 /// Ok(())
924 /// }
925 /// ```
926 #[stable(feature = "file_lock", since = "1.89.0")]
927 pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
928 self.inner.try_lock_shared()
929 }
930
931 /// Release all locks on the file.
932 ///
933 /// All locks are released when the file (along with any other file descriptors/handles
934 /// duplicated or inherited from it) is closed. This method allows releasing locks without
935 /// closing the file.
936 ///
937 /// If no lock is currently held via this file descriptor/handle, this method may return an
938 /// error, or may return successfully without taking any action.
939 ///
940 /// # Platform-specific behavior
941 ///
942 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
943 /// and the `UnlockFile` function on Windows. Note that, this
944 /// [may change in the future][changes].
945 ///
946 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
947 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
948 ///
949 /// [changes]: io#platform-specific-behavior
950 ///
951 /// # Examples
952 ///
953 /// ```no_run
954 /// use std::fs::File;
955 ///
956 /// fn main() -> std::io::Result<()> {
957 /// let f = File::open("foo.txt")?;
958 /// f.lock()?;
959 /// f.unlock()?;
960 /// Ok(())
961 /// }
962 /// ```
963 #[stable(feature = "file_lock", since = "1.89.0")]
964 pub fn unlock(&self) -> io::Result<()> {
965 self.inner.unlock()
966 }
967
968 /// Truncates or extends the underlying file, updating the size of
969 /// this file to become `size`.
970 ///
971 /// If the `size` is less than the current file's size, then the file will
972 /// be shrunk. If it is greater than the current file's size, then the file
973 /// will be extended to `size` and have all of the intermediate data filled
974 /// in with 0s.
975 ///
976 /// The file's cursor isn't changed. In particular, if the cursor was at the
977 /// end and the file is shrunk using this operation, the cursor will now be
978 /// past the end.
979 ///
980 /// # Errors
981 ///
982 /// This function will return an error if the file is not opened for writing.
983 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
984 /// will be returned if the desired length would cause an overflow due to
985 /// the implementation specifics.
986 ///
987 /// # Examples
988 ///
989 /// ```no_run
990 /// use std::fs::File;
991 ///
992 /// fn main() -> std::io::Result<()> {
993 /// let mut f = File::create("foo.txt")?;
994 /// f.set_len(10)?;
995 /// Ok(())
996 /// }
997 /// ```
998 ///
999 /// Note that this method alters the content of the underlying file, even
1000 /// though it takes `&self` rather than `&mut self`.
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn set_len(&self, size: u64) -> io::Result<()> {
1003 self.inner.truncate(size)
1004 }
1005
1006 /// Queries metadata about the underlying file.
1007 ///
1008 /// # Examples
1009 ///
1010 /// ```no_run
1011 /// use std::fs::File;
1012 ///
1013 /// fn main() -> std::io::Result<()> {
1014 /// let mut f = File::open("foo.txt")?;
1015 /// let metadata = f.metadata()?;
1016 /// Ok(())
1017 /// }
1018 /// ```
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn metadata(&self) -> io::Result<Metadata> {
1021 self.inner.file_attr().map(Metadata)
1022 }
1023
1024 /// Creates a new `File` instance that shares the same underlying file handle
1025 /// as the existing `File` instance. Reads, writes, and seeks will affect
1026 /// both `File` instances simultaneously.
1027 ///
1028 /// # Examples
1029 ///
1030 /// Creates two handles for a file named `foo.txt`:
1031 ///
1032 /// ```no_run
1033 /// use std::fs::File;
1034 ///
1035 /// fn main() -> std::io::Result<()> {
1036 /// let mut file = File::open("foo.txt")?;
1037 /// let file_copy = file.try_clone()?;
1038 /// Ok(())
1039 /// }
1040 /// ```
1041 ///
1042 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
1043 /// two handles, seek one of them, and read the remaining bytes from the
1044 /// other handle:
1045 ///
1046 /// ```no_run
1047 /// use std::fs::File;
1048 /// use std::io::SeekFrom;
1049 /// use std::io::prelude::*;
1050 ///
1051 /// fn main() -> std::io::Result<()> {
1052 /// let mut file = File::open("foo.txt")?;
1053 /// let mut file_copy = file.try_clone()?;
1054 ///
1055 /// file.seek(SeekFrom::Start(3))?;
1056 ///
1057 /// let mut contents = vec![];
1058 /// file_copy.read_to_end(&mut contents)?;
1059 /// assert_eq!(contents, b"def\n");
1060 /// Ok(())
1061 /// }
1062 /// ```
1063 #[stable(feature = "file_try_clone", since = "1.9.0")]
1064 pub fn try_clone(&self) -> io::Result<File> {
1065 Ok(File { inner: self.inner.duplicate()? })
1066 }
1067
1068 /// Changes the permissions on the underlying file.
1069 ///
1070 /// # Platform-specific behavior
1071 ///
1072 /// This function currently corresponds to the `fchmod` function on Unix and
1073 /// the `SetFileInformationByHandle` function on Windows. Note that, this
1074 /// [may change in the future][changes].
1075 ///
1076 /// [changes]: io#platform-specific-behavior
1077 ///
1078 /// # Errors
1079 ///
1080 /// This function will return an error if the user lacks permission change
1081 /// attributes on the underlying file. It may also return an error in other
1082 /// os-specific unspecified cases.
1083 ///
1084 /// # Examples
1085 ///
1086 /// ```no_run
1087 /// fn main() -> std::io::Result<()> {
1088 /// use std::fs::File;
1089 ///
1090 /// let file = File::open("foo.txt")?;
1091 /// let mut perms = file.metadata()?.permissions();
1092 /// perms.set_readonly(true);
1093 /// file.set_permissions(perms)?;
1094 /// Ok(())
1095 /// }
1096 /// ```
1097 ///
1098 /// Note that this method alters the permissions of the underlying file,
1099 /// even though it takes `&self` rather than `&mut self`.
1100 #[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
1101 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
1102 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
1103 self.inner.set_permissions(perm.0)
1104 }
1105
1106 /// Changes the timestamps of the underlying file.
1107 ///
1108 /// # Platform-specific behavior
1109 ///
1110 /// This function currently corresponds to the `futimens` function on Unix (falling back to
1111 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
1112 /// [may change in the future][changes].
1113 ///
1114 /// On most platforms, including UNIX and Windows platforms, this function can also change the
1115 /// timestamps of a directory. To get a `File` representing a directory in order to call
1116 /// `set_times`, open the directory with `File::open` without attempting to obtain write
1117 /// permission.
1118 ///
1119 /// [changes]: io#platform-specific-behavior
1120 ///
1121 /// # Errors
1122 ///
1123 /// This function will return an error if the user lacks permission to change timestamps on the
1124 /// underlying file. It may also return an error in other os-specific unspecified cases.
1125 ///
1126 /// This function may return an error if the operating system lacks support to change one or
1127 /// more of the timestamps set in the `FileTimes` structure.
1128 ///
1129 /// # Examples
1130 ///
1131 /// ```no_run
1132 /// fn main() -> std::io::Result<()> {
1133 /// use std::fs::{self, File, FileTimes};
1134 ///
1135 /// let src = fs::metadata("src")?;
1136 /// let dest = File::open("dest")?;
1137 /// let times = FileTimes::new()
1138 /// .set_accessed(src.accessed()?)
1139 /// .set_modified(src.modified()?);
1140 /// dest.set_times(times)?;
1141 /// Ok(())
1142 /// }
1143 /// ```
1144 #[stable(feature = "file_set_times", since = "1.75.0")]
1145 #[doc(alias = "futimens")]
1146 #[doc(alias = "futimes")]
1147 #[doc(alias = "SetFileTime")]
1148 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1149 self.inner.set_times(times.0)
1150 }
1151
1152 /// Changes the modification time of the underlying file.
1153 ///
1154 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
1155 #[stable(feature = "file_set_times", since = "1.75.0")]
1156 #[inline]
1157 pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
1158 self.set_times(FileTimes::new().set_modified(time))
1159 }
1160}
1161
1162// In addition to the `impl`s here, `File` also has `impl`s for
1163// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1164// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1165// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
1166// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
1167
1168impl AsInner<fs_imp::File> for File {
1169 #[inline]
1170 fn as_inner(&self) -> &fs_imp::File {
1171 &self.inner
1172 }
1173}
1174impl FromInner<fs_imp::File> for File {
1175 fn from_inner(f: fs_imp::File) -> File {
1176 File { inner: f }
1177 }
1178}
1179impl IntoInner<fs_imp::File> for File {
1180 fn into_inner(self) -> fs_imp::File {
1181 self.inner
1182 }
1183}
1184
1185#[stable(feature = "rust1", since = "1.0.0")]
1186impl fmt::Debug for File {
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 self.inner.fmt(f)
1189 }
1190}
1191
1192/// Indicates how much extra capacity is needed to read the rest of the file.
1193fn buffer_capacity_required(mut file: &File) -> Option<usize> {
1194 let size = file.metadata().map(|m| m.len()).ok()?;
1195 let pos = file.stream_position().ok()?;
1196 // Don't worry about `usize` overflow because reading will fail regardless
1197 // in that case.
1198 Some(size.saturating_sub(pos) as usize)
1199}
1200
1201#[stable(feature = "rust1", since = "1.0.0")]
1202impl Read for &File {
1203 /// Reads some bytes from the file.
1204 ///
1205 /// See [`Read::read`] docs for more info.
1206 ///
1207 /// # Platform-specific behavior
1208 ///
1209 /// This function currently corresponds to the `read` function on Unix and
1210 /// the `NtReadFile` function on Windows. Note that this [may change in
1211 /// the future][changes].
1212 ///
1213 /// [changes]: io#platform-specific-behavior
1214 #[inline]
1215 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1216 self.inner.read(buf)
1217 }
1218
1219 /// Like `read`, except that it reads into a slice of buffers.
1220 ///
1221 /// See [`Read::read_vectored`] docs for more info.
1222 ///
1223 /// # Platform-specific behavior
1224 ///
1225 /// This function currently corresponds to the `readv` function on Unix and
1226 /// falls back to the `read` implementation on Windows. Note that this
1227 /// [may change in the future][changes].
1228 ///
1229 /// [changes]: io#platform-specific-behavior
1230 #[inline]
1231 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1232 self.inner.read_vectored(bufs)
1233 }
1234
1235 #[inline]
1236 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1237 self.inner.read_buf(cursor)
1238 }
1239
1240 /// Determines if `File` has an efficient `read_vectored` implementation.
1241 ///
1242 /// See [`Read::is_read_vectored`] docs for more info.
1243 ///
1244 /// # Platform-specific behavior
1245 ///
1246 /// This function currently returns `true` on Unix an `false` on Windows.
1247 /// Note that this [may change in the future][changes].
1248 ///
1249 /// [changes]: io#platform-specific-behavior
1250 #[inline]
1251 fn is_read_vectored(&self) -> bool {
1252 self.inner.is_read_vectored()
1253 }
1254
1255 // Reserves space in the buffer based on the file size when available.
1256 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1257 let size = buffer_capacity_required(self);
1258 buf.try_reserve(size.unwrap_or(0))?;
1259 io::default_read_to_end(self, buf, size)
1260 }
1261
1262 // Reserves space in the buffer based on the file size when available.
1263 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1264 let size = buffer_capacity_required(self);
1265 buf.try_reserve(size.unwrap_or(0))?;
1266 io::default_read_to_string(self, buf, size)
1267 }
1268}
1269#[stable(feature = "rust1", since = "1.0.0")]
1270impl Write for &File {
1271 /// Writes some bytes to the file.
1272 ///
1273 /// See [`Write::write`] docs for more info.
1274 ///
1275 /// # Platform-specific behavior
1276 ///
1277 /// This function currently corresponds to the `write` function on Unix and
1278 /// the `NtWriteFile` function on Windows. Note that this [may change in
1279 /// the future][changes].
1280 ///
1281 /// [changes]: io#platform-specific-behavior
1282 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1283 self.inner.write(buf)
1284 }
1285
1286 /// Like `write`, except that it writes into a slice of buffers.
1287 ///
1288 /// See [`Write::write_vectored`] docs for more info.
1289 ///
1290 /// # Platform-specific behavior
1291 ///
1292 /// This function currently corresponds to the `writev` function on Unix
1293 /// and falls back to the `write` implementation on Windows. Note that this
1294 /// [may change in the future][changes].
1295 ///
1296 /// [changes]: io#platform-specific-behavior
1297 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1298 self.inner.write_vectored(bufs)
1299 }
1300
1301 /// Determines if `File` has an efficient `write_vectored` implementation.
1302 ///
1303 /// See [`Write::is_write_vectored`] docs for more info.
1304 ///
1305 /// # Platform-specific behavior
1306 ///
1307 /// This function currently returns `true` on Unix an `false` on Windows.
1308 /// Note that this [may change in the future][changes].
1309 ///
1310 /// [changes]: io#platform-specific-behavior
1311 #[inline]
1312 fn is_write_vectored(&self) -> bool {
1313 self.inner.is_write_vectored()
1314 }
1315
1316 /// Flushes the file, ensuring that all intermediately buffered contents
1317 /// reach their destination.
1318 ///
1319 /// See [`Write::flush`] docs for more info.
1320 ///
1321 /// # Platform-specific behavior
1322 ///
1323 /// Since a `File` structure doesn't contain any buffers, this function is
1324 /// currently a no-op on Unix and Windows. Note that this [may change in
1325 /// the future][changes].
1326 ///
1327 /// [changes]: io#platform-specific-behavior
1328 #[inline]
1329 fn flush(&mut self) -> io::Result<()> {
1330 self.inner.flush()
1331 }
1332}
1333#[stable(feature = "rust1", since = "1.0.0")]
1334impl Seek for &File {
1335 /// Seek to an offset, in bytes in a file.
1336 ///
1337 /// See [`Seek::seek`] docs for more info.
1338 ///
1339 /// # Platform-specific behavior
1340 ///
1341 /// This function currently corresponds to the `lseek64` function on Unix
1342 /// and the `SetFilePointerEx` function on Windows. Note that this [may
1343 /// change in the future][changes].
1344 ///
1345 /// [changes]: io#platform-specific-behavior
1346 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1347 self.inner.seek(pos)
1348 }
1349
1350 /// Returns the length of this file (in bytes).
1351 ///
1352 /// See [`Seek::stream_len`] docs for more info.
1353 ///
1354 /// # Platform-specific behavior
1355 ///
1356 /// This function currently corresponds to the `statx` function on Linux
1357 /// (with fallbacks) and the `GetFileSizeEx` function on Windows. Note that
1358 /// this [may change in the future][changes].
1359 ///
1360 /// [changes]: io#platform-specific-behavior
1361 fn stream_len(&mut self) -> io::Result<u64> {
1362 if let Some(result) = self.inner.size() {
1363 return result;
1364 }
1365 io::stream_len_default(self)
1366 }
1367
1368 fn stream_position(&mut self) -> io::Result<u64> {
1369 self.inner.tell()
1370 }
1371}
1372
1373#[stable(feature = "rust1", since = "1.0.0")]
1374impl Read for File {
1375 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1376 (&*self).read(buf)
1377 }
1378 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1379 (&*self).read_vectored(bufs)
1380 }
1381 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1382 (&*self).read_buf(cursor)
1383 }
1384 #[inline]
1385 fn is_read_vectored(&self) -> bool {
1386 (&&*self).is_read_vectored()
1387 }
1388 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1389 (&*self).read_to_end(buf)
1390 }
1391 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1392 (&*self).read_to_string(buf)
1393 }
1394}
1395#[stable(feature = "rust1", since = "1.0.0")]
1396impl Write for File {
1397 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1398 (&*self).write(buf)
1399 }
1400 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1401 (&*self).write_vectored(bufs)
1402 }
1403 #[inline]
1404 fn is_write_vectored(&self) -> bool {
1405 (&&*self).is_write_vectored()
1406 }
1407 #[inline]
1408 fn flush(&mut self) -> io::Result<()> {
1409 (&*self).flush()
1410 }
1411}
1412#[stable(feature = "rust1", since = "1.0.0")]
1413impl Seek for File {
1414 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1415 (&*self).seek(pos)
1416 }
1417 fn stream_len(&mut self) -> io::Result<u64> {
1418 (&*self).stream_len()
1419 }
1420 fn stream_position(&mut self) -> io::Result<u64> {
1421 (&*self).stream_position()
1422 }
1423}
1424
1425#[stable(feature = "io_traits_arc", since = "1.73.0")]
1426impl Read for Arc<File> {
1427 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1428 (&**self).read(buf)
1429 }
1430 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1431 (&**self).read_vectored(bufs)
1432 }
1433 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1434 (&**self).read_buf(cursor)
1435 }
1436 #[inline]
1437 fn is_read_vectored(&self) -> bool {
1438 (&**self).is_read_vectored()
1439 }
1440 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1441 (&**self).read_to_end(buf)
1442 }
1443 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1444 (&**self).read_to_string(buf)
1445 }
1446}
1447#[stable(feature = "io_traits_arc", since = "1.73.0")]
1448impl Write for Arc<File> {
1449 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1450 (&**self).write(buf)
1451 }
1452 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1453 (&**self).write_vectored(bufs)
1454 }
1455 #[inline]
1456 fn is_write_vectored(&self) -> bool {
1457 (&**self).is_write_vectored()
1458 }
1459 #[inline]
1460 fn flush(&mut self) -> io::Result<()> {
1461 (&**self).flush()
1462 }
1463}
1464#[stable(feature = "io_traits_arc", since = "1.73.0")]
1465impl Seek for Arc<File> {
1466 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1467 (&**self).seek(pos)
1468 }
1469 fn stream_len(&mut self) -> io::Result<u64> {
1470 (&**self).stream_len()
1471 }
1472 fn stream_position(&mut self) -> io::Result<u64> {
1473 (&**self).stream_position()
1474 }
1475}
1476
1477impl OpenOptions {
1478 /// Creates a blank new set of options ready for configuration.
1479 ///
1480 /// All options are initially set to `false`.
1481 ///
1482 /// # Examples
1483 ///
1484 /// ```no_run
1485 /// use std::fs::OpenOptions;
1486 ///
1487 /// let mut options = OpenOptions::new();
1488 /// let file = options.read(true).open("foo.txt");
1489 /// ```
1490 #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 #[must_use]
1493 pub fn new() -> Self {
1494 OpenOptions(fs_imp::OpenOptions::new())
1495 }
1496
1497 /// Sets the option for read access.
1498 ///
1499 /// This option, when true, will indicate that the file should be
1500 /// `read`-able if opened.
1501 ///
1502 /// # Examples
1503 ///
1504 /// ```no_run
1505 /// use std::fs::OpenOptions;
1506 ///
1507 /// let file = OpenOptions::new().read(true).open("foo.txt");
1508 /// ```
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 pub fn read(&mut self, read: bool) -> &mut Self {
1511 self.0.read(read);
1512 self
1513 }
1514
1515 /// Sets the option for write access.
1516 ///
1517 /// This option, when true, will indicate that the file should be
1518 /// `write`-able if opened.
1519 ///
1520 /// If the file already exists, any write calls on it will overwrite its
1521 /// contents, without truncating it.
1522 ///
1523 /// # Examples
1524 ///
1525 /// ```no_run
1526 /// use std::fs::OpenOptions;
1527 ///
1528 /// let file = OpenOptions::new().write(true).open("foo.txt");
1529 /// ```
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 pub fn write(&mut self, write: bool) -> &mut Self {
1532 self.0.write(write);
1533 self
1534 }
1535
1536 /// Sets the option for the append mode.
1537 ///
1538 /// This option, when true, means that writes will append to a file instead
1539 /// of overwriting previous contents.
1540 /// Note that setting `.write(true).append(true)` has the same effect as
1541 /// setting only `.append(true)`.
1542 ///
1543 /// Append mode guarantees that writes will be positioned at the current end of file,
1544 /// even when there are other processes or threads appending to the same file. This is
1545 /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
1546 /// has a race between seeking and writing during which another writer can write, with
1547 /// our `write()` overwriting their data.
1548 ///
1549 /// Keep in mind that this does not necessarily guarantee that data appended by
1550 /// different processes or threads does not interleave. The amount of data accepted a
1551 /// single `write()` call depends on the operating system and file system. A
1552 /// successful `write()` is allowed to write only part of the given data, so even if
1553 /// you're careful to provide the whole message in a single call to `write()`, there
1554 /// is no guarantee that it will be written out in full. If you rely on the filesystem
1555 /// accepting the message in a single write, make sure that all data that belongs
1556 /// together is written in one operation. This can be done by concatenating strings
1557 /// before passing them to [`write()`].
1558 ///
1559 /// If a file is opened with both read and append access, beware that after
1560 /// opening, and after every write, the position for reading may be set at the
1561 /// end of the file. So, before writing, save the current position (using
1562 /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
1563 ///
1564 /// ## Note
1565 ///
1566 /// This function doesn't create the file if it doesn't exist. Use the
1567 /// [`OpenOptions::create`] method to do so.
1568 ///
1569 /// [`write()`]: Write::write "io::Write::write"
1570 /// [`flush()`]: Write::flush "io::Write::flush"
1571 /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
1572 /// [seek]: Seek::seek "io::Seek::seek"
1573 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
1574 /// [End]: SeekFrom::End "io::SeekFrom::End"
1575 ///
1576 /// # Examples
1577 ///
1578 /// ```no_run
1579 /// use std::fs::OpenOptions;
1580 ///
1581 /// let file = OpenOptions::new().append(true).open("foo.txt");
1582 /// ```
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 pub fn append(&mut self, append: bool) -> &mut Self {
1585 self.0.append(append);
1586 self
1587 }
1588
1589 /// Sets the option for truncating a previous file.
1590 ///
1591 /// If a file is successfully opened with this option set to true, it will truncate
1592 /// the file to 0 length if it already exists.
1593 ///
1594 /// The file must be opened with write access for truncate to work.
1595 ///
1596 /// # Examples
1597 ///
1598 /// ```no_run
1599 /// use std::fs::OpenOptions;
1600 ///
1601 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
1602 /// ```
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
1605 self.0.truncate(truncate);
1606 self
1607 }
1608
1609 /// Sets the option to create a new file, or open it if it already exists.
1610 ///
1611 /// In order for the file to be created, [`OpenOptions::write`] or
1612 /// [`OpenOptions::append`] access must be used.
1613 ///
1614 /// See also [`std::fs::write()`][self::write] for a simple function to
1615 /// create a file with some given data.
1616 ///
1617 /// # Examples
1618 ///
1619 /// ```no_run
1620 /// use std::fs::OpenOptions;
1621 ///
1622 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
1623 /// ```
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 pub fn create(&mut self, create: bool) -> &mut Self {
1626 self.0.create(create);
1627 self
1628 }
1629
1630 /// Sets the option to create a new file, failing if it already exists.
1631 ///
1632 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1633 /// way, if the call succeeds, the file returned is guaranteed to be new.
1634 /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
1635 /// or another error based on the situation. See [`OpenOptions::open`] for a
1636 /// non-exhaustive list of likely errors.
1637 ///
1638 /// This option is useful because it is atomic. Otherwise between checking
1639 /// whether a file exists and creating a new one, the file may have been
1640 /// created by another process (a [TOCTOU] race condition / attack).
1641 ///
1642 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1643 /// ignored.
1644 ///
1645 /// The file must be opened with write or append access in order to create
1646 /// a new file.
1647 ///
1648 /// [`.create()`]: OpenOptions::create
1649 /// [`.truncate()`]: OpenOptions::truncate
1650 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1651 /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
1652 ///
1653 /// # Examples
1654 ///
1655 /// ```no_run
1656 /// use std::fs::OpenOptions;
1657 ///
1658 /// let file = OpenOptions::new().write(true)
1659 /// .create_new(true)
1660 /// .open("foo.txt");
1661 /// ```
1662 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1663 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1664 self.0.create_new(create_new);
1665 self
1666 }
1667
1668 /// Opens a file at `path` with the options specified by `self`.
1669 ///
1670 /// # Errors
1671 ///
1672 /// This function will return an error under a number of different
1673 /// circumstances. Some of these error conditions are listed here, together
1674 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1675 /// part of the compatibility contract of the function.
1676 ///
1677 /// * [`NotFound`]: The specified file does not exist and neither `create`
1678 /// or `create_new` is set.
1679 /// * [`NotFound`]: One of the directory components of the file path does
1680 /// not exist.
1681 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1682 /// access rights for the file.
1683 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1684 /// directory components of the specified path.
1685 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1686 /// exists.
1687 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1688 /// without write access, no access mode set, etc.).
1689 ///
1690 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1691 /// * One of the directory components of the specified file path
1692 /// was not, in fact, a directory.
1693 /// * Filesystem-level errors: full disk, write permission
1694 /// requested on a read-only file system, exceeded disk quota, too many
1695 /// open files, too long filename, too many symbolic links in the
1696 /// specified path (Unix-like systems only), etc.
1697 ///
1698 /// # Examples
1699 ///
1700 /// ```no_run
1701 /// use std::fs::OpenOptions;
1702 ///
1703 /// let file = OpenOptions::new().read(true).open("foo.txt");
1704 /// ```
1705 ///
1706 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1707 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1708 /// [`NotFound`]: io::ErrorKind::NotFound
1709 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1712 self._open(path.as_ref())
1713 }
1714
1715 fn _open(&self, path: &Path) -> io::Result<File> {
1716 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1717 }
1718}
1719
1720impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1721 #[inline]
1722 fn as_inner(&self) -> &fs_imp::OpenOptions {
1723 &self.0
1724 }
1725}
1726
1727impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1728 #[inline]
1729 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1730 &mut self.0
1731 }
1732}
1733
1734impl Metadata {
1735 /// Returns the file type for this metadata.
1736 ///
1737 /// # Examples
1738 ///
1739 /// ```no_run
1740 /// fn main() -> std::io::Result<()> {
1741 /// use std::fs;
1742 ///
1743 /// let metadata = fs::metadata("foo.txt")?;
1744 ///
1745 /// println!("{:?}", metadata.file_type());
1746 /// Ok(())
1747 /// }
1748 /// ```
1749 #[must_use]
1750 #[stable(feature = "file_type", since = "1.1.0")]
1751 pub fn file_type(&self) -> FileType {
1752 FileType(self.0.file_type())
1753 }
1754
1755 /// Returns `true` if this metadata is for a directory. The
1756 /// result is mutually exclusive to the result of
1757 /// [`Metadata::is_file`], and will be false for symlink metadata
1758 /// obtained from [`symlink_metadata`].
1759 ///
1760 /// # Examples
1761 ///
1762 /// ```no_run
1763 /// fn main() -> std::io::Result<()> {
1764 /// use std::fs;
1765 ///
1766 /// let metadata = fs::metadata("foo.txt")?;
1767 ///
1768 /// assert!(!metadata.is_dir());
1769 /// Ok(())
1770 /// }
1771 /// ```
1772 #[must_use]
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 pub fn is_dir(&self) -> bool {
1775 self.file_type().is_dir()
1776 }
1777
1778 /// Returns `true` if this metadata is for a regular file. The
1779 /// result is mutually exclusive to the result of
1780 /// [`Metadata::is_dir`], and will be false for symlink metadata
1781 /// obtained from [`symlink_metadata`].
1782 ///
1783 /// When the goal is simply to read from (or write to) the source, the most
1784 /// reliable way to test the source can be read (or written to) is to open
1785 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1786 /// a Unix-like system for example. See [`File::open`] or
1787 /// [`OpenOptions::open`] for more information.
1788 ///
1789 /// # Examples
1790 ///
1791 /// ```no_run
1792 /// use std::fs;
1793 ///
1794 /// fn main() -> std::io::Result<()> {
1795 /// let metadata = fs::metadata("foo.txt")?;
1796 ///
1797 /// assert!(metadata.is_file());
1798 /// Ok(())
1799 /// }
1800 /// ```
1801 #[must_use]
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 pub fn is_file(&self) -> bool {
1804 self.file_type().is_file()
1805 }
1806
1807 /// Returns `true` if this metadata is for a symbolic link.
1808 ///
1809 /// # Examples
1810 ///
1811 #[cfg_attr(unix, doc = "```no_run")]
1812 #[cfg_attr(not(unix), doc = "```ignore")]
1813 /// use std::fs;
1814 /// use std::path::Path;
1815 /// use std::os::unix::fs::symlink;
1816 ///
1817 /// fn main() -> std::io::Result<()> {
1818 /// let link_path = Path::new("link");
1819 /// symlink("/origin_does_not_exist/", link_path)?;
1820 ///
1821 /// let metadata = fs::symlink_metadata(link_path)?;
1822 ///
1823 /// assert!(metadata.is_symlink());
1824 /// Ok(())
1825 /// }
1826 /// ```
1827 #[must_use]
1828 #[stable(feature = "is_symlink", since = "1.58.0")]
1829 pub fn is_symlink(&self) -> bool {
1830 self.file_type().is_symlink()
1831 }
1832
1833 /// Returns the size of the file, in bytes, this metadata is for.
1834 ///
1835 /// # Examples
1836 ///
1837 /// ```no_run
1838 /// use std::fs;
1839 ///
1840 /// fn main() -> std::io::Result<()> {
1841 /// let metadata = fs::metadata("foo.txt")?;
1842 ///
1843 /// assert_eq!(0, metadata.len());
1844 /// Ok(())
1845 /// }
1846 /// ```
1847 #[must_use]
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 pub fn len(&self) -> u64 {
1850 self.0.size()
1851 }
1852
1853 /// Returns the permissions of the file this metadata is for.
1854 ///
1855 /// # Examples
1856 ///
1857 /// ```no_run
1858 /// use std::fs;
1859 ///
1860 /// fn main() -> std::io::Result<()> {
1861 /// let metadata = fs::metadata("foo.txt")?;
1862 ///
1863 /// assert!(!metadata.permissions().readonly());
1864 /// Ok(())
1865 /// }
1866 /// ```
1867 #[must_use]
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 pub fn permissions(&self) -> Permissions {
1870 Permissions(self.0.perm())
1871 }
1872
1873 /// Returns the last modification time listed in this metadata.
1874 ///
1875 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1876 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1877 ///
1878 /// # Errors
1879 ///
1880 /// This field might not be available on all platforms, and will return an
1881 /// `Err` on platforms where it is not available.
1882 ///
1883 /// # Examples
1884 ///
1885 /// ```no_run
1886 /// use std::fs;
1887 ///
1888 /// fn main() -> std::io::Result<()> {
1889 /// let metadata = fs::metadata("foo.txt")?;
1890 ///
1891 /// if let Ok(time) = metadata.modified() {
1892 /// println!("{time:?}");
1893 /// } else {
1894 /// println!("Not supported on this platform");
1895 /// }
1896 /// Ok(())
1897 /// }
1898 /// ```
1899 #[doc(alias = "mtime", alias = "ftLastWriteTime")]
1900 #[stable(feature = "fs_time", since = "1.10.0")]
1901 pub fn modified(&self) -> io::Result<SystemTime> {
1902 self.0.modified().map(FromInner::from_inner)
1903 }
1904
1905 /// Returns the last access time of this metadata.
1906 ///
1907 /// The returned value corresponds to the `atime` field of `stat` on Unix
1908 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1909 ///
1910 /// Note that not all platforms will keep this field update in a file's
1911 /// metadata, for example Windows has an option to disable updating this
1912 /// time when files are accessed and Linux similarly has `noatime`.
1913 ///
1914 /// # Errors
1915 ///
1916 /// This field might not be available on all platforms, and will return an
1917 /// `Err` on platforms where it is not available.
1918 ///
1919 /// # Examples
1920 ///
1921 /// ```no_run
1922 /// use std::fs;
1923 ///
1924 /// fn main() -> std::io::Result<()> {
1925 /// let metadata = fs::metadata("foo.txt")?;
1926 ///
1927 /// if let Ok(time) = metadata.accessed() {
1928 /// println!("{time:?}");
1929 /// } else {
1930 /// println!("Not supported on this platform");
1931 /// }
1932 /// Ok(())
1933 /// }
1934 /// ```
1935 #[doc(alias = "atime", alias = "ftLastAccessTime")]
1936 #[stable(feature = "fs_time", since = "1.10.0")]
1937 pub fn accessed(&self) -> io::Result<SystemTime> {
1938 self.0.accessed().map(FromInner::from_inner)
1939 }
1940
1941 /// Returns the creation time listed in this metadata.
1942 ///
1943 /// The returned value corresponds to the `btime` field of `statx` on
1944 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1945 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1946 ///
1947 /// # Errors
1948 ///
1949 /// This field might not be available on all platforms, and will return an
1950 /// `Err` on platforms or filesystems where it is not available.
1951 ///
1952 /// # Examples
1953 ///
1954 /// ```no_run
1955 /// use std::fs;
1956 ///
1957 /// fn main() -> std::io::Result<()> {
1958 /// let metadata = fs::metadata("foo.txt")?;
1959 ///
1960 /// if let Ok(time) = metadata.created() {
1961 /// println!("{time:?}");
1962 /// } else {
1963 /// println!("Not supported on this platform or filesystem");
1964 /// }
1965 /// Ok(())
1966 /// }
1967 /// ```
1968 #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
1969 #[stable(feature = "fs_time", since = "1.10.0")]
1970 pub fn created(&self) -> io::Result<SystemTime> {
1971 self.0.created().map(FromInner::from_inner)
1972 }
1973}
1974
1975#[stable(feature = "std_debug", since = "1.16.0")]
1976impl fmt::Debug for Metadata {
1977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1978 let mut debug = f.debug_struct("Metadata");
1979 debug.field("file_type", &self.file_type());
1980 debug.field("permissions", &self.permissions());
1981 debug.field("len", &self.len());
1982 if let Ok(modified) = self.modified() {
1983 debug.field("modified", &modified);
1984 }
1985 if let Ok(accessed) = self.accessed() {
1986 debug.field("accessed", &accessed);
1987 }
1988 if let Ok(created) = self.created() {
1989 debug.field("created", &created);
1990 }
1991 debug.finish_non_exhaustive()
1992 }
1993}
1994
1995impl AsInner<fs_imp::FileAttr> for Metadata {
1996 #[inline]
1997 fn as_inner(&self) -> &fs_imp::FileAttr {
1998 &self.0
1999 }
2000}
2001
2002impl FromInner<fs_imp::FileAttr> for Metadata {
2003 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2004 Metadata(attr)
2005 }
2006}
2007
2008impl FileTimes {
2009 /// Creates a new `FileTimes` with no times set.
2010 ///
2011 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2012 #[stable(feature = "file_set_times", since = "1.75.0")]
2013 pub fn new() -> Self {
2014 Self::default()
2015 }
2016
2017 /// Set the last access time of a file.
2018 #[stable(feature = "file_set_times", since = "1.75.0")]
2019 pub fn set_accessed(mut self, t: SystemTime) -> Self {
2020 self.0.set_accessed(t.into_inner());
2021 self
2022 }
2023
2024 /// Set the last modified time of a file.
2025 #[stable(feature = "file_set_times", since = "1.75.0")]
2026 pub fn set_modified(mut self, t: SystemTime) -> Self {
2027 self.0.set_modified(t.into_inner());
2028 self
2029 }
2030}
2031
2032impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2033 fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2034 &mut self.0
2035 }
2036}
2037
2038// For implementing OS extension traits in `std::os`
2039#[stable(feature = "file_set_times", since = "1.75.0")]
2040impl Sealed for FileTimes {}
2041
2042impl Permissions {
2043 /// Returns `true` if these permissions describe a readonly (unwritable) file.
2044 ///
2045 /// # Note
2046 ///
2047 /// This function does not take Access Control Lists (ACLs), Unix group
2048 /// membership and other nuances into account.
2049 /// Therefore the return value of this function cannot be relied upon
2050 /// to predict whether attempts to read or write the file will actually succeed.
2051 ///
2052 /// # Windows
2053 ///
2054 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2055 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2056 /// but the user may still have permission to change this flag. If
2057 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2058 /// to lack of write permission.
2059 /// The behavior of this attribute for directories depends on the Windows
2060 /// version.
2061 ///
2062 /// # Unix (including macOS)
2063 ///
2064 /// On Unix-based platforms this checks if *any* of the owner, group or others
2065 /// write permission bits are set. It does not consider anything else, including:
2066 ///
2067 /// * Whether the current user is in the file's assigned group.
2068 /// * Permissions granted by ACL.
2069 /// * That `root` user can write to files that do not have any write bits set.
2070 /// * Writable files on a filesystem that is mounted read-only.
2071 ///
2072 /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2073 /// also does not read ACLs.
2074 ///
2075 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2076 ///
2077 /// # Examples
2078 ///
2079 /// ```no_run
2080 /// use std::fs::File;
2081 ///
2082 /// fn main() -> std::io::Result<()> {
2083 /// let mut f = File::create("foo.txt")?;
2084 /// let metadata = f.metadata()?;
2085 ///
2086 /// assert_eq!(false, metadata.permissions().readonly());
2087 /// Ok(())
2088 /// }
2089 /// ```
2090 #[must_use = "call `set_readonly` to modify the readonly flag"]
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 pub fn readonly(&self) -> bool {
2093 self.0.readonly()
2094 }
2095
2096 /// Modifies the readonly flag for this set of permissions. If the
2097 /// `readonly` argument is `true`, using the resulting `Permission` will
2098 /// update file permissions to forbid writing. Conversely, if it's `false`,
2099 /// using the resulting `Permission` will update file permissions to allow
2100 /// writing.
2101 ///
2102 /// This operation does **not** modify the files attributes. This only
2103 /// changes the in-memory value of these attributes for this `Permissions`
2104 /// instance. To modify the files attributes use the [`set_permissions`]
2105 /// function which commits these attribute changes to the file.
2106 ///
2107 /// # Note
2108 ///
2109 /// `set_readonly(false)` makes the file *world-writable* on Unix.
2110 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2111 ///
2112 /// It also does not take Access Control Lists (ACLs) or Unix group
2113 /// membership into account.
2114 ///
2115 /// # Windows
2116 ///
2117 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2118 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2119 /// but the user may still have permission to change this flag. If
2120 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2121 /// the user does not have permission to write to the file.
2122 ///
2123 /// In Windows 7 and earlier this attribute prevents deleting empty
2124 /// directories. It does not prevent modifying the directory contents.
2125 /// On later versions of Windows this attribute is ignored for directories.
2126 ///
2127 /// # Unix (including macOS)
2128 ///
2129 /// On Unix-based platforms this sets or clears the write access bit for
2130 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2131 /// or `chmod a-w <file>` respectively. The latter will grant write access
2132 /// to all users! You can use the [`PermissionsExt`] trait on Unix
2133 /// to avoid this issue.
2134 ///
2135 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2136 ///
2137 /// # Examples
2138 ///
2139 /// ```no_run
2140 /// use std::fs::File;
2141 ///
2142 /// fn main() -> std::io::Result<()> {
2143 /// let f = File::create("foo.txt")?;
2144 /// let metadata = f.metadata()?;
2145 /// let mut permissions = metadata.permissions();
2146 ///
2147 /// permissions.set_readonly(true);
2148 ///
2149 /// // filesystem doesn't change, only the in memory state of the
2150 /// // readonly permission
2151 /// assert_eq!(false, metadata.permissions().readonly());
2152 ///
2153 /// // just this particular `permissions`.
2154 /// assert_eq!(true, permissions.readonly());
2155 /// Ok(())
2156 /// }
2157 /// ```
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 pub fn set_readonly(&mut self, readonly: bool) {
2160 self.0.set_readonly(readonly)
2161 }
2162}
2163
2164impl FileType {
2165 /// Tests whether this file type represents a directory. The
2166 /// result is mutually exclusive to the results of
2167 /// [`is_file`] and [`is_symlink`]; only zero or one of these
2168 /// tests may pass.
2169 ///
2170 /// [`is_file`]: FileType::is_file
2171 /// [`is_symlink`]: FileType::is_symlink
2172 ///
2173 /// # Examples
2174 ///
2175 /// ```no_run
2176 /// fn main() -> std::io::Result<()> {
2177 /// use std::fs;
2178 ///
2179 /// let metadata = fs::metadata("foo.txt")?;
2180 /// let file_type = metadata.file_type();
2181 ///
2182 /// assert_eq!(file_type.is_dir(), false);
2183 /// Ok(())
2184 /// }
2185 /// ```
2186 #[must_use]
2187 #[stable(feature = "file_type", since = "1.1.0")]
2188 pub fn is_dir(&self) -> bool {
2189 self.0.is_dir()
2190 }
2191
2192 /// Tests whether this file type represents a regular file.
2193 /// The result is mutually exclusive to the results of
2194 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2195 /// tests may pass.
2196 ///
2197 /// When the goal is simply to read from (or write to) the source, the most
2198 /// reliable way to test the source can be read (or written to) is to open
2199 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2200 /// a Unix-like system for example. See [`File::open`] or
2201 /// [`OpenOptions::open`] for more information.
2202 ///
2203 /// [`is_dir`]: FileType::is_dir
2204 /// [`is_symlink`]: FileType::is_symlink
2205 ///
2206 /// # Examples
2207 ///
2208 /// ```no_run
2209 /// fn main() -> std::io::Result<()> {
2210 /// use std::fs;
2211 ///
2212 /// let metadata = fs::metadata("foo.txt")?;
2213 /// let file_type = metadata.file_type();
2214 ///
2215 /// assert_eq!(file_type.is_file(), true);
2216 /// Ok(())
2217 /// }
2218 /// ```
2219 #[must_use]
2220 #[stable(feature = "file_type", since = "1.1.0")]
2221 pub fn is_file(&self) -> bool {
2222 self.0.is_file()
2223 }
2224
2225 /// Tests whether this file type represents a symbolic link.
2226 /// The result is mutually exclusive to the results of
2227 /// [`is_dir`] and [`is_file`]; only zero or one of these
2228 /// tests may pass.
2229 ///
2230 /// The underlying [`Metadata`] struct needs to be retrieved
2231 /// with the [`fs::symlink_metadata`] function and not the
2232 /// [`fs::metadata`] function. The [`fs::metadata`] function
2233 /// follows symbolic links, so [`is_symlink`] would always
2234 /// return `false` for the target file.
2235 ///
2236 /// [`fs::metadata`]: metadata
2237 /// [`fs::symlink_metadata`]: symlink_metadata
2238 /// [`is_dir`]: FileType::is_dir
2239 /// [`is_file`]: FileType::is_file
2240 /// [`is_symlink`]: FileType::is_symlink
2241 ///
2242 /// # Examples
2243 ///
2244 /// ```no_run
2245 /// use std::fs;
2246 ///
2247 /// fn main() -> std::io::Result<()> {
2248 /// let metadata = fs::symlink_metadata("foo.txt")?;
2249 /// let file_type = metadata.file_type();
2250 ///
2251 /// assert_eq!(file_type.is_symlink(), false);
2252 /// Ok(())
2253 /// }
2254 /// ```
2255 #[must_use]
2256 #[stable(feature = "file_type", since = "1.1.0")]
2257 pub fn is_symlink(&self) -> bool {
2258 self.0.is_symlink()
2259 }
2260}
2261
2262#[stable(feature = "std_debug", since = "1.16.0")]
2263impl fmt::Debug for FileType {
2264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2265 f.debug_struct("FileType")
2266 .field("is_file", &self.is_file())
2267 .field("is_dir", &self.is_dir())
2268 .field("is_symlink", &self.is_symlink())
2269 .finish_non_exhaustive()
2270 }
2271}
2272
2273impl AsInner<fs_imp::FileType> for FileType {
2274 #[inline]
2275 fn as_inner(&self) -> &fs_imp::FileType {
2276 &self.0
2277 }
2278}
2279
2280impl FromInner<fs_imp::FilePermissions> for Permissions {
2281 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2282 Permissions(f)
2283 }
2284}
2285
2286impl AsInner<fs_imp::FilePermissions> for Permissions {
2287 #[inline]
2288 fn as_inner(&self) -> &fs_imp::FilePermissions {
2289 &self.0
2290 }
2291}
2292
2293#[stable(feature = "rust1", since = "1.0.0")]
2294impl Iterator for ReadDir {
2295 type Item = io::Result<DirEntry>;
2296
2297 fn next(&mut self) -> Option<io::Result<DirEntry>> {
2298 self.0.next().map(|entry| entry.map(DirEntry))
2299 }
2300}
2301
2302impl DirEntry {
2303 /// Returns the full path to the file that this entry represents.
2304 ///
2305 /// The full path is created by joining the original path to `read_dir`
2306 /// with the filename of this entry.
2307 ///
2308 /// # Examples
2309 ///
2310 /// ```no_run
2311 /// use std::fs;
2312 ///
2313 /// fn main() -> std::io::Result<()> {
2314 /// for entry in fs::read_dir(".")? {
2315 /// let dir = entry?;
2316 /// println!("{:?}", dir.path());
2317 /// }
2318 /// Ok(())
2319 /// }
2320 /// ```
2321 ///
2322 /// This prints output like:
2323 ///
2324 /// ```text
2325 /// "./whatever.txt"
2326 /// "./foo.html"
2327 /// "./hello_world.rs"
2328 /// ```
2329 ///
2330 /// The exact text, of course, depends on what files you have in `.`.
2331 #[must_use]
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 pub fn path(&self) -> PathBuf {
2334 self.0.path()
2335 }
2336
2337 /// Returns the metadata for the file that this entry points at.
2338 ///
2339 /// This function will not traverse symlinks if this entry points at a
2340 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2341 ///
2342 /// [`fs::metadata`]: metadata
2343 /// [`fs::File::metadata`]: File::metadata
2344 ///
2345 /// # Platform-specific behavior
2346 ///
2347 /// On Windows this function is cheap to call (no extra system calls
2348 /// needed), but on Unix platforms this function is the equivalent of
2349 /// calling `symlink_metadata` on the path.
2350 ///
2351 /// # Examples
2352 ///
2353 /// ```
2354 /// use std::fs;
2355 ///
2356 /// if let Ok(entries) = fs::read_dir(".") {
2357 /// for entry in entries {
2358 /// if let Ok(entry) = entry {
2359 /// // Here, `entry` is a `DirEntry`.
2360 /// if let Ok(metadata) = entry.metadata() {
2361 /// // Now let's show our entry's permissions!
2362 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
2363 /// } else {
2364 /// println!("Couldn't get metadata for {:?}", entry.path());
2365 /// }
2366 /// }
2367 /// }
2368 /// }
2369 /// ```
2370 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2371 pub fn metadata(&self) -> io::Result<Metadata> {
2372 self.0.metadata().map(Metadata)
2373 }
2374
2375 /// Returns the file type for the file that this entry points at.
2376 ///
2377 /// This function will not traverse symlinks if this entry points at a
2378 /// symlink.
2379 ///
2380 /// # Platform-specific behavior
2381 ///
2382 /// On Windows and most Unix platforms this function is free (no extra
2383 /// system calls needed), but some Unix platforms may require the equivalent
2384 /// call to `symlink_metadata` to learn about the target file type.
2385 ///
2386 /// # Examples
2387 ///
2388 /// ```
2389 /// use std::fs;
2390 ///
2391 /// if let Ok(entries) = fs::read_dir(".") {
2392 /// for entry in entries {
2393 /// if let Ok(entry) = entry {
2394 /// // Here, `entry` is a `DirEntry`.
2395 /// if let Ok(file_type) = entry.file_type() {
2396 /// // Now let's show our entry's file type!
2397 /// println!("{:?}: {:?}", entry.path(), file_type);
2398 /// } else {
2399 /// println!("Couldn't get file type for {:?}", entry.path());
2400 /// }
2401 /// }
2402 /// }
2403 /// }
2404 /// ```
2405 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2406 pub fn file_type(&self) -> io::Result<FileType> {
2407 self.0.file_type().map(FileType)
2408 }
2409
2410 /// Returns the file name of this directory entry without any
2411 /// leading path component(s).
2412 ///
2413 /// As an example,
2414 /// the output of the function will result in "foo" for all the following paths:
2415 /// - "./foo"
2416 /// - "/the/foo"
2417 /// - "../../foo"
2418 ///
2419 /// # Examples
2420 ///
2421 /// ```
2422 /// use std::fs;
2423 ///
2424 /// if let Ok(entries) = fs::read_dir(".") {
2425 /// for entry in entries {
2426 /// if let Ok(entry) = entry {
2427 /// // Here, `entry` is a `DirEntry`.
2428 /// println!("{:?}", entry.file_name());
2429 /// }
2430 /// }
2431 /// }
2432 /// ```
2433 #[must_use]
2434 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2435 pub fn file_name(&self) -> OsString {
2436 self.0.file_name()
2437 }
2438}
2439
2440#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2441impl fmt::Debug for DirEntry {
2442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2443 f.debug_tuple("DirEntry").field(&self.path()).finish()
2444 }
2445}
2446
2447impl AsInner<fs_imp::DirEntry> for DirEntry {
2448 #[inline]
2449 fn as_inner(&self) -> &fs_imp::DirEntry {
2450 &self.0
2451 }
2452}
2453
2454/// Removes a file from the filesystem.
2455///
2456/// Note that there is no
2457/// guarantee that the file is immediately deleted (e.g., depending on
2458/// platform, other open file descriptors may prevent immediate removal).
2459///
2460/// # Platform-specific behavior
2461///
2462/// This function currently corresponds to the `unlink` function on Unix.
2463/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2464/// Note that, this [may change in the future][changes].
2465///
2466/// [changes]: io#platform-specific-behavior
2467///
2468/// # Errors
2469///
2470/// This function will return an error in the following situations, but is not
2471/// limited to just these cases:
2472///
2473/// * `path` points to a directory.
2474/// * The file doesn't exist.
2475/// * The user lacks permissions to remove the file.
2476///
2477/// This function will only ever return an error of kind `NotFound` if the given
2478/// path does not exist. Note that the inverse is not true,
2479/// ie. if a path does not exist, its removal may fail for a number of reasons,
2480/// such as insufficient permissions.
2481///
2482/// # Examples
2483///
2484/// ```no_run
2485/// use std::fs;
2486///
2487/// fn main() -> std::io::Result<()> {
2488/// fs::remove_file("a.txt")?;
2489/// Ok(())
2490/// }
2491/// ```
2492#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
2493#[stable(feature = "rust1", since = "1.0.0")]
2494pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
2495 fs_imp::remove_file(path.as_ref())
2496}
2497
2498/// Given a path, queries the file system to get information about a file,
2499/// directory, etc.
2500///
2501/// This function will traverse symbolic links to query information about the
2502/// destination file.
2503///
2504/// # Platform-specific behavior
2505///
2506/// This function currently corresponds to the `stat` function on Unix
2507/// and the `GetFileInformationByHandle` function on Windows.
2508/// Note that, this [may change in the future][changes].
2509///
2510/// [changes]: io#platform-specific-behavior
2511///
2512/// # Errors
2513///
2514/// This function will return an error in the following situations, but is not
2515/// limited to just these cases:
2516///
2517/// * The user lacks permissions to perform `metadata` call on `path`.
2518/// * `path` does not exist.
2519///
2520/// # Examples
2521///
2522/// ```rust,no_run
2523/// use std::fs;
2524///
2525/// fn main() -> std::io::Result<()> {
2526/// let attr = fs::metadata("/some/file/path.txt")?;
2527/// // inspect attr ...
2528/// Ok(())
2529/// }
2530/// ```
2531#[doc(alias = "stat")]
2532#[stable(feature = "rust1", since = "1.0.0")]
2533pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2534 fs_imp::metadata(path.as_ref()).map(Metadata)
2535}
2536
2537/// Queries the metadata about a file without following symlinks.
2538///
2539/// # Platform-specific behavior
2540///
2541/// This function currently corresponds to the `lstat` function on Unix
2542/// and the `GetFileInformationByHandle` function on Windows.
2543/// Note that, this [may change in the future][changes].
2544///
2545/// [changes]: io#platform-specific-behavior
2546///
2547/// # Errors
2548///
2549/// This function will return an error in the following situations, but is not
2550/// limited to just these cases:
2551///
2552/// * The user lacks permissions to perform `metadata` call on `path`.
2553/// * `path` does not exist.
2554///
2555/// # Examples
2556///
2557/// ```rust,no_run
2558/// use std::fs;
2559///
2560/// fn main() -> std::io::Result<()> {
2561/// let attr = fs::symlink_metadata("/some/file/path.txt")?;
2562/// // inspect attr ...
2563/// Ok(())
2564/// }
2565/// ```
2566#[doc(alias = "lstat")]
2567#[stable(feature = "symlink_metadata", since = "1.1.0")]
2568pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2569 fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
2570}
2571
2572/// Renames a file or directory to a new name, replacing the original file if
2573/// `to` already exists.
2574///
2575/// This will not work if the new name is on a different mount point.
2576///
2577/// # Platform-specific behavior
2578///
2579/// This function currently corresponds to the `rename` function on Unix
2580/// and the `MoveFileExW` or `SetFileInformationByHandle` function on Windows.
2581///
2582/// Because of this, the behavior when both `from` and `to` exist differs. On
2583/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
2584/// `from` is not a directory, `to` must also be not a directory. The behavior
2585/// on Windows is the same on Windows 10 1607 and higher if `FileRenameInfoEx`
2586/// is supported by the filesystem; otherwise, `from` can be anything, but
2587/// `to` must *not* be a directory.
2588///
2589/// Note that, this [may change in the future][changes].
2590///
2591/// [changes]: io#platform-specific-behavior
2592///
2593/// # Errors
2594///
2595/// This function will return an error in the following situations, but is not
2596/// limited to just these cases:
2597///
2598/// * `from` does not exist.
2599/// * The user lacks permissions to view contents.
2600/// * `from` and `to` are on separate filesystems.
2601///
2602/// # Examples
2603///
2604/// ```no_run
2605/// use std::fs;
2606///
2607/// fn main() -> std::io::Result<()> {
2608/// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
2609/// Ok(())
2610/// }
2611/// ```
2612#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
2613#[stable(feature = "rust1", since = "1.0.0")]
2614pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
2615 fs_imp::rename(from.as_ref(), to.as_ref())
2616}
2617
2618/// Copies the contents of one file to another. This function will also
2619/// copy the permission bits of the original file to the destination file.
2620///
2621/// This function will **overwrite** the contents of `to`.
2622///
2623/// Note that if `from` and `to` both point to the same file, then the file
2624/// will likely get truncated by this operation.
2625///
2626/// On success, the total number of bytes copied is returned and it is equal to
2627/// the length of the `to` file as reported by `metadata`.
2628///
2629/// If you want to copy the contents of one file to another and you’re
2630/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
2631///
2632/// # Platform-specific behavior
2633///
2634/// This function currently corresponds to the `open` function in Unix
2635/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
2636/// `O_CLOEXEC` is set for returned file descriptors.
2637///
2638/// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
2639/// and falls back to reading and writing if that is not possible.
2640///
2641/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
2642/// NTFS streams are copied but only the size of the main stream is returned by
2643/// this function.
2644///
2645/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
2646///
2647/// Note that platform-specific behavior [may change in the future][changes].
2648///
2649/// [changes]: io#platform-specific-behavior
2650///
2651/// # Errors
2652///
2653/// This function will return an error in the following situations, but is not
2654/// limited to just these cases:
2655///
2656/// * `from` is neither a regular file nor a symlink to a regular file.
2657/// * `from` does not exist.
2658/// * The current process does not have the permission rights to read
2659/// `from` or write `to`.
2660/// * The parent directory of `to` doesn't exist.
2661///
2662/// # Examples
2663///
2664/// ```no_run
2665/// use std::fs;
2666///
2667/// fn main() -> std::io::Result<()> {
2668/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
2669/// Ok(())
2670/// }
2671/// ```
2672#[doc(alias = "cp")]
2673#[doc(alias = "CopyFile", alias = "CopyFileEx")]
2674#[doc(alias = "fclonefileat", alias = "fcopyfile")]
2675#[stable(feature = "rust1", since = "1.0.0")]
2676pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
2677 fs_imp::copy(from.as_ref(), to.as_ref())
2678}
2679
2680/// Creates a new hard link on the filesystem.
2681///
2682/// The `link` path will be a link pointing to the `original` path. Note that
2683/// systems often require these two paths to both be located on the same
2684/// filesystem.
2685///
2686/// If `original` names a symbolic link, it is platform-specific whether the
2687/// symbolic link is followed. On platforms where it's possible to not follow
2688/// it, it is not followed, and the created hard link points to the symbolic
2689/// link itself.
2690///
2691/// # Platform-specific behavior
2692///
2693/// This function currently corresponds the `CreateHardLink` function on Windows.
2694/// On most Unix systems, it corresponds to the `linkat` function with no flags.
2695/// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2696/// On MacOS, it uses the `linkat` function if it is available, but on very old
2697/// systems where `linkat` is not available, `link` is selected at runtime instead.
2698/// Note that, this [may change in the future][changes].
2699///
2700/// [changes]: io#platform-specific-behavior
2701///
2702/// # Errors
2703///
2704/// This function will return an error in the following situations, but is not
2705/// limited to just these cases:
2706///
2707/// * The `original` path is not a file or doesn't exist.
2708/// * The 'link' path already exists.
2709///
2710/// # Examples
2711///
2712/// ```no_run
2713/// use std::fs;
2714///
2715/// fn main() -> std::io::Result<()> {
2716/// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2717/// Ok(())
2718/// }
2719/// ```
2720#[doc(alias = "CreateHardLink", alias = "linkat")]
2721#[stable(feature = "rust1", since = "1.0.0")]
2722pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2723 fs_imp::hard_link(original.as_ref(), link.as_ref())
2724}
2725
2726/// Creates a new symbolic link on the filesystem.
2727///
2728/// The `link` path will be a symbolic link pointing to the `original` path.
2729/// On Windows, this will be a file symlink, not a directory symlink;
2730/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2731/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2732/// used instead to make the intent explicit.
2733///
2734/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2735/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2736/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2737///
2738/// # Examples
2739///
2740/// ```no_run
2741/// use std::fs;
2742///
2743/// fn main() -> std::io::Result<()> {
2744/// fs::soft_link("a.txt", "b.txt")?;
2745/// Ok(())
2746/// }
2747/// ```
2748#[stable(feature = "rust1", since = "1.0.0")]
2749#[deprecated(
2750 since = "1.1.0",
2751 note = "replaced with std::os::unix::fs::symlink and \
2752 std::os::windows::fs::{symlink_file, symlink_dir}"
2753)]
2754pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2755 fs_imp::symlink(original.as_ref(), link.as_ref())
2756}
2757
2758/// Reads a symbolic link, returning the file that the link points to.
2759///
2760/// # Platform-specific behavior
2761///
2762/// This function currently corresponds to the `readlink` function on Unix
2763/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2764/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2765/// Note that, this [may change in the future][changes].
2766///
2767/// [changes]: io#platform-specific-behavior
2768///
2769/// # Errors
2770///
2771/// This function will return an error in the following situations, but is not
2772/// limited to just these cases:
2773///
2774/// * `path` is not a symbolic link.
2775/// * `path` does not exist.
2776///
2777/// # Examples
2778///
2779/// ```no_run
2780/// use std::fs;
2781///
2782/// fn main() -> std::io::Result<()> {
2783/// let path = fs::read_link("a.txt")?;
2784/// Ok(())
2785/// }
2786/// ```
2787#[stable(feature = "rust1", since = "1.0.0")]
2788pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2789 fs_imp::read_link(path.as_ref())
2790}
2791
2792/// Returns the canonical, absolute form of a path with all intermediate
2793/// components normalized and symbolic links resolved.
2794///
2795/// # Platform-specific behavior
2796///
2797/// This function currently corresponds to the `realpath` function on Unix
2798/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2799/// Note that this [may change in the future][changes].
2800///
2801/// On Windows, this converts the path to use [extended length path][path]
2802/// syntax, which allows your program to use longer path names, but means you
2803/// can only join backslash-delimited paths to it, and it may be incompatible
2804/// with other applications (if passed to the application on the command-line,
2805/// or written to a file another application may read).
2806///
2807/// [changes]: io#platform-specific-behavior
2808/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2809///
2810/// # Errors
2811///
2812/// This function will return an error in the following situations, but is not
2813/// limited to just these cases:
2814///
2815/// * `path` does not exist.
2816/// * A non-final component in path is not a directory.
2817///
2818/// # Examples
2819///
2820/// ```no_run
2821/// use std::fs;
2822///
2823/// fn main() -> std::io::Result<()> {
2824/// let path = fs::canonicalize("../a/../foo.txt")?;
2825/// Ok(())
2826/// }
2827/// ```
2828#[doc(alias = "realpath")]
2829#[doc(alias = "GetFinalPathNameByHandle")]
2830#[stable(feature = "fs_canonicalize", since = "1.5.0")]
2831pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2832 fs_imp::canonicalize(path.as_ref())
2833}
2834
2835/// Creates a new, empty directory at the provided path
2836///
2837/// # Platform-specific behavior
2838///
2839/// This function currently corresponds to the `mkdir` function on Unix
2840/// and the `CreateDirectoryW` function on Windows.
2841/// Note that, this [may change in the future][changes].
2842///
2843/// [changes]: io#platform-specific-behavior
2844///
2845/// **NOTE**: If a parent of the given path doesn't exist, this function will
2846/// return an error. To create a directory and all its missing parents at the
2847/// same time, use the [`create_dir_all`] function.
2848///
2849/// # Errors
2850///
2851/// This function will return an error in the following situations, but is not
2852/// limited to just these cases:
2853///
2854/// * User lacks permissions to create directory at `path`.
2855/// * A parent of the given path doesn't exist. (To create a directory and all
2856/// its missing parents at the same time, use the [`create_dir_all`]
2857/// function.)
2858/// * `path` already exists.
2859///
2860/// # Examples
2861///
2862/// ```no_run
2863/// use std::fs;
2864///
2865/// fn main() -> std::io::Result<()> {
2866/// fs::create_dir("/some/dir")?;
2867/// Ok(())
2868/// }
2869/// ```
2870#[doc(alias = "mkdir", alias = "CreateDirectory")]
2871#[stable(feature = "rust1", since = "1.0.0")]
2872#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
2873pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2874 DirBuilder::new().create(path.as_ref())
2875}
2876
2877/// Recursively create a directory and all of its parent components if they
2878/// are missing.
2879///
2880/// This function is not atomic. If it returns an error, any parent components it was able to create
2881/// will remain.
2882///
2883/// If the empty path is passed to this function, it always succeeds without
2884/// creating any directories.
2885///
2886/// # Platform-specific behavior
2887///
2888/// This function currently corresponds to multiple calls to the `mkdir`
2889/// function on Unix and the `CreateDirectoryW` function on Windows.
2890///
2891/// Note that, this [may change in the future][changes].
2892///
2893/// [changes]: io#platform-specific-behavior
2894///
2895/// # Errors
2896///
2897/// The function will return an error if any directory specified in path does not exist and
2898/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
2899///
2900/// Notable exception is made for situations where any of the directories
2901/// specified in the `path` could not be created as it was being created concurrently.
2902/// Such cases are considered to be successful. That is, calling `create_dir_all`
2903/// concurrently from multiple threads or processes is guaranteed not to fail
2904/// due to a race condition with itself.
2905///
2906/// [`fs::create_dir`]: create_dir
2907///
2908/// # Examples
2909///
2910/// ```no_run
2911/// use std::fs;
2912///
2913/// fn main() -> std::io::Result<()> {
2914/// fs::create_dir_all("/some/dir")?;
2915/// Ok(())
2916/// }
2917/// ```
2918#[stable(feature = "rust1", since = "1.0.0")]
2919pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2920 DirBuilder::new().recursive(true).create(path.as_ref())
2921}
2922
2923/// Removes an empty directory.
2924///
2925/// If you want to remove a directory that is not empty, as well as all
2926/// of its contents recursively, consider using [`remove_dir_all`]
2927/// instead.
2928///
2929/// # Platform-specific behavior
2930///
2931/// This function currently corresponds to the `rmdir` function on Unix
2932/// and the `RemoveDirectory` function on Windows.
2933/// Note that, this [may change in the future][changes].
2934///
2935/// [changes]: io#platform-specific-behavior
2936///
2937/// # Errors
2938///
2939/// This function will return an error in the following situations, but is not
2940/// limited to just these cases:
2941///
2942/// * `path` doesn't exist.
2943/// * `path` isn't a directory.
2944/// * The user lacks permissions to remove the directory at the provided `path`.
2945/// * The directory isn't empty.
2946///
2947/// This function will only ever return an error of kind `NotFound` if the given
2948/// path does not exist. Note that the inverse is not true,
2949/// ie. if a path does not exist, its removal may fail for a number of reasons,
2950/// such as insufficient permissions.
2951///
2952/// # Examples
2953///
2954/// ```no_run
2955/// use std::fs;
2956///
2957/// fn main() -> std::io::Result<()> {
2958/// fs::remove_dir("/some/dir")?;
2959/// Ok(())
2960/// }
2961/// ```
2962#[doc(alias = "rmdir", alias = "RemoveDirectory")]
2963#[stable(feature = "rust1", since = "1.0.0")]
2964pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2965 fs_imp::remove_dir(path.as_ref())
2966}
2967
2968/// Removes a directory at this path, after removing all its contents. Use
2969/// carefully!
2970///
2971/// This function does **not** follow symbolic links and it will simply remove the
2972/// symbolic link itself.
2973///
2974/// # Platform-specific behavior
2975///
2976/// These implementation details [may change in the future][changes].
2977///
2978/// - "Unix-like": By default, this function currently corresponds to
2979/// `openat`, `fdopendir`, `unlinkat` and `lstat`
2980/// on Unix-family platforms, except where noted otherwise.
2981/// - "Windows": This function currently corresponds to `CreateFileW`,
2982/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
2983///
2984/// ## Time-of-check to time-of-use (TOCTOU) race conditions
2985/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
2986///
2987/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
2988/// However, on the following platforms, this protection is not provided and the function should
2989/// not be used in security-sensitive contexts:
2990/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
2991/// TOCTOU races, Miri will not do so.
2992/// - **Redox OS**: This function does not protect against TOCTOU races, as Redox does not implement
2993/// the required platform support to do so.
2994///
2995/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
2996/// [changes]: io#platform-specific-behavior
2997///
2998/// # Errors
2999///
3000/// See [`fs::remove_file`] and [`fs::remove_dir`].
3001///
3002/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3003/// paths, *including* the root `path`. Consequently,
3004///
3005/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3006/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3007///
3008/// Consider ignoring the error if validating the removal is not required for your use case.
3009///
3010/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3011/// written into, which typically indicates some contents were removed but not all.
3012/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3013///
3014/// [`fs::remove_file`]: remove_file
3015/// [`fs::remove_dir`]: remove_dir
3016///
3017/// # Examples
3018///
3019/// ```no_run
3020/// use std::fs;
3021///
3022/// fn main() -> std::io::Result<()> {
3023/// fs::remove_dir_all("/some/dir")?;
3024/// Ok(())
3025/// }
3026/// ```
3027#[stable(feature = "rust1", since = "1.0.0")]
3028pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3029 fs_imp::remove_dir_all(path.as_ref())
3030}
3031
3032/// Returns an iterator over the entries within a directory.
3033///
3034/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3035/// New errors may be encountered after an iterator is initially constructed.
3036/// Entries for the current and parent directories (typically `.` and `..`) are
3037/// skipped.
3038///
3039/// # Platform-specific behavior
3040///
3041/// This function currently corresponds to the `opendir` function on Unix
3042/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3043/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3044/// Note that, this [may change in the future][changes].
3045///
3046/// [changes]: io#platform-specific-behavior
3047///
3048/// The order in which this iterator returns entries is platform and filesystem
3049/// dependent.
3050///
3051/// # Errors
3052///
3053/// This function will return an error in the following situations, but is not
3054/// limited to just these cases:
3055///
3056/// * The provided `path` doesn't exist.
3057/// * The process lacks permissions to view the contents.
3058/// * The `path` points at a non-directory file.
3059///
3060/// # Examples
3061///
3062/// ```
3063/// use std::io;
3064/// use std::fs::{self, DirEntry};
3065/// use std::path::Path;
3066///
3067/// // one possible implementation of walking a directory only visiting files
3068/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3069/// if dir.is_dir() {
3070/// for entry in fs::read_dir(dir)? {
3071/// let entry = entry?;
3072/// let path = entry.path();
3073/// if path.is_dir() {
3074/// visit_dirs(&path, cb)?;
3075/// } else {
3076/// cb(&entry);
3077/// }
3078/// }
3079/// }
3080/// Ok(())
3081/// }
3082/// ```
3083///
3084/// ```rust,no_run
3085/// use std::{fs, io};
3086///
3087/// fn main() -> io::Result<()> {
3088/// let mut entries = fs::read_dir(".")?
3089/// .map(|res| res.map(|e| e.path()))
3090/// .collect::<Result<Vec<_>, io::Error>>()?;
3091///
3092/// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3093/// // ordering is required the entries should be explicitly sorted.
3094///
3095/// entries.sort();
3096///
3097/// // The entries have now been sorted by their path.
3098///
3099/// Ok(())
3100/// }
3101/// ```
3102#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3103#[stable(feature = "rust1", since = "1.0.0")]
3104pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3105 fs_imp::read_dir(path.as_ref()).map(ReadDir)
3106}
3107
3108/// Changes the permissions found on a file or a directory.
3109///
3110/// # Platform-specific behavior
3111///
3112/// This function currently corresponds to the `chmod` function on Unix
3113/// and the `SetFileAttributes` function on Windows.
3114/// Note that, this [may change in the future][changes].
3115///
3116/// [changes]: io#platform-specific-behavior
3117///
3118/// ## Symlinks
3119/// On UNIX-like systems, this function will update the permission bits
3120/// of the file pointed to by the symlink.
3121///
3122/// Note that this behavior can lead to privalage escalation vulnerabilities,
3123/// where the ability to create a symlink in one directory allows you to
3124/// cause the permissions of another file or directory to be modified.
3125///
3126/// For this reason, using this function with symlinks should be avoided.
3127/// When possible, permissions should be set at creation time instead.
3128///
3129/// # Rationale
3130/// POSIX does not specify an `lchmod` function,
3131/// and symlinks can be followed regardless of what permission bits are set.
3132///
3133/// # Errors
3134///
3135/// This function will return an error in the following situations, but is not
3136/// limited to just these cases:
3137///
3138/// * `path` does not exist.
3139/// * The user lacks the permission to change attributes of the file.
3140///
3141/// # Examples
3142///
3143/// ```no_run
3144/// use std::fs;
3145///
3146/// fn main() -> std::io::Result<()> {
3147/// let mut perms = fs::metadata("foo.txt")?.permissions();
3148/// perms.set_readonly(true);
3149/// fs::set_permissions("foo.txt", perms)?;
3150/// Ok(())
3151/// }
3152/// ```
3153#[doc(alias = "chmod", alias = "SetFileAttributes")]
3154#[stable(feature = "set_permissions", since = "1.1.0")]
3155pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3156 fs_imp::set_permissions(path.as_ref(), perm.0)
3157}
3158
3159impl DirBuilder {
3160 /// Creates a new set of options with default mode/security settings for all
3161 /// platforms and also non-recursive.
3162 ///
3163 /// # Examples
3164 ///
3165 /// ```
3166 /// use std::fs::DirBuilder;
3167 ///
3168 /// let builder = DirBuilder::new();
3169 /// ```
3170 #[stable(feature = "dir_builder", since = "1.6.0")]
3171 #[must_use]
3172 pub fn new() -> DirBuilder {
3173 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3174 }
3175
3176 /// Indicates that directories should be created recursively, creating all
3177 /// parent directories. Parents that do not exist are created with the same
3178 /// security and permissions settings.
3179 ///
3180 /// This option defaults to `false`.
3181 ///
3182 /// # Examples
3183 ///
3184 /// ```
3185 /// use std::fs::DirBuilder;
3186 ///
3187 /// let mut builder = DirBuilder::new();
3188 /// builder.recursive(true);
3189 /// ```
3190 #[stable(feature = "dir_builder", since = "1.6.0")]
3191 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3192 self.recursive = recursive;
3193 self
3194 }
3195
3196 /// Creates the specified directory with the options configured in this
3197 /// builder.
3198 ///
3199 /// It is considered an error if the directory already exists unless
3200 /// recursive mode is enabled.
3201 ///
3202 /// # Examples
3203 ///
3204 /// ```no_run
3205 /// use std::fs::{self, DirBuilder};
3206 ///
3207 /// let path = "/tmp/foo/bar/baz";
3208 /// DirBuilder::new()
3209 /// .recursive(true)
3210 /// .create(path).unwrap();
3211 ///
3212 /// assert!(fs::metadata(path).unwrap().is_dir());
3213 /// ```
3214 #[stable(feature = "dir_builder", since = "1.6.0")]
3215 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3216 self._create(path.as_ref())
3217 }
3218
3219 fn _create(&self, path: &Path) -> io::Result<()> {
3220 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3221 }
3222
3223 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3224 if path == Path::new("") {
3225 return Ok(());
3226 }
3227
3228 match self.inner.mkdir(path) {
3229 Ok(()) => return Ok(()),
3230 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
3231 Err(_) if path.is_dir() => return Ok(()),
3232 Err(e) => return Err(e),
3233 }
3234 match path.parent() {
3235 Some(p) => self.create_dir_all(p)?,
3236 None => {
3237 return Err(io::const_error!(
3238 io::ErrorKind::Uncategorized,
3239 "failed to create whole tree",
3240 ));
3241 }
3242 }
3243 match self.inner.mkdir(path) {
3244 Ok(()) => Ok(()),
3245 Err(_) if path.is_dir() => Ok(()),
3246 Err(e) => Err(e),
3247 }
3248 }
3249}
3250
3251impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3252 #[inline]
3253 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3254 &mut self.inner
3255 }
3256}
3257
3258/// Returns `Ok(true)` if the path points at an existing entity.
3259///
3260/// This function will traverse symbolic links to query information about the
3261/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3262///
3263/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3264/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3265/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3266/// permission is denied on one of the parent directories.
3267///
3268/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3269/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3270/// where those bugs are not an issue.
3271///
3272/// # Examples
3273///
3274/// ```no_run
3275/// use std::fs;
3276///
3277/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3278/// assert!(fs::exists("/root/secret_file.txt").is_err());
3279/// ```
3280///
3281/// [`Path::exists`]: crate::path::Path::exists
3282/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3283#[stable(feature = "fs_try_exists", since = "1.81.0")]
3284#[inline]
3285pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
3286 fs_imp::exists(path.as_ref())
3287}