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