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