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