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