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