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 /// This is equivalent to `dir.metadata(".")` but can be more efficient.
1641 ///
1642 /// # Examples
1643 ///
1644 /// ```no_run
1645 /// #![feature(dirfd)]
1646 /// use std::fs::Dir;
1647 ///
1648 /// fn main() -> std::io::Result<()> {
1649 /// let dir = Dir::open("foo")?;
1650 /// let metadata = dir.self_metadata()?;
1651 /// Ok(())
1652 /// }
1653 /// ```
1654 #[unstable(feature = "dirfd", issue = "120426")]
1655 pub fn self_metadata(&self) -> io::Result<Metadata> {
1656 self.inner.self_metadata().map(Metadata)
1657 }
1658
1659 /// Attempts to open a file in read-only mode relative to this directory.
1660 ///
1661 /// This function interprets `path` relative to the directory provided by `self`. To open a file
1662 /// relative to the current working directory, or at an absolute path, see [`File::open`].
1663 ///
1664 /// # Errors
1665 ///
1666 /// This function will return an error if `path` does not point to an existing file.
1667 /// Other errors may also be returned according to [`OpenOptions::open`].
1668 ///
1669 /// # Examples
1670 ///
1671 /// ```no_run
1672 /// #![feature(dirfd)]
1673 /// use std::{fs::Dir, io};
1674 ///
1675 /// fn main() -> std::io::Result<()> {
1676 /// let dir = Dir::open("foo")?;
1677 /// let mut f = dir.open_file("bar.txt")?;
1678 /// let contents = io::read_to_string(f)?;
1679 /// assert_eq!(contents, "Hello, world!");
1680 /// Ok(())
1681 /// }
1682 /// ```
1683 #[unstable(feature = "dirfd", issue = "120426")]
1684 pub fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1685 self.inner
1686 .open_file(path.as_ref(), &OpenOptions::new().read(true).0)
1687 .map(|f| File { inner: f })
1688 }
1689
1690 /// Attempts to open a file according to `opts` relative to this directory.
1691 ///
1692 /// This function interprets `path` relative to the directory provided by `self`. To open a file
1693 /// relative to the current working directory, or at an absolute path, see [`File::open`].
1694 ///
1695 /// # Errors
1696 ///
1697 /// This function will return an error if `path` does not point to an existing file.
1698 /// Other errors may also be returned according to [`OpenOptions::open`].
1699 ///
1700 /// # Examples
1701 ///
1702 /// ```no_run
1703 /// #![feature(dirfd)]
1704 /// use std::{fs::{Dir, OpenOptions}, io::{self, Write}};
1705 ///
1706 /// fn main() -> io::Result<()> {
1707 /// let dir = Dir::open("foo")?;
1708 /// let mut opts = OpenOptions::new();
1709 /// opts.read(true).write(true);
1710 /// let mut f = dir.open_file_with("bar.txt", &opts)?;
1711 /// f.write_all(b"Hello, world!")?;
1712 /// let contents = io::read_to_string(f)?;
1713 /// assert_eq!(contents, "Hello, world!");
1714 /// Ok(())
1715 /// }
1716 /// ```
1717 #[unstable(feature = "dirfd", issue = "120426")]
1718 pub fn open_file_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> io::Result<File> {
1719 self.inner.open_file(path.as_ref(), &opts.0).map(|f| File { inner: f })
1720 }
1721
1722 /// Attempts to remove a file relative to this directory.
1723 ///
1724 /// This function interprets `path` relative to the directory provided by `self`. To remove a file
1725 /// relative to the current working directory, or at an absolute path, see [`fs::remove_file`][remove_file].
1726 ///
1727 /// # Errors
1728 ///
1729 /// This function will return an error if `path` does not point to an existing file.
1730 /// Other errors may also be returned according to [`OpenOptions::open`].
1731 ///
1732 /// # Examples
1733 ///
1734 /// ```no_run
1735 /// #![feature(dirfd)]
1736 /// use std::fs::Dir;
1737 ///
1738 /// fn main() -> std::io::Result<()> {
1739 /// let dir = Dir::open("foo")?;
1740 /// dir.remove_file("bar.txt")?;
1741 /// Ok(())
1742 /// }
1743 /// ```
1744 #[unstable(feature = "dirfd", issue = "120426")]
1745 pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1746 self.inner.remove_file(path.as_ref())
1747 }
1748
1749 /// Attempts to rename a file or directory relative to this directory to a new name, replacing
1750 /// the destination file if present.
1751 ///
1752 /// This function interprets `from` relative to the directory provided by `self` and `to` relative to the directory
1753 /// provided by `to_dir`. To rename a file relative to the current working directory, or at an absolute path, see [`fs::rename`][rename].
1754 ///
1755 /// # Errors
1756 ///
1757 /// This function will return an error if `from` does not point to an existing file or directory.
1758 /// Other errors may also be returned according to [`OpenOptions::open`].
1759 ///
1760 /// # Examples
1761 ///
1762 /// ```no_run
1763 /// #![feature(dirfd)]
1764 /// use std::fs::Dir;
1765 ///
1766 /// fn main() -> std::io::Result<()> {
1767 /// let dir = Dir::open("foo")?;
1768 /// dir.rename("bar.txt", &dir, "quux.txt")?;
1769 /// Ok(())
1770 /// }
1771 /// ```
1772 #[unstable(feature = "dirfd", issue = "120426")]
1773 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(
1774 &self,
1775 from: P,
1776 to_dir: &Self,
1777 to: Q,
1778 ) -> io::Result<()> {
1779 self.inner.rename(from.as_ref(), &to_dir.inner, to.as_ref())
1780 }
1781
1782 /// Attempts to create a directory relative to this directory.
1783 ///
1784 /// This function interprets `path` relative to the directory provided by `self`. To create a directory
1785 /// relative to the current working directory, or at an absolute path, see
1786 /// [`fs::create_dir`][crate::fs::create_dir].
1787 #[unstable(feature = "dirfd", issue = "120426")]
1788 pub fn create_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1789 self.inner.create_dir(path.as_ref())
1790 }
1791
1792 /// Attempts to open a directory in read-only mode relative to this directory.
1793 ///
1794 /// This function interprets `path` relative to the directory provided by `self`. To open a directory
1795 /// relative to the current working directory, or at an absolute path, see [`Dir::open`].
1796 ///
1797 /// # Errors
1798 ///
1799 /// This function will return an error if `path` does not point to an existing directory.
1800 /// Other errors may also be returned according to [`OpenOptions::open`].
1801 ///
1802 /// # Examples
1803 ///
1804 /// ```no_run
1805 /// #![feature(dirfd)]
1806 /// use std::{fs::Dir};
1807 ///
1808 /// fn main() -> std::io::Result<()> {
1809 /// let dir = Dir::open("foo")?;
1810 /// let foobar = dir.open_dir("bar")?;
1811 /// Ok(())
1812 /// }
1813 /// ```
1814 #[unstable(feature = "dirfd", issue = "120426")]
1815 pub fn open_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<Self> {
1816 self.inner
1817 .open_dir(path.as_ref(), &OpenOptions::new().read(true).0)
1818 .map(|inner| Self { inner })
1819 }
1820
1821 /// Attempts to open a directory relative to this directory according to `opts`.
1822 ///
1823 /// This function interprets `path` relative to the directory provided by `self`. To open a directory
1824 /// relative to the current working directory, or at an absolute path, see [`Dir::open`].
1825 ///
1826 /// # Errors
1827 ///
1828 /// This function will return errors according to [`OpenOptions::open`].
1829 ///
1830 /// # Examples
1831 ///
1832 /// ```no_run
1833 /// #![feature(dirfd)]
1834 /// use std::fs::{Dir, OpenOptions};
1835 ///
1836 /// fn main() -> std::io::Result<()> {
1837 /// let dir = Dir::open("foo")?;
1838 /// let foobar_w = dir.open_dir_with("bar", &OpenOptions::new().write(true))?;
1839 /// Ok(())
1840 /// }
1841 /// ```
1842 #[unstable(feature = "dirfd", issue = "120426")]
1843 pub fn open_dir_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> io::Result<Self> {
1844 self.inner.open_dir(path.as_ref(), &opts.0).map(|inner| Self { inner })
1845 }
1846
1847 /// Attempts to remove a directory relative to this directory.
1848 ///
1849 /// This function interprets `path` relative to the directory provided by `self`. To remove a directory
1850 /// relative to the current working directory, or at an absolute path, see
1851 /// [`fs::remove_dir`][crate::fs::remove_dir].
1852 ///
1853 /// # Errors
1854 ///
1855 /// This function will return an error if `path` does not point to an existing directory.
1856 /// Other errors may also be returned according to [`OpenOptions::open`].
1857 ///
1858 /// # Examples
1859 ///
1860 /// ```no_run
1861 /// #![feature(dirfd)]
1862 /// use std::{fs::Dir};
1863 ///
1864 /// fn main() -> std::io::Result<()> {
1865 /// let dir = Dir::open("foo")?;
1866 /// dir.remove_dir("bar")?;
1867 /// Ok(())
1868 /// }
1869 /// ```
1870 #[unstable(feature = "dirfd", issue = "120426")]
1871 pub fn remove_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1872 self.inner.remove_dir(path.as_ref())
1873 }
1874
1875 /// Creates a new `Dir` instance that shares the same underlying directory handle
1876 /// as the existing `Dir` instance.
1877 ///
1878 /// # Examples
1879 ///
1880 /// Creates two handles for a directory named `foo`:
1881 ///
1882 /// ```no_run
1883 /// #![feature(dirfd)]
1884 /// use std::fs::Dir;
1885 ///
1886 /// fn main() -> std::io::Result<()> {
1887 /// let dir = Dir::open("foo")?;
1888 /// let dir_copy = dir.try_clone()?;
1889 /// Ok(())
1890 /// }
1891 /// ```
1892 #[unstable(feature = "dirfd", issue = "120426")]
1893 pub fn try_clone(&self) -> io::Result<Self> {
1894 Ok(Dir { inner: self.inner.duplicate()? })
1895 }
1896
1897 /// Queries the file system to get information about a file, directory, etc. relative to this
1898 /// directory.
1899 ///
1900 /// This function will traverse symbolic links to query information about the destination file.
1901 /// To query metadata about the path itself without following symbolic links, use
1902 /// [`symlink_metadata`][Self::symlink_metadata].
1903 ///
1904 /// # Examples
1905 ///
1906 /// ```no_run
1907 /// #![feature(dirfd)]
1908 /// use std::fs::Dir;
1909 ///
1910 /// fn main() -> std::io::Result<()> {
1911 /// let dir = Dir::open("foo")?;
1912 /// let metadata = dir.metadata("subdir/file.txt")?;
1913 /// Ok(())
1914 /// }
1915 /// ```
1916 #[unstable(feature = "dirfd", issue = "120426")]
1917 pub fn metadata<P: AsRef<Path>>(&self, path: P) -> io::Result<Metadata> {
1918 self.inner.metadata(path.as_ref()).map(Metadata)
1919 }
1920
1921 /// Queries the file system to get information about a file, directory, etc. relative to this
1922 /// directory.
1923 ///
1924 /// This function will return the [`Metadata`] of the exact path without traversing symbolic
1925 /// links to a resolved destination file. Using this function on a path that is a file or
1926 /// directory (not a symbolic link) will behave the same as [`metadata`][Self::metadata].
1927 ///
1928 /// # Examples
1929 ///
1930 /// ```no_run
1931 /// #![feature(dirfd)]
1932 /// use std::fs::Dir;
1933 ///
1934 /// fn main() -> std::io::Result<()> {
1935 /// let dir = Dir::open("foo")?;
1936 /// let metadata = dir.symlink_metadata("subdir/file.txt")?;
1937 /// Ok(())
1938 /// }
1939 /// ```
1940 #[unstable(feature = "dirfd", issue = "120426")]
1941 pub fn symlink_metadata<P: AsRef<Path>>(&self, path: P) -> io::Result<Metadata> {
1942 self.inner.symlink_metadata(path.as_ref()).map(Metadata)
1943 }
1944}
1945
1946impl AsInner<fs_imp::Dir> for Dir {
1947 #[inline]
1948 fn as_inner(&self) -> &fs_imp::Dir {
1949 &self.inner
1950 }
1951}
1952impl FromInner<fs_imp::Dir> for Dir {
1953 fn from_inner(f: fs_imp::Dir) -> Dir {
1954 Dir { inner: f }
1955 }
1956}
1957impl IntoInner<fs_imp::Dir> for Dir {
1958 fn into_inner(self) -> fs_imp::Dir {
1959 self.inner
1960 }
1961}
1962
1963#[unstable(feature = "dirfd", issue = "120426")]
1964impl fmt::Debug for Dir {
1965 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1966 self.inner.fmt(f)
1967 }
1968}
1969
1970impl OpenOptions {
1971 /// Creates a blank new set of options ready for configuration.
1972 ///
1973 /// All options are initially set to `false`.
1974 ///
1975 /// # Examples
1976 ///
1977 /// ```no_run
1978 /// use std::fs::OpenOptions;
1979 ///
1980 /// let mut options = OpenOptions::new();
1981 /// let file = options.read(true).open("foo.txt");
1982 /// ```
1983 #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 #[must_use]
1986 pub fn new() -> Self {
1987 OpenOptions(fs_imp::OpenOptions::new())
1988 }
1989
1990 /// Sets the option for read access.
1991 ///
1992 /// This option, when true, will indicate that the file should be
1993 /// `read`-able if opened.
1994 ///
1995 /// # Examples
1996 ///
1997 /// ```no_run
1998 /// use std::fs::OpenOptions;
1999 ///
2000 /// let file = OpenOptions::new().read(true).open("foo.txt");
2001 /// ```
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub fn read(&mut self, read: bool) -> &mut Self {
2004 self.0.read(read);
2005 self
2006 }
2007
2008 /// Sets the option for write access.
2009 ///
2010 /// This option, when true, will indicate that the file should be
2011 /// `write`-able if opened.
2012 ///
2013 /// If the file already exists, any write calls on it will overwrite its
2014 /// contents, without truncating it.
2015 ///
2016 /// # Examples
2017 ///
2018 /// ```no_run
2019 /// use std::fs::OpenOptions;
2020 ///
2021 /// let file = OpenOptions::new().write(true).open("foo.txt");
2022 /// ```
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 pub fn write(&mut self, write: bool) -> &mut Self {
2025 self.0.write(write);
2026 self
2027 }
2028
2029 /// Sets the option for the append mode.
2030 ///
2031 /// This option, when true, means that writes will append to a file instead
2032 /// of overwriting previous contents.
2033 /// Note that setting `.write(true).append(true)` has the same effect as
2034 /// setting only `.append(true)`.
2035 ///
2036 /// Append mode guarantees that writes will be positioned at the current end of file,
2037 /// even when there are other processes or threads appending to the same file. This is
2038 /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
2039 /// has a race between seeking and writing during which another writer can write, with
2040 /// our `write()` overwriting their data.
2041 ///
2042 /// Keep in mind that this does not necessarily guarantee that data appended by
2043 /// different processes or threads does not interleave. The amount of data accepted a
2044 /// single `write()` call depends on the operating system and file system. A
2045 /// successful `write()` is allowed to write only part of the given data, so even if
2046 /// you're careful to provide the whole message in a single call to `write()`, there
2047 /// is no guarantee that it will be written out in full. If you rely on the filesystem
2048 /// accepting the message in a single write, make sure that all data that belongs
2049 /// together is written in one operation. This can be done by concatenating strings
2050 /// before passing them to [`write()`].
2051 ///
2052 /// If a file is opened with both read and append access, beware that after
2053 /// opening, and after every write, the position for reading may be set at the
2054 /// end of the file. So, before writing, save the current position (using
2055 /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
2056 ///
2057 /// ## Note
2058 ///
2059 /// This function doesn't create the file if it doesn't exist. Use the
2060 /// [`OpenOptions::create`] method to do so.
2061 ///
2062 /// [`write()`]: Write::write "io::Write::write"
2063 /// [`flush()`]: Write::flush "io::Write::flush"
2064 /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
2065 /// [seek]: Seek::seek "io::Seek::seek"
2066 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
2067 /// [End]: SeekFrom::End "io::SeekFrom::End"
2068 ///
2069 /// # Examples
2070 ///
2071 /// ```no_run
2072 /// use std::fs::OpenOptions;
2073 ///
2074 /// let file = OpenOptions::new().append(true).open("foo.txt");
2075 /// ```
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 pub fn append(&mut self, append: bool) -> &mut Self {
2078 self.0.append(append);
2079 self
2080 }
2081
2082 /// Sets the option for truncating a previous file.
2083 ///
2084 /// If a file is successfully opened with this option set to true, it will truncate
2085 /// the file to 0 length if it already exists.
2086 ///
2087 /// The file must be opened with write access for truncate to work.
2088 ///
2089 /// # Examples
2090 ///
2091 /// ```no_run
2092 /// use std::fs::OpenOptions;
2093 ///
2094 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
2095 /// ```
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
2098 self.0.truncate(truncate);
2099 self
2100 }
2101
2102 /// Sets the option to create a new file, or open it if it already exists.
2103 ///
2104 /// In order for the file to be created, [`OpenOptions::write`] or
2105 /// [`OpenOptions::append`] access must be used.
2106 ///
2107 /// See also [`std::fs::write()`][self::write] for a simple function to
2108 /// create a file with some given data.
2109 ///
2110 /// # Errors
2111 ///
2112 /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
2113 /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
2114 /// # Examples
2115 ///
2116 /// ```no_run
2117 /// use std::fs::OpenOptions;
2118 ///
2119 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
2120 /// ```
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub fn create(&mut self, create: bool) -> &mut Self {
2123 self.0.create(create);
2124 self
2125 }
2126
2127 /// Sets the option to create a new file, failing if it already exists.
2128 ///
2129 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
2130 /// way, if the call succeeds, the file returned is guaranteed to be new.
2131 /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
2132 /// or another error based on the situation. See [`OpenOptions::open`] for a
2133 /// non-exhaustive list of likely errors.
2134 ///
2135 /// This option is useful because it is atomic. Otherwise between checking
2136 /// whether a file exists and creating a new one, the file may have been
2137 /// created by another process (a [TOCTOU] race condition / attack).
2138 ///
2139 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
2140 /// ignored.
2141 ///
2142 /// The file must be opened with write or append access in order to create
2143 /// a new file.
2144 ///
2145 /// [`.create()`]: OpenOptions::create
2146 /// [`.truncate()`]: OpenOptions::truncate
2147 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
2148 /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
2149 ///
2150 /// # Examples
2151 ///
2152 /// ```no_run
2153 /// use std::fs::OpenOptions;
2154 ///
2155 /// let file = OpenOptions::new().write(true)
2156 /// .create_new(true)
2157 /// .open("foo.txt");
2158 /// ```
2159 #[stable(feature = "expand_open_options2", since = "1.9.0")]
2160 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
2161 self.0.create_new(create_new);
2162 self
2163 }
2164
2165 /// Opens a file at `path` with the options specified by `self`.
2166 ///
2167 /// # Errors
2168 ///
2169 /// This function will return an error under a number of different
2170 /// circumstances. Some of these error conditions are listed here, together
2171 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
2172 /// part of the compatibility contract of the function.
2173 ///
2174 /// * [`NotFound`]: The specified file does not exist and neither `create`
2175 /// or `create_new` is set.
2176 /// * [`NotFound`]: One of the directory components of the file path does
2177 /// not exist.
2178 /// * [`PermissionDenied`]: The user lacks permission to get the specified
2179 /// access rights for the file.
2180 /// * [`PermissionDenied`]: The user lacks permission to open one of the
2181 /// directory components of the specified path.
2182 /// * [`AlreadyExists`]: `create_new` was specified and the file already
2183 /// exists.
2184 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
2185 /// without write access, create without write or append access,
2186 /// no access mode set, etc.).
2187 ///
2188 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
2189 /// * One of the directory components of the specified file path
2190 /// was not, in fact, a directory.
2191 /// * Filesystem-level errors: full disk, write permission
2192 /// requested on a read-only file system, exceeded disk quota, too many
2193 /// open files, too long filename, too many symbolic links in the
2194 /// specified path (Unix-like systems only), etc.
2195 ///
2196 /// # Examples
2197 ///
2198 /// ```no_run
2199 /// use std::fs::OpenOptions;
2200 ///
2201 /// let file = OpenOptions::new().read(true).open("foo.txt");
2202 /// ```
2203 ///
2204 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
2205 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2206 /// [`NotFound`]: io::ErrorKind::NotFound
2207 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
2210 self._open(path.as_ref())
2211 }
2212
2213 fn _open(&self, path: &Path) -> io::Result<File> {
2214 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
2215 }
2216}
2217
2218impl AsInner<fs_imp::OpenOptions> for OpenOptions {
2219 #[inline]
2220 fn as_inner(&self) -> &fs_imp::OpenOptions {
2221 &self.0
2222 }
2223}
2224
2225impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
2226 #[inline]
2227 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
2228 &mut self.0
2229 }
2230}
2231
2232impl Metadata {
2233 /// Returns the file type for this metadata.
2234 ///
2235 /// # Examples
2236 ///
2237 /// ```no_run
2238 /// fn main() -> std::io::Result<()> {
2239 /// use std::fs;
2240 ///
2241 /// let metadata = fs::metadata("foo.txt")?;
2242 ///
2243 /// println!("{:?}", metadata.file_type());
2244 /// Ok(())
2245 /// }
2246 /// ```
2247 #[must_use]
2248 #[stable(feature = "file_type", since = "1.1.0")]
2249 pub fn file_type(&self) -> FileType {
2250 FileType(self.0.file_type())
2251 }
2252
2253 /// Returns `true` if this metadata is for a directory. The
2254 /// result is mutually exclusive to the result of
2255 /// [`Metadata::is_file`], and will be false for symlink metadata
2256 /// obtained from [`symlink_metadata`].
2257 ///
2258 /// # Examples
2259 ///
2260 /// ```no_run
2261 /// fn main() -> std::io::Result<()> {
2262 /// use std::fs;
2263 ///
2264 /// let metadata = fs::metadata("foo.txt")?;
2265 ///
2266 /// assert!(!metadata.is_dir());
2267 /// Ok(())
2268 /// }
2269 /// ```
2270 #[must_use]
2271 #[stable(feature = "rust1", since = "1.0.0")]
2272 pub fn is_dir(&self) -> bool {
2273 self.file_type().is_dir()
2274 }
2275
2276 /// Returns `true` if this metadata is for a regular file. The
2277 /// result is mutually exclusive to the result of
2278 /// [`Metadata::is_dir`], and will be false for symlink metadata
2279 /// obtained from [`symlink_metadata`].
2280 ///
2281 /// When the goal is simply to read from (or write to) the source, the most
2282 /// reliable way to test the source can be read (or written to) is to open
2283 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2284 /// a Unix-like system for example. See [`File::open`] or
2285 /// [`OpenOptions::open`] for more information.
2286 ///
2287 /// # Examples
2288 ///
2289 /// ```no_run
2290 /// use std::fs;
2291 ///
2292 /// fn main() -> std::io::Result<()> {
2293 /// let metadata = fs::metadata("foo.txt")?;
2294 ///
2295 /// assert!(metadata.is_file());
2296 /// Ok(())
2297 /// }
2298 /// ```
2299 #[must_use]
2300 #[stable(feature = "rust1", since = "1.0.0")]
2301 pub fn is_file(&self) -> bool {
2302 self.file_type().is_file()
2303 }
2304
2305 /// Returns `true` if this metadata is for a symbolic link.
2306 ///
2307 /// # Examples
2308 ///
2309 #[cfg_attr(unix, doc = "```no_run")]
2310 #[cfg_attr(not(unix), doc = "```ignore")]
2311 /// use std::fs;
2312 /// use std::path::Path;
2313 /// use std::os::unix::fs::symlink;
2314 ///
2315 /// fn main() -> std::io::Result<()> {
2316 /// let link_path = Path::new("link");
2317 /// symlink("/origin_does_not_exist/", link_path)?;
2318 ///
2319 /// let metadata = fs::symlink_metadata(link_path)?;
2320 ///
2321 /// assert!(metadata.is_symlink());
2322 /// Ok(())
2323 /// }
2324 /// ```
2325 #[must_use]
2326 #[stable(feature = "is_symlink", since = "1.58.0")]
2327 pub fn is_symlink(&self) -> bool {
2328 self.file_type().is_symlink()
2329 }
2330
2331 /// Returns the size of the file, in bytes, this metadata is for.
2332 ///
2333 /// # Examples
2334 ///
2335 /// ```no_run
2336 /// use std::fs;
2337 ///
2338 /// fn main() -> std::io::Result<()> {
2339 /// let metadata = fs::metadata("foo.txt")?;
2340 ///
2341 /// assert_eq!(0, metadata.len());
2342 /// Ok(())
2343 /// }
2344 /// ```
2345 #[must_use]
2346 #[stable(feature = "rust1", since = "1.0.0")]
2347 pub fn len(&self) -> u64 {
2348 self.0.size()
2349 }
2350
2351 /// Returns the permissions of the file this metadata is for.
2352 ///
2353 /// # Examples
2354 ///
2355 /// ```no_run
2356 /// use std::fs;
2357 ///
2358 /// fn main() -> std::io::Result<()> {
2359 /// let metadata = fs::metadata("foo.txt")?;
2360 ///
2361 /// assert!(!metadata.permissions().readonly());
2362 /// Ok(())
2363 /// }
2364 /// ```
2365 #[must_use]
2366 #[stable(feature = "rust1", since = "1.0.0")]
2367 pub fn permissions(&self) -> Permissions {
2368 Permissions(self.0.perm())
2369 }
2370
2371 /// Returns the last modification time listed in this metadata.
2372 ///
2373 /// The returned value corresponds to the `mtime` field of `stat` on Unix
2374 /// platforms and the `ftLastWriteTime` field on Windows platforms.
2375 ///
2376 /// # Errors
2377 ///
2378 /// This field might not be available on all platforms, and will return an
2379 /// `Err` on platforms where it is not available.
2380 ///
2381 /// # Examples
2382 ///
2383 /// ```no_run
2384 /// use std::fs;
2385 ///
2386 /// fn main() -> std::io::Result<()> {
2387 /// let metadata = fs::metadata("foo.txt")?;
2388 ///
2389 /// if let Ok(time) = metadata.modified() {
2390 /// println!("{time:?}");
2391 /// } else {
2392 /// println!("Not supported on this platform");
2393 /// }
2394 /// Ok(())
2395 /// }
2396 /// ```
2397 #[doc(alias = "mtime", alias = "ftLastWriteTime")]
2398 #[stable(feature = "fs_time", since = "1.10.0")]
2399 pub fn modified(&self) -> io::Result<SystemTime> {
2400 self.0.modified().map(FromInner::from_inner)
2401 }
2402
2403 /// Returns the last access time of this metadata.
2404 ///
2405 /// The returned value corresponds to the `atime` field of `stat` on Unix
2406 /// platforms and the `ftLastAccessTime` field on Windows platforms.
2407 ///
2408 /// Note that not all platforms will keep this field update in a file's
2409 /// metadata, for example Windows has an option to disable updating this
2410 /// time when files are accessed and Linux similarly has `noatime`.
2411 ///
2412 /// # Errors
2413 ///
2414 /// This field might not be available on all platforms, and will return an
2415 /// `Err` on platforms where it is not available.
2416 ///
2417 /// # Examples
2418 ///
2419 /// ```no_run
2420 /// use std::fs;
2421 ///
2422 /// fn main() -> std::io::Result<()> {
2423 /// let metadata = fs::metadata("foo.txt")?;
2424 ///
2425 /// if let Ok(time) = metadata.accessed() {
2426 /// println!("{time:?}");
2427 /// } else {
2428 /// println!("Not supported on this platform");
2429 /// }
2430 /// Ok(())
2431 /// }
2432 /// ```
2433 #[doc(alias = "atime", alias = "ftLastAccessTime")]
2434 #[stable(feature = "fs_time", since = "1.10.0")]
2435 pub fn accessed(&self) -> io::Result<SystemTime> {
2436 self.0.accessed().map(FromInner::from_inner)
2437 }
2438
2439 /// Returns the creation time listed in this metadata.
2440 ///
2441 /// The returned value corresponds to the `btime` field of `statx` on
2442 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
2443 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
2444 ///
2445 /// # Errors
2446 ///
2447 /// This field might not be available on all platforms, and will return an
2448 /// `Err` on platforms or filesystems where it is not available.
2449 ///
2450 /// # Examples
2451 ///
2452 /// ```no_run
2453 /// use std::fs;
2454 ///
2455 /// fn main() -> std::io::Result<()> {
2456 /// let metadata = fs::metadata("foo.txt")?;
2457 ///
2458 /// if let Ok(time) = metadata.created() {
2459 /// println!("{time:?}");
2460 /// } else {
2461 /// println!("Not supported on this platform or filesystem");
2462 /// }
2463 /// Ok(())
2464 /// }
2465 /// ```
2466 #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
2467 #[stable(feature = "fs_time", since = "1.10.0")]
2468 pub fn created(&self) -> io::Result<SystemTime> {
2469 self.0.created().map(FromInner::from_inner)
2470 }
2471}
2472
2473#[stable(feature = "std_debug", since = "1.16.0")]
2474impl fmt::Debug for Metadata {
2475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2476 let mut debug = f.debug_struct("Metadata");
2477 debug.field("file_type", &self.file_type());
2478 debug.field("permissions", &self.permissions());
2479 debug.field("len", &self.len());
2480 if let Ok(modified) = self.modified() {
2481 debug.field("modified", &modified);
2482 }
2483 if let Ok(accessed) = self.accessed() {
2484 debug.field("accessed", &accessed);
2485 }
2486 if let Ok(created) = self.created() {
2487 debug.field("created", &created);
2488 }
2489 debug.finish_non_exhaustive()
2490 }
2491}
2492
2493impl IntoInner<fs_imp::FileAttr> for Metadata {
2494 fn into_inner(self) -> fs_imp::FileAttr {
2495 self.0
2496 }
2497}
2498
2499impl AsInner<fs_imp::FileAttr> for Metadata {
2500 #[inline]
2501 fn as_inner(&self) -> &fs_imp::FileAttr {
2502 &self.0
2503 }
2504}
2505
2506impl FromInner<fs_imp::FileAttr> for Metadata {
2507 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2508 Metadata(attr)
2509 }
2510}
2511
2512impl FileTimes {
2513 /// Creates a new `FileTimes` with no times set.
2514 ///
2515 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2516 #[stable(feature = "file_set_times", since = "1.75.0")]
2517 pub fn new() -> Self {
2518 Self::default()
2519 }
2520
2521 /// Set the last access time of a file.
2522 #[stable(feature = "file_set_times", since = "1.75.0")]
2523 pub fn set_accessed(mut self, t: SystemTime) -> Self {
2524 self.0.set_accessed(t.into_inner());
2525 self
2526 }
2527
2528 /// Set the last modified time of a file.
2529 #[stable(feature = "file_set_times", since = "1.75.0")]
2530 pub fn set_modified(mut self, t: SystemTime) -> Self {
2531 self.0.set_modified(t.into_inner());
2532 self
2533 }
2534}
2535
2536impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2537 fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2538 &mut self.0
2539 }
2540}
2541
2542impl Permissions {
2543 /// Returns `true` if these permissions describe a readonly (unwritable) file.
2544 ///
2545 /// # Note
2546 ///
2547 /// This function does not take Access Control Lists (ACLs), Unix group
2548 /// membership and other nuances into account.
2549 /// Therefore the return value of this function cannot be relied upon
2550 /// to predict whether attempts to read or write the file will actually succeed.
2551 ///
2552 /// # Windows
2553 ///
2554 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2555 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2556 /// but the user may still have permission to change this flag. If
2557 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2558 /// to lack of write permission.
2559 /// The behavior of this attribute for directories depends on the Windows
2560 /// version.
2561 ///
2562 /// # Unix (including macOS)
2563 ///
2564 /// On Unix-based platforms this checks if *any* of the owner, group or others
2565 /// write permission bits are set. It does not consider anything else, including:
2566 ///
2567 /// * Whether the current user is in the file's assigned group.
2568 /// * Permissions granted by ACL.
2569 /// * That `root` user can write to files that do not have any write bits set.
2570 /// * Writable files on a filesystem that is mounted read-only.
2571 ///
2572 /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2573 /// also does not read ACLs.
2574 ///
2575 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2576 ///
2577 /// # Examples
2578 ///
2579 /// ```no_run
2580 /// use std::fs::File;
2581 ///
2582 /// fn main() -> std::io::Result<()> {
2583 /// let mut f = File::create("foo.txt")?;
2584 /// let metadata = f.metadata()?;
2585 ///
2586 /// assert_eq!(false, metadata.permissions().readonly());
2587 /// Ok(())
2588 /// }
2589 /// ```
2590 #[must_use = "call `set_readonly` to modify the readonly flag"]
2591 #[stable(feature = "rust1", since = "1.0.0")]
2592 pub fn readonly(&self) -> bool {
2593 self.0.readonly()
2594 }
2595
2596 /// Modifies the readonly flag for this set of permissions. If the
2597 /// `readonly` argument is `true`, using the resulting `Permission` will
2598 /// update file permissions to forbid writing. Conversely, if it's `false`,
2599 /// using the resulting `Permission` will update file permissions to allow
2600 /// writing.
2601 ///
2602 /// This operation does **not** modify the files attributes. This only
2603 /// changes the in-memory value of these attributes for this `Permissions`
2604 /// instance. To modify the files attributes use the [`set_permissions`]
2605 /// function which commits these attribute changes to the file.
2606 ///
2607 /// # Note
2608 ///
2609 /// `set_readonly(false)` makes the file *world-writable* on Unix.
2610 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2611 ///
2612 /// It also does not take Access Control Lists (ACLs) or Unix group
2613 /// membership into account.
2614 ///
2615 /// # Windows
2616 ///
2617 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2618 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2619 /// but the user may still have permission to change this flag. If
2620 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2621 /// the user does not have permission to write to the file.
2622 ///
2623 /// In Windows 7 and earlier this attribute prevents deleting empty
2624 /// directories. It does not prevent modifying the directory contents.
2625 /// On later versions of Windows this attribute is ignored for directories.
2626 ///
2627 /// # Unix (including macOS)
2628 ///
2629 /// On Unix-based platforms this sets or clears the write access bit for
2630 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2631 /// or `chmod a-w <file>` respectively. The latter will grant write access
2632 /// to all users! You can use the [`PermissionsExt`] trait on Unix
2633 /// to avoid this issue.
2634 ///
2635 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2636 ///
2637 /// # Examples
2638 ///
2639 /// ```no_run
2640 /// use std::fs::File;
2641 ///
2642 /// fn main() -> std::io::Result<()> {
2643 /// let f = File::create("foo.txt")?;
2644 /// let metadata = f.metadata()?;
2645 /// let mut permissions = metadata.permissions();
2646 ///
2647 /// permissions.set_readonly(true);
2648 ///
2649 /// // filesystem doesn't change, only the in memory state of the
2650 /// // readonly permission
2651 /// assert_eq!(false, metadata.permissions().readonly());
2652 ///
2653 /// // just this particular `permissions`.
2654 /// assert_eq!(true, permissions.readonly());
2655 /// Ok(())
2656 /// }
2657 /// ```
2658 #[stable(feature = "rust1", since = "1.0.0")]
2659 pub fn set_readonly(&mut self, readonly: bool) {
2660 self.0.set_readonly(readonly)
2661 }
2662}
2663
2664impl FileType {
2665 /// Tests whether this file type represents a directory. The
2666 /// result is mutually exclusive to the results of
2667 /// [`is_file`] and [`is_symlink`]; only zero or one of these
2668 /// tests may pass.
2669 ///
2670 /// [`is_file`]: FileType::is_file
2671 /// [`is_symlink`]: FileType::is_symlink
2672 ///
2673 /// # Examples
2674 ///
2675 /// ```no_run
2676 /// fn main() -> std::io::Result<()> {
2677 /// use std::fs;
2678 ///
2679 /// let metadata = fs::metadata("foo.txt")?;
2680 /// let file_type = metadata.file_type();
2681 ///
2682 /// assert_eq!(file_type.is_dir(), false);
2683 /// Ok(())
2684 /// }
2685 /// ```
2686 #[must_use]
2687 #[stable(feature = "file_type", since = "1.1.0")]
2688 pub fn is_dir(&self) -> bool {
2689 self.0.is_dir()
2690 }
2691
2692 /// Tests whether this file type represents a regular file.
2693 /// The result is mutually exclusive to the results of
2694 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2695 /// tests may pass.
2696 ///
2697 /// When the goal is simply to read from (or write to) the source, the most
2698 /// reliable way to test the source can be read (or written to) is to open
2699 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2700 /// a Unix-like system for example. See [`File::open`] or
2701 /// [`OpenOptions::open`] for more information.
2702 ///
2703 /// [`is_dir`]: FileType::is_dir
2704 /// [`is_symlink`]: FileType::is_symlink
2705 ///
2706 /// # Examples
2707 ///
2708 /// ```no_run
2709 /// fn main() -> std::io::Result<()> {
2710 /// use std::fs;
2711 ///
2712 /// let metadata = fs::metadata("foo.txt")?;
2713 /// let file_type = metadata.file_type();
2714 ///
2715 /// assert_eq!(file_type.is_file(), true);
2716 /// Ok(())
2717 /// }
2718 /// ```
2719 #[must_use]
2720 #[stable(feature = "file_type", since = "1.1.0")]
2721 pub fn is_file(&self) -> bool {
2722 self.0.is_file()
2723 }
2724
2725 /// Tests whether this file type represents a symbolic link.
2726 /// The result is mutually exclusive to the results of
2727 /// [`is_dir`] and [`is_file`]; only zero or one of these
2728 /// tests may pass.
2729 ///
2730 /// The underlying [`Metadata`] struct needs to be retrieved
2731 /// with the [`fs::symlink_metadata`] function and not the
2732 /// [`fs::metadata`] function. The [`fs::metadata`] function
2733 /// follows symbolic links, so [`is_symlink`] would always
2734 /// return `false` for the target file.
2735 ///
2736 /// [`fs::metadata`]: metadata
2737 /// [`fs::symlink_metadata`]: symlink_metadata
2738 /// [`is_dir`]: FileType::is_dir
2739 /// [`is_file`]: FileType::is_file
2740 /// [`is_symlink`]: FileType::is_symlink
2741 ///
2742 /// # Examples
2743 ///
2744 /// ```no_run
2745 /// use std::fs;
2746 ///
2747 /// fn main() -> std::io::Result<()> {
2748 /// let metadata = fs::symlink_metadata("foo.txt")?;
2749 /// let file_type = metadata.file_type();
2750 ///
2751 /// assert_eq!(file_type.is_symlink(), false);
2752 /// Ok(())
2753 /// }
2754 /// ```
2755 #[must_use]
2756 #[stable(feature = "file_type", since = "1.1.0")]
2757 pub fn is_symlink(&self) -> bool {
2758 self.0.is_symlink()
2759 }
2760}
2761
2762#[stable(feature = "std_debug", since = "1.16.0")]
2763impl fmt::Debug for FileType {
2764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2765 f.debug_struct("FileType")
2766 .field("is_file", &self.is_file())
2767 .field("is_dir", &self.is_dir())
2768 .field("is_symlink", &self.is_symlink())
2769 .finish_non_exhaustive()
2770 }
2771}
2772
2773impl AsInner<fs_imp::FileType> for FileType {
2774 #[inline]
2775 fn as_inner(&self) -> &fs_imp::FileType {
2776 &self.0
2777 }
2778}
2779
2780impl FromInner<fs_imp::FilePermissions> for Permissions {
2781 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2782 Permissions(f)
2783 }
2784}
2785
2786impl AsInner<fs_imp::FilePermissions> for Permissions {
2787 #[inline]
2788 fn as_inner(&self) -> &fs_imp::FilePermissions {
2789 &self.0
2790 }
2791}
2792
2793#[stable(feature = "rust1", since = "1.0.0")]
2794impl Iterator for ReadDir {
2795 type Item = io::Result<DirEntry>;
2796
2797 fn next(&mut self) -> Option<io::Result<DirEntry>> {
2798 self.0.next().map(|entry| entry.map(DirEntry))
2799 }
2800}
2801
2802impl DirEntry {
2803 /// Returns the full path to the file that this entry represents.
2804 ///
2805 /// The full path is created by joining the original path to `read_dir`
2806 /// with the filename of this entry.
2807 ///
2808 /// # Examples
2809 ///
2810 /// ```no_run
2811 /// use std::fs;
2812 ///
2813 /// fn main() -> std::io::Result<()> {
2814 /// for entry in fs::read_dir(".")? {
2815 /// let dir = entry?;
2816 /// println!("{:?}", dir.path());
2817 /// }
2818 /// Ok(())
2819 /// }
2820 /// ```
2821 ///
2822 /// This prints output like:
2823 ///
2824 /// ```text
2825 /// "./whatever.txt"
2826 /// "./foo.html"
2827 /// "./hello_world.rs"
2828 /// ```
2829 ///
2830 /// The exact text, of course, depends on what files you have in `.`.
2831 #[must_use]
2832 #[stable(feature = "rust1", since = "1.0.0")]
2833 pub fn path(&self) -> PathBuf {
2834 self.0.path()
2835 }
2836
2837 /// Returns the metadata for the file that this entry points at.
2838 ///
2839 /// This function will not traverse symlinks if this entry points at a
2840 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2841 ///
2842 /// [`fs::metadata`]: metadata
2843 /// [`fs::File::metadata`]: File::metadata
2844 ///
2845 /// # Platform-specific behavior
2846 ///
2847 /// On Windows this function is cheap to call (no extra system calls
2848 /// needed), but on Unix platforms this function is the equivalent of
2849 /// calling `symlink_metadata` on the path.
2850 ///
2851 /// # Examples
2852 ///
2853 /// ```
2854 /// use std::fs;
2855 ///
2856 /// if let Ok(entries) = fs::read_dir(".") {
2857 /// for entry in entries {
2858 /// if let Ok(entry) = entry {
2859 /// // Here, `entry` is a `DirEntry`.
2860 /// if let Ok(metadata) = entry.metadata() {
2861 /// // Now let's show our entry's permissions!
2862 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
2863 /// } else {
2864 /// println!("Couldn't get metadata for {:?}", entry.path());
2865 /// }
2866 /// }
2867 /// }
2868 /// }
2869 /// ```
2870 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2871 pub fn metadata(&self) -> io::Result<Metadata> {
2872 self.0.metadata().map(Metadata)
2873 }
2874
2875 /// Returns the file type for the file that this entry points at.
2876 ///
2877 /// This function will not traverse symlinks if this entry points at a
2878 /// symlink.
2879 ///
2880 /// # Platform-specific behavior
2881 ///
2882 /// On Windows and most Unix platforms this function is free (no extra
2883 /// system calls needed), but some Unix platforms may require the equivalent
2884 /// call to `symlink_metadata` to learn about the target file type.
2885 ///
2886 /// # Examples
2887 ///
2888 /// ```
2889 /// use std::fs;
2890 ///
2891 /// if let Ok(entries) = fs::read_dir(".") {
2892 /// for entry in entries {
2893 /// if let Ok(entry) = entry {
2894 /// // Here, `entry` is a `DirEntry`.
2895 /// if let Ok(file_type) = entry.file_type() {
2896 /// // Now let's show our entry's file type!
2897 /// println!("{:?}: {:?}", entry.path(), file_type);
2898 /// } else {
2899 /// println!("Couldn't get file type for {:?}", entry.path());
2900 /// }
2901 /// }
2902 /// }
2903 /// }
2904 /// ```
2905 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2906 pub fn file_type(&self) -> io::Result<FileType> {
2907 self.0.file_type().map(FileType)
2908 }
2909
2910 /// Returns the file name of this directory entry without any
2911 /// leading path component(s).
2912 ///
2913 /// As an example,
2914 /// the output of the function will result in "foo" for all the following paths:
2915 /// - "./foo"
2916 /// - "/the/foo"
2917 /// - "../../foo"
2918 ///
2919 /// # Examples
2920 ///
2921 /// ```
2922 /// use std::fs;
2923 ///
2924 /// if let Ok(entries) = fs::read_dir(".") {
2925 /// for entry in entries {
2926 /// if let Ok(entry) = entry {
2927 /// // Here, `entry` is a `DirEntry`.
2928 /// println!("{:?}", entry.file_name());
2929 /// }
2930 /// }
2931 /// }
2932 /// ```
2933 #[must_use]
2934 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2935 pub fn file_name(&self) -> OsString {
2936 self.0.file_name()
2937 }
2938}
2939
2940#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2941impl fmt::Debug for DirEntry {
2942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2943 f.debug_tuple("DirEntry").field(&self.path()).finish()
2944 }
2945}
2946
2947impl AsInner<fs_imp::DirEntry> for DirEntry {
2948 #[inline]
2949 fn as_inner(&self) -> &fs_imp::DirEntry {
2950 &self.0
2951 }
2952}
2953
2954/// Removes a file from the filesystem.
2955///
2956/// Note that there is no
2957/// guarantee that the file is immediately deleted (e.g., depending on
2958/// platform, other open file descriptors may prevent immediate removal).
2959///
2960/// # Platform-specific behavior
2961///
2962/// This function currently corresponds to the `unlink` function on Unix.
2963/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2964/// Note that, this [may change in the future][changes].
2965///
2966/// [changes]: io#platform-specific-behavior
2967///
2968/// # Errors
2969///
2970/// This function will return an error in the following situations, but is not
2971/// limited to just these cases:
2972///
2973/// * `path` points to a directory.
2974/// * The file doesn't exist.
2975/// * The user lacks permissions to remove the file.
2976///
2977/// This function will only ever return an error of kind `NotFound` if the given
2978/// path does not exist. Note that the inverse is not true,
2979/// i.e. if a path does not exist, its removal may fail for a number of reasons,
2980/// such as insufficient permissions.
2981///
2982/// # Examples
2983///
2984/// ```no_run
2985/// use std::fs;
2986///
2987/// fn main() -> std::io::Result<()> {
2988/// fs::remove_file("a.txt")?;
2989/// Ok(())
2990/// }
2991/// ```
2992#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
2993#[stable(feature = "rust1", since = "1.0.0")]
2994#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_file")]
2995pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
2996 fs_imp::remove_file(path.as_ref())
2997}
2998
2999/// Given a path, queries the file system to get information about a file,
3000/// directory, etc.
3001///
3002/// This function will traverse symbolic links to query information about the
3003/// destination file. To query metadata about the path itself without following
3004/// symbolic links, use [`symlink_metadata`].
3005///
3006/// # Platform-specific behavior
3007///
3008/// This function currently corresponds to the `stat` function on Unix
3009/// and the `GetFileInformationByHandle` function on Windows.
3010/// Note that, this [may change in the future][changes].
3011///
3012/// [changes]: io#platform-specific-behavior
3013///
3014/// # Errors
3015///
3016/// This function will return an error in the following situations, but is not
3017/// limited to just these cases:
3018///
3019/// * The user lacks permissions to perform `metadata` call on `path`.
3020/// * `path` does not exist.
3021/// * `path` is a symbolic link, but the destination file cannot be resolved.
3022///
3023/// # Examples
3024///
3025/// ```rust,no_run
3026/// use std::fs;
3027///
3028/// fn main() -> std::io::Result<()> {
3029/// let attr = fs::metadata("/some/file/path.txt")?;
3030/// // inspect attr ...
3031/// Ok(())
3032/// }
3033/// ```
3034#[doc(alias = "stat")]
3035#[stable(feature = "rust1", since = "1.0.0")]
3036#[cfg_attr(not(test), rustc_diagnostic_item = "fs_metadata")]
3037pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
3038 fs_imp::metadata(path.as_ref()).map(Metadata)
3039}
3040
3041/// Queries the metadata about a file without following symlinks.
3042///
3043/// This function will return the [`Metadata`] of the exact path without
3044/// traversing symbolic links to a resolved destination file. Using this function
3045/// on a path that is a file or directory (not a symbolic link) will behave the
3046/// same as [`metadata`].
3047///
3048/// # Platform-specific behavior
3049///
3050/// This function currently corresponds to the `lstat` function on Unix
3051/// and the `GetFileInformationByHandle` function on Windows.
3052/// Note that, this [may change in the future][changes].
3053///
3054/// [changes]: io#platform-specific-behavior
3055///
3056/// # Errors
3057///
3058/// This function will return an error in the following situations, but is not
3059/// limited to just these cases:
3060///
3061/// * The user lacks permissions to perform `metadata` call on `path`.
3062/// * `path` does not exist.
3063///
3064/// # Examples
3065///
3066/// ```rust,no_run
3067/// use std::fs;
3068///
3069/// fn main() -> std::io::Result<()> {
3070/// let attr = fs::symlink_metadata("/some/file/path.txt")?;
3071/// // inspect attr ...
3072/// Ok(())
3073/// }
3074/// ```
3075#[doc(alias = "lstat")]
3076#[stable(feature = "symlink_metadata", since = "1.1.0")]
3077#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_metadata")]
3078pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
3079 fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
3080}
3081
3082/// Renames a file or directory to a new name, replacing the original file if
3083/// `to` already exists.
3084///
3085/// This will not work if the new name is on a different mount point.
3086///
3087/// # Platform-specific behavior
3088///
3089/// This function currently corresponds to the [rename] function on Unix, and
3090/// `MoveFileExW` with a fallback to `SetFileInformationByHandle` on Windows.
3091/// The exact behavior differs:
3092///
3093/// - If `to` does not exist, `from` can be anything.
3094/// - On Unix, when `from` is a directory and `to` exists, `to` must be an empty directory.
3095/// - On Unix, when `from` is not a directory and `to` exists, `to` may not be a directory.
3096/// - On Windows 10 version 1607 and above, the behavior is the same as Unix if the
3097/// filesystem supports `FileRenameInfoEx`.
3098/// - Otherwise on Windows, `from` can be anything but `to` must not be a directory.
3099///
3100/// Note that, this [may change in the future][changes].
3101///
3102/// [changes]: io#platform-specific-behavior
3103/// [rename]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/rename.html
3104///
3105/// # Errors
3106///
3107/// This function will return an error in the following situations, but is not
3108/// limited to just these cases:
3109///
3110/// * `from` does not exist.
3111/// * The user lacks permissions to view contents.
3112/// * `from` and `to` are on separate filesystems.
3113///
3114/// # Examples
3115///
3116/// ```no_run
3117/// use std::fs;
3118///
3119/// fn main() -> std::io::Result<()> {
3120/// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
3121/// Ok(())
3122/// }
3123/// ```
3124#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
3125#[stable(feature = "rust1", since = "1.0.0")]
3126#[cfg_attr(not(test), rustc_diagnostic_item = "fs_rename")]
3127pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
3128 fs_imp::rename(from.as_ref(), to.as_ref())
3129}
3130
3131/// Copies the contents of one file to another. This function will also
3132/// copy the permission bits of the original file to the destination file.
3133///
3134/// This function will **overwrite** the contents of `to`.
3135///
3136/// Note that if `from` and `to` both point to the same file, then the file
3137/// will likely get truncated by this operation.
3138///
3139/// On success, the total number of bytes copied is returned and it is equal to
3140/// the length of the `to` file as reported by `metadata`.
3141///
3142/// If you want to copy the contents of one file to another and you’re
3143/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
3144///
3145/// # Platform-specific behavior
3146///
3147/// This function currently corresponds to the `open` function in Unix
3148/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
3149/// `O_CLOEXEC` is set for returned file descriptors.
3150///
3151/// On Linux (including Android), this function uses copy_file_range(2),
3152/// sendfile(2), or splice(2) syscalls to move data directly between files
3153/// if possible.
3154///
3155/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
3156/// NTFS streams are copied but only the size of the main stream is returned by
3157/// this function.
3158///
3159/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
3160///
3161/// Note that platform-specific behavior [may change in the future][changes].
3162///
3163/// [changes]: io#platform-specific-behavior
3164///
3165/// # Errors
3166///
3167/// This function will return an error in the following situations, but is not
3168/// limited to just these cases:
3169///
3170/// * `from` is neither a regular file nor a symlink to a regular file.
3171/// * `from` does not exist.
3172/// * The current process does not have the permission rights to read
3173/// `from` or write `to`.
3174/// * The parent directory of `to` doesn't exist.
3175///
3176/// # Examples
3177///
3178/// ```no_run
3179/// use std::fs;
3180///
3181/// fn main() -> std::io::Result<()> {
3182/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
3183/// Ok(())
3184/// }
3185/// ```
3186#[doc(alias = "cp")]
3187#[doc(alias = "CopyFile", alias = "CopyFileEx")]
3188#[doc(alias = "fclonefileat", alias = "fcopyfile")]
3189#[stable(feature = "rust1", since = "1.0.0")]
3190#[cfg_attr(not(test), rustc_diagnostic_item = "fs_copy")]
3191pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
3192 fs_imp::copy(from.as_ref(), to.as_ref())
3193}
3194
3195/// Creates a new hard link on the filesystem.
3196///
3197/// The `link` path will be a link pointing to the `original` path. Note that
3198/// systems often require these two paths to both be located on the same
3199/// filesystem.
3200///
3201/// If `original` names a symbolic link, it is platform-specific whether the
3202/// symbolic link is followed. On platforms where it's possible to not follow
3203/// it, it is not followed, and the created hard link points to the symbolic
3204/// link itself.
3205///
3206/// # Platform-specific behavior
3207///
3208/// This function currently corresponds to the `CreateHardLink` function on Windows.
3209/// On most Unix systems, it corresponds to the `linkat` function with no flags.
3210/// On VxWorks and Redox, it instead corresponds to the `link` function.
3211/// On MacOS, it uses the `linkat` function if it is available, but on very old
3212/// systems where `linkat` is not available, `link` is selected at runtime instead.
3213/// Note that, this [may change in the future][changes].
3214///
3215/// [changes]: io#platform-specific-behavior
3216///
3217/// # Errors
3218///
3219/// This function will return an error in the following situations, but is not
3220/// limited to just these cases:
3221///
3222/// * The `original` path is not a file or doesn't exist.
3223/// * The 'link' path already exists.
3224///
3225/// # Examples
3226///
3227/// ```no_run
3228/// use std::fs;
3229///
3230/// fn main() -> std::io::Result<()> {
3231/// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
3232/// Ok(())
3233/// }
3234/// ```
3235#[doc(alias = "CreateHardLink", alias = "linkat")]
3236#[stable(feature = "rust1", since = "1.0.0")]
3237#[cfg_attr(not(test), rustc_diagnostic_item = "fs_hard_link")]
3238pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
3239 fs_imp::hard_link(original.as_ref(), link.as_ref())
3240}
3241
3242/// Creates a new symbolic link on the filesystem.
3243///
3244/// The `link` path will be a symbolic link pointing to the `original` path.
3245/// On Windows, this will be a file symlink, not a directory symlink;
3246/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
3247/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
3248/// used instead to make the intent explicit.
3249///
3250/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
3251/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
3252/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
3253///
3254/// # Examples
3255///
3256/// ```no_run
3257/// use std::fs;
3258///
3259/// fn main() -> std::io::Result<()> {
3260/// fs::soft_link("a.txt", "b.txt")?;
3261/// Ok(())
3262/// }
3263/// ```
3264#[stable(feature = "rust1", since = "1.0.0")]
3265#[deprecated(
3266 since = "1.1.0",
3267 note = "replaced with std::os::unix::fs::symlink and \
3268 std::os::windows::fs::{symlink_file, symlink_dir}"
3269)]
3270pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
3271 fs_imp::symlink(original.as_ref(), link.as_ref())
3272}
3273
3274/// Reads a symbolic link, returning the file that the link points to.
3275///
3276/// # Platform-specific behavior
3277///
3278/// This function currently corresponds to the `readlink` function on Unix
3279/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
3280/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
3281/// Note that, this [may change in the future][changes].
3282///
3283/// [changes]: io#platform-specific-behavior
3284///
3285/// # Errors
3286///
3287/// This function will return an error in the following situations, but is not
3288/// limited to just these cases:
3289///
3290/// * `path` is not a symbolic link.
3291/// * `path` does not exist.
3292///
3293/// # Examples
3294///
3295/// ```no_run
3296/// use std::fs;
3297///
3298/// fn main() -> std::io::Result<()> {
3299/// let path = fs::read_link("a.txt")?;
3300/// Ok(())
3301/// }
3302/// ```
3303#[stable(feature = "rust1", since = "1.0.0")]
3304#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_link")]
3305pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
3306 fs_imp::read_link(path.as_ref())
3307}
3308
3309/// Returns the canonical, absolute form of a path with all intermediate
3310/// components normalized and symbolic links resolved.
3311///
3312/// # Platform-specific behavior
3313///
3314/// This function currently corresponds to the `realpath` function on Unix
3315/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
3316/// Note that this [may change in the future][changes].
3317///
3318/// On Windows, this converts the path to use [extended length path][path]
3319/// syntax, which allows your program to use longer path names, but means you
3320/// can only join backslash-delimited paths to it, and it may be incompatible
3321/// with other applications (if passed to the application on the command-line,
3322/// or written to a file another application may read).
3323///
3324/// [changes]: io#platform-specific-behavior
3325/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
3326///
3327/// # Errors
3328///
3329/// This function will return an error in the following situations, but is not
3330/// limited to just these cases:
3331///
3332/// * `path` does not exist.
3333/// * A non-final component in path is not a directory.
3334///
3335/// # Examples
3336///
3337/// ```no_run
3338/// use std::fs;
3339///
3340/// fn main() -> std::io::Result<()> {
3341/// let path = fs::canonicalize("../a/../foo.txt")?;
3342/// Ok(())
3343/// }
3344/// ```
3345#[doc(alias = "realpath")]
3346#[doc(alias = "GetFinalPathNameByHandle")]
3347#[stable(feature = "fs_canonicalize", since = "1.5.0")]
3348#[cfg_attr(not(test), rustc_diagnostic_item = "fs_canonicalize")]
3349pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
3350 fs_imp::canonicalize(path.as_ref())
3351}
3352
3353/// Creates a new, empty directory at the provided path.
3354///
3355/// # Platform-specific behavior
3356///
3357/// This function currently corresponds to the `mkdir` function on Unix
3358/// and the `CreateDirectoryW` function on Windows.
3359/// Note that, this [may change in the future][changes].
3360///
3361/// [changes]: io#platform-specific-behavior
3362///
3363/// **NOTE**: If a parent of the given path doesn't exist, this function will
3364/// return an error. To create a directory and all its missing parents at the
3365/// same time, use the [`create_dir_all`] function.
3366///
3367/// # Errors
3368///
3369/// This function will return an error in the following situations, but is not
3370/// limited to just these cases:
3371///
3372/// * User lacks permissions to create directory at `path`.
3373/// * A parent of the given path doesn't exist. (To create a directory and all
3374/// its missing parents at the same time, use the [`create_dir_all`]
3375/// function.)
3376/// * `path` already exists.
3377///
3378/// # Examples
3379///
3380/// ```no_run
3381/// use std::fs;
3382///
3383/// fn main() -> std::io::Result<()> {
3384/// fs::create_dir("/some/dir")?;
3385/// Ok(())
3386/// }
3387/// ```
3388#[doc(alias = "mkdir", alias = "CreateDirectory")]
3389#[stable(feature = "rust1", since = "1.0.0")]
3390#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
3391pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3392 DirBuilder::new().create(path.as_ref())
3393}
3394
3395/// Recursively create a directory and all of its parent components if they
3396/// are missing.
3397///
3398/// This function is not atomic. If it returns an error, any parent components it was able to create
3399/// will remain.
3400///
3401/// If the empty path is passed to this function, it always succeeds without
3402/// creating any directories.
3403///
3404/// # Platform-specific behavior
3405///
3406/// This function currently corresponds to multiple calls to the `mkdir`
3407/// function on Unix and the `CreateDirectoryW` function on Windows.
3408///
3409/// Note that, this [may change in the future][changes].
3410///
3411/// [changes]: io#platform-specific-behavior
3412///
3413/// # Errors
3414///
3415/// The function will return an error if any directory specified in path does not exist and
3416/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
3417///
3418/// Notable exception is made for situations where any of the directories
3419/// specified in the `path` could not be created as it was being created concurrently.
3420/// Such cases are considered to be successful. That is, calling `create_dir_all`
3421/// concurrently from multiple threads or processes is guaranteed not to fail
3422/// due to a race condition with itself.
3423///
3424/// [`fs::create_dir`]: create_dir
3425///
3426/// # Examples
3427///
3428/// ```no_run
3429/// use std::fs;
3430///
3431/// fn main() -> std::io::Result<()> {
3432/// fs::create_dir_all("/some/dir")?;
3433/// Ok(())
3434/// }
3435/// ```
3436#[stable(feature = "rust1", since = "1.0.0")]
3437#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir_all")]
3438pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3439 DirBuilder::new().recursive(true).create(path.as_ref())
3440}
3441
3442/// Removes an empty directory.
3443///
3444/// If you want to remove a directory that is not empty, as well as all
3445/// of its contents recursively, consider using [`remove_dir_all`]
3446/// instead.
3447///
3448/// # Platform-specific behavior
3449///
3450/// This function currently corresponds to the `rmdir` function on Unix
3451/// and the `RemoveDirectory` function on Windows.
3452/// Note that, this [may change in the future][changes].
3453///
3454/// [changes]: io#platform-specific-behavior
3455///
3456/// # Errors
3457///
3458/// This function will return an error in the following situations, but is not
3459/// limited to just these cases:
3460///
3461/// * `path` doesn't exist.
3462/// * `path` isn't a directory.
3463/// * The user lacks permissions to remove the directory at the provided `path`.
3464/// * The directory isn't empty.
3465///
3466/// This function will only ever return an error of kind `NotFound` if the given
3467/// path does not exist. Note that the inverse is not true,
3468/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3469/// such as insufficient permissions.
3470///
3471/// # Examples
3472///
3473/// ```no_run
3474/// use std::fs;
3475///
3476/// fn main() -> std::io::Result<()> {
3477/// fs::remove_dir("/some/dir")?;
3478/// Ok(())
3479/// }
3480/// ```
3481#[doc(alias = "rmdir", alias = "RemoveDirectory")]
3482#[stable(feature = "rust1", since = "1.0.0")]
3483#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir")]
3484pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3485 fs_imp::remove_dir(path.as_ref())
3486}
3487
3488/// Removes a directory at this path, after removing all its contents. Use
3489/// carefully!
3490///
3491/// This function does **not** follow symbolic links and it will simply remove the
3492/// symbolic link itself.
3493///
3494/// # Platform-specific behavior
3495///
3496/// These implementation details [may change in the future][changes].
3497///
3498/// - "Unix-like": By default, this function currently corresponds to
3499/// `openat`, `fdopendir`, `unlinkat` and `lstat`
3500/// on Unix-family platforms, except where noted otherwise.
3501/// - "Windows": This function currently corresponds to `CreateFileW`,
3502/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
3503///
3504/// ## Time-of-check to time-of-use (TOCTOU) race conditions
3505/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
3506///
3507/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
3508/// However, on the following platforms, this protection is not provided and the function should
3509/// not be used in security-sensitive contexts:
3510/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
3511/// TOCTOU races, Miri will not do so.
3512/// - **ESP-IDF**, **Horizon**, **PS Vita**, **QNX**, **Redox OS**, **VxWorks**: This function does
3513/// not protect against TOCTOU races, as the underlying platform does not implement the required
3514/// platform support to do so.
3515///
3516/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3517/// [changes]: io#platform-specific-behavior
3518///
3519/// # Errors
3520///
3521/// See [`fs::remove_file`] and [`fs::remove_dir`].
3522///
3523/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3524/// paths, *including* the root `path`. Consequently,
3525///
3526/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3527/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3528///
3529/// Consider ignoring the error if validating the removal is not required for your use case.
3530///
3531/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3532/// written into, which typically indicates some contents were removed but not all.
3533/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3534///
3535/// [`fs::remove_file`]: remove_file
3536/// [`fs::remove_dir`]: remove_dir
3537///
3538/// # Examples
3539///
3540/// ```no_run
3541/// use std::fs;
3542///
3543/// fn main() -> std::io::Result<()> {
3544/// fs::remove_dir_all("/some/dir")?;
3545/// Ok(())
3546/// }
3547/// ```
3548#[stable(feature = "rust1", since = "1.0.0")]
3549#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir_all")]
3550pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3551 fs_imp::remove_dir_all(path.as_ref())
3552}
3553
3554/// Returns an iterator over the entries within a directory.
3555///
3556/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3557/// New errors may be encountered after an iterator is initially constructed.
3558/// Entries for the current and parent directories (typically `.` and `..`) are
3559/// skipped.
3560///
3561/// The order in which `read_dir` returns entries can change between calls. If reproducible
3562/// ordering is required, the entries should be explicitly sorted.
3563///
3564/// # Platform-specific behavior
3565///
3566/// This function currently corresponds to the `opendir` function on Unix
3567/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3568/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3569/// Note that, this [may change in the future][changes].
3570///
3571/// [changes]: io#platform-specific-behavior
3572///
3573/// The order in which this iterator returns entries is platform and filesystem
3574/// dependent.
3575///
3576/// # Errors
3577///
3578/// This function will return an error in the following situations, but is not
3579/// limited to just these cases:
3580///
3581/// * The provided `path` doesn't exist.
3582/// * The process lacks permissions to view the contents.
3583/// * The `path` points at a non-directory file.
3584///
3585/// # Examples
3586///
3587/// ```
3588/// use std::io;
3589/// use std::fs::{self, DirEntry};
3590/// use std::path::Path;
3591///
3592/// // one possible implementation of walking a directory only visiting files
3593/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3594/// if dir.is_dir() {
3595/// for entry in fs::read_dir(dir)? {
3596/// let entry = entry?;
3597/// let path = entry.path();
3598/// if path.is_dir() {
3599/// visit_dirs(&path, cb)?;
3600/// } else {
3601/// cb(&entry);
3602/// }
3603/// }
3604/// }
3605/// Ok(())
3606/// }
3607/// ```
3608///
3609/// ```rust,no_run
3610/// use std::{fs, io};
3611///
3612/// fn main() -> io::Result<()> {
3613/// let mut entries = fs::read_dir(".")?
3614/// .map(|res| res.map(|e| e.path()))
3615/// .collect::<Result<Vec<_>, io::Error>>()?;
3616///
3617/// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3618/// // ordering is required the entries should be explicitly sorted.
3619///
3620/// entries.sort();
3621///
3622/// // The entries have now been sorted by their path.
3623///
3624/// Ok(())
3625/// }
3626/// ```
3627#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3628#[stable(feature = "rust1", since = "1.0.0")]
3629#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_dir")]
3630pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3631 fs_imp::read_dir(path.as_ref()).map(ReadDir)
3632}
3633
3634/// Changes the permissions found on a file or a directory.
3635///
3636/// # Platform-specific behavior
3637///
3638/// This function currently corresponds to the `chmod` function on Unix
3639/// and the `SetFileAttributes` function on Windows.
3640/// Note that, this [may change in the future][changes].
3641///
3642/// [changes]: io#platform-specific-behavior
3643///
3644/// ## Symlinks
3645/// On UNIX-like systems, this function will update the permission bits
3646/// of the file pointed to by the symlink.
3647///
3648/// Note that this behavior can lead to privilege escalation vulnerabilities,
3649/// where the ability to create a symlink in one directory allows you to
3650/// cause the permissions of another file or directory to be modified.
3651///
3652/// For this reason, using this function with symlinks should be avoided.
3653/// When possible, permissions should be set at creation time instead.
3654///
3655/// # Rationale
3656/// POSIX does not specify an `lchmod` function,
3657/// and symlinks can be followed regardless of what permission bits are set.
3658///
3659/// # Errors
3660///
3661/// This function will return an error in the following situations, but is not
3662/// limited to just these cases:
3663///
3664/// * `path` does not exist.
3665/// * The user lacks the permission to change attributes of the file.
3666///
3667/// # Examples
3668///
3669/// ```no_run
3670/// use std::fs;
3671///
3672/// fn main() -> std::io::Result<()> {
3673/// let mut perms = fs::metadata("foo.txt")?.permissions();
3674/// perms.set_readonly(true);
3675/// fs::set_permissions("foo.txt", perms)?;
3676/// Ok(())
3677/// }
3678/// ```
3679#[doc(alias = "chmod", alias = "SetFileAttributes")]
3680#[stable(feature = "set_permissions", since = "1.1.0")]
3681#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions")]
3682pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3683 fs_imp::set_permissions(path.as_ref(), perm.0)
3684}
3685
3686/// Changes the permissions found on a file or a directory. On certain platforms, if the file
3687/// is a symlink, it will change the permissions bits on the symlink itself rather than
3688/// the target (e.g. Windows, BSD, MacOS). On other platforms, this results in an error when
3689/// attempting to change permissions on a symlink (e.g. Linux).
3690///
3691/// Note that non-final path elements are allowed to be symlinks.
3692///
3693/// # Platform-specific behavior
3694///
3695/// This function currently corresponds to the following underlying operations:
3696/// * Android: returns [`Unsupported`] on all files.
3697/// * Linux, BSD-based platforms, QNX, NTO: `fchmodat` with `AT_SYMLINK_NOFOLLOW`.
3698/// If that is not supported, we fall back to:
3699/// * Unix-based platforms with symlinks: `open` with `O_NOFOLLOW` followed by
3700/// [`fs::set_permissions`].
3701/// * Unix-based platforms without symlinks: `open` followed by [`fs::set_permissions`].
3702/// * Windows: `CreateFileW` with `FILE_FLAG_OPEN_REPARSE_POINT` followed
3703/// by `SetFileInformationByHandle`.
3704///
3705/// Note that, this [may change in the future][changes].
3706///
3707/// [changes]: io#platform-specific-behavior
3708///
3709/// [`fs::set_permissions`]: crate::fs::set_permissions
3710///
3711/// # Errors
3712///
3713/// This function will return an error in the following situations, but is not
3714/// limited to just these cases:
3715///
3716/// * `path` does not exist.
3717/// * The user lacks the permission to change attributes of the file.
3718///
3719/// Note: On Linux and other Unix-based platforms with symlinks (non-BSD-based),
3720/// this will result in an [`Unsupported`] error if the final element is a symlink.
3721///
3722/// [`Unsupported`]: crate::io::ErrorKind::Unsupported
3723///
3724/// # Examples
3725///
3726/// ```no_run
3727/// #![feature(set_permissions_nofollow)]
3728/// use std::fs;
3729///
3730/// fn main() -> std::io::Result<()> {
3731/// let mut perms = fs::symlink_metadata("foo.txt")?.permissions();
3732/// perms.set_readonly(true);
3733/// // This should result in an error on certain platforms or
3734/// // succeed in modifying the permissions of a symlink
3735/// fs::set_permissions_nofollow("foo.txt", perms)?;
3736/// Ok(())
3737/// }
3738/// ```
3739#[doc(alias = "fchmodat", alias = "SetFileInformationByHandle")]
3740#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
3741#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions_nofollow")]
3742pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3743 fs_imp::set_permissions_nofollow(path.as_ref(), perm.0)
3744}
3745
3746impl DirBuilder {
3747 /// Creates a new set of options with default mode/security settings for all
3748 /// platforms and also non-recursive.
3749 ///
3750 /// # Examples
3751 ///
3752 /// ```
3753 /// use std::fs::DirBuilder;
3754 ///
3755 /// let builder = DirBuilder::new();
3756 /// ```
3757 #[stable(feature = "dir_builder", since = "1.6.0")]
3758 #[must_use]
3759 pub fn new() -> DirBuilder {
3760 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3761 }
3762
3763 /// Indicates that directories should be created recursively, creating all
3764 /// parent directories. Parents that do not exist are created with the same
3765 /// security and permissions settings.
3766 ///
3767 /// This option defaults to `false`.
3768 ///
3769 /// # Examples
3770 ///
3771 /// ```
3772 /// use std::fs::DirBuilder;
3773 ///
3774 /// let mut builder = DirBuilder::new();
3775 /// builder.recursive(true);
3776 /// ```
3777 #[stable(feature = "dir_builder", since = "1.6.0")]
3778 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3779 self.recursive = recursive;
3780 self
3781 }
3782
3783 /// Creates the specified directory with the options configured in this
3784 /// builder.
3785 ///
3786 /// It is considered an error if the directory already exists unless
3787 /// recursive mode is enabled.
3788 ///
3789 /// # Examples
3790 ///
3791 /// ```no_run
3792 /// use std::fs::{self, DirBuilder};
3793 ///
3794 /// let path = "/tmp/foo/bar/baz";
3795 /// DirBuilder::new()
3796 /// .recursive(true)
3797 /// .create(path).unwrap();
3798 ///
3799 /// assert!(fs::metadata(path).unwrap().is_dir());
3800 /// ```
3801 #[stable(feature = "dir_builder", since = "1.6.0")]
3802 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3803 self._create(path.as_ref())
3804 }
3805
3806 fn _create(&self, path: &Path) -> io::Result<()> {
3807 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3808 }
3809
3810 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3811 // if path's parent is None, it is "/" path, which should
3812 // return Ok immediately
3813 if path.is_empty() || path.parent().is_none() {
3814 return Ok(());
3815 }
3816
3817 let ancestors = path.ancestors();
3818 let mut uncreated_dirs = 0;
3819
3820 for ancestor in ancestors {
3821 // for relative paths like "foo/bar", the parent of
3822 // "foo" will be "" which there's no need to invoke
3823 // a mkdir syscall on
3824 if ancestor.is_empty() || ancestor.parent().is_none() {
3825 break;
3826 }
3827
3828 match self.inner.mkdir(ancestor) {
3829 Ok(()) => break,
3830 Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
3831 // we check if the err is AlreadyExists for two reasons
3832 // - in case the path exists as a *file*
3833 // - and to avoid calls to .is_dir() in case of other errs
3834 // (i.e. PermissionDenied)
3835 Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
3836 Err(e) => return Err(e),
3837 }
3838 }
3839
3840 // collect only the uncreated directories w/o letting the vec resize
3841 let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
3842 uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
3843
3844 for uncreated_dir in uncreated_dirs_vec.iter().rev() {
3845 if let Err(e) = self.inner.mkdir(uncreated_dir) {
3846 if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
3847 return Err(e);
3848 }
3849 }
3850 }
3851
3852 Ok(())
3853 }
3854}
3855
3856impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3857 #[inline]
3858 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3859 &mut self.inner
3860 }
3861}
3862
3863/// Returns `Ok(true)` if the path points at an existing entity.
3864///
3865/// This function will traverse symbolic links to query information about the
3866/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3867///
3868/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3869/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3870/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3871/// permission is denied on one of the parent directories.
3872///
3873/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3874/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3875/// where those bugs are not an issue.
3876///
3877/// # Examples
3878///
3879/// ```no_run
3880/// use std::fs;
3881///
3882/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3883/// assert!(fs::exists("/root/secret_file.txt").is_err());
3884/// ```
3885///
3886/// [`Path::exists`]: crate::path::Path::exists
3887/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3888#[stable(feature = "fs_try_exists", since = "1.81.0")]
3889#[cfg_attr(not(test), rustc_diagnostic_item = "fs_exists")]
3890#[inline]
3891pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
3892 fs_imp::exists(path.as_ref())
3893}