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 ///
821 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
822 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
823 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
824 /// cause non-lockholders to block.
825 ///
826 /// If this file handle/descriptor, or a clone of it, already holds a lock the exact behavior
827 /// is unspecified and platform dependent, including the possibility that it will deadlock.
828 /// However, if this method returns, then an exclusive lock is held.
829 ///
830 /// If the file is not open for writing, it is unspecified whether this function returns an error.
831 ///
832 /// The lock will be released when this file (along with any other file descriptors/handles
833 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
834 ///
835 /// # Platform-specific behavior
836 ///
837 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
838 /// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
839 /// this [may change in the future][changes].
840 ///
841 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
842 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
843 ///
844 /// [changes]: io#platform-specific-behavior
845 ///
846 /// [`lock`]: File::lock
847 /// [`lock_shared`]: File::lock_shared
848 /// [`try_lock`]: File::try_lock
849 /// [`try_lock_shared`]: File::try_lock_shared
850 /// [`unlock`]: File::unlock
851 /// [`read`]: Read::read
852 /// [`write`]: Write::write
853 ///
854 /// # Examples
855 ///
856 /// ```no_run
857 /// use std::fs::File;
858 ///
859 /// fn main() -> std::io::Result<()> {
860 /// let f = File::create("foo.txt")?;
861 /// f.lock()?;
862 /// Ok(())
863 /// }
864 /// ```
865 #[stable(feature = "file_lock", since = "1.89.0")]
866 pub fn lock(&self) -> io::Result<()> {
867 self.inner.lock()
868 }
869
870 /// Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.
871 ///
872 /// This acquires a shared lock; more than one file handle, in this or any other process, may
873 /// hold a shared lock, but none may hold an exclusive lock at the same time.
874 ///
875 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
876 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
877 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
878 /// cause non-lockholders to block.
879 ///
880 /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
881 /// is unspecified and platform dependent, including the possibility that it will deadlock.
882 /// However, if this method returns, then a shared lock is held.
883 ///
884 /// The lock will be released when this file (along with any other file descriptors/handles
885 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
886 ///
887 /// # Platform-specific behavior
888 ///
889 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
890 /// and the `LockFileEx` function on Windows. Note that, this
891 /// [may change in the future][changes].
892 ///
893 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
894 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
895 ///
896 /// [changes]: io#platform-specific-behavior
897 ///
898 /// [`lock`]: File::lock
899 /// [`lock_shared`]: File::lock_shared
900 /// [`try_lock`]: File::try_lock
901 /// [`try_lock_shared`]: File::try_lock_shared
902 /// [`unlock`]: File::unlock
903 /// [`read`]: Read::read
904 /// [`write`]: Write::write
905 ///
906 /// # Examples
907 ///
908 /// ```no_run
909 /// use std::fs::File;
910 ///
911 /// fn main() -> std::io::Result<()> {
912 /// let f = File::open("foo.txt")?;
913 /// f.lock_shared()?;
914 /// Ok(())
915 /// }
916 /// ```
917 #[stable(feature = "file_lock", since = "1.89.0")]
918 pub fn lock_shared(&self) -> io::Result<()> {
919 self.inner.lock_shared()
920 }
921
922 /// Try to acquire an exclusive lock on the file.
923 ///
924 /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
925 /// (via another handle/descriptor).
926 ///
927 /// This acquires an exclusive lock; no other file handle to this file, in this or any other
928 /// process, may acquire another lock.
929 ///
930 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
931 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
932 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
933 /// cause non-lockholders to block.
934 ///
935 /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
936 /// is unspecified and platform dependent, including the possibility that it will deadlock.
937 /// However, if this method returns `Ok(())`, then it has acquired an exclusive lock.
938 ///
939 /// If the file is not open for writing, it is unspecified whether this function returns an error.
940 ///
941 /// The lock will be released when this file (along with any other file descriptors/handles
942 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
943 ///
944 /// # Platform-specific behavior
945 ///
946 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
947 /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
948 /// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
949 /// [may change in the future][changes].
950 ///
951 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
952 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
953 ///
954 /// [changes]: io#platform-specific-behavior
955 ///
956 /// [`lock`]: File::lock
957 /// [`lock_shared`]: File::lock_shared
958 /// [`try_lock`]: File::try_lock
959 /// [`try_lock_shared`]: File::try_lock_shared
960 /// [`unlock`]: File::unlock
961 /// [`read`]: Read::read
962 /// [`write`]: Write::write
963 ///
964 /// # Examples
965 ///
966 /// ```no_run
967 /// use std::fs::{File, TryLockError};
968 ///
969 /// fn main() -> std::io::Result<()> {
970 /// let f = File::create("foo.txt")?;
971 /// // Explicit handling of the WouldBlock error
972 /// match f.try_lock() {
973 /// Ok(_) => (),
974 /// Err(TryLockError::WouldBlock) => (), // Lock not acquired
975 /// Err(TryLockError::Error(err)) => return Err(err),
976 /// }
977 /// // Alternately, propagate the error as an io::Error
978 /// f.try_lock()?;
979 /// Ok(())
980 /// }
981 /// ```
982 #[stable(feature = "file_lock", since = "1.89.0")]
983 pub fn try_lock(&self) -> Result<(), TryLockError> {
984 self.inner.try_lock()
985 }
986
987 /// Try to acquire a shared (non-exclusive) lock on the file.
988 ///
989 /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
990 /// (via another handle/descriptor).
991 ///
992 /// This acquires a shared lock; more than one file handle, in this or any other process, may
993 /// hold a shared lock, but none may hold an exclusive lock at the same time.
994 ///
995 /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
996 /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
997 /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
998 /// cause non-lockholders to block.
999 ///
1000 /// If this file handle, or a clone of it, already holds a lock, the exact behavior is
1001 /// unspecified and platform dependent, including the possibility that it will deadlock.
1002 /// However, if this method returns `Ok(())`, then it has acquired a shared lock.
1003 ///
1004 /// The lock will be released when this file (along with any other file descriptors/handles
1005 /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
1006 ///
1007 /// # Platform-specific behavior
1008 ///
1009 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
1010 /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
1011 /// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
1012 /// [may change in the future][changes].
1013 ///
1014 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
1015 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
1016 ///
1017 /// [changes]: io#platform-specific-behavior
1018 ///
1019 /// [`lock`]: File::lock
1020 /// [`lock_shared`]: File::lock_shared
1021 /// [`try_lock`]: File::try_lock
1022 /// [`try_lock_shared`]: File::try_lock_shared
1023 /// [`unlock`]: File::unlock
1024 /// [`read`]: Read::read
1025 /// [`write`]: Write::write
1026 ///
1027 /// # Examples
1028 ///
1029 /// ```no_run
1030 /// use std::fs::{File, TryLockError};
1031 ///
1032 /// fn main() -> std::io::Result<()> {
1033 /// let f = File::open("foo.txt")?;
1034 /// // Explicit handling of the WouldBlock error
1035 /// match f.try_lock_shared() {
1036 /// Ok(_) => (),
1037 /// Err(TryLockError::WouldBlock) => (), // Lock not acquired
1038 /// Err(TryLockError::Error(err)) => return Err(err),
1039 /// }
1040 /// // Alternately, propagate the error as an io::Error
1041 /// f.try_lock_shared()?;
1042 ///
1043 /// Ok(())
1044 /// }
1045 /// ```
1046 #[stable(feature = "file_lock", since = "1.89.0")]
1047 pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1048 self.inner.try_lock_shared()
1049 }
1050
1051 /// Release all locks on the file.
1052 ///
1053 /// All locks are released when the file (along with any other file descriptors/handles
1054 /// duplicated or inherited from it) is closed. This method allows releasing locks without
1055 /// closing the file.
1056 ///
1057 /// If no lock is currently held via this file descriptor/handle, this method may return an
1058 /// error, or may return successfully without taking any action.
1059 ///
1060 /// # Platform-specific behavior
1061 ///
1062 /// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
1063 /// and the `UnlockFile` function on Windows. Note that, this
1064 /// [may change in the future][changes].
1065 ///
1066 /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
1067 /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
1068 ///
1069 /// [changes]: io#platform-specific-behavior
1070 ///
1071 /// # Examples
1072 ///
1073 /// ```no_run
1074 /// use std::fs::File;
1075 ///
1076 /// fn main() -> std::io::Result<()> {
1077 /// let f = File::open("foo.txt")?;
1078 /// f.lock()?;
1079 /// f.unlock()?;
1080 /// Ok(())
1081 /// }
1082 /// ```
1083 #[stable(feature = "file_lock", since = "1.89.0")]
1084 pub fn unlock(&self) -> io::Result<()> {
1085 self.inner.unlock()
1086 }
1087
1088 /// Truncates or extends the underlying file, updating the size of
1089 /// this file to become `size`.
1090 ///
1091 /// If the `size` is less than the current file's size, then the file will
1092 /// be shrunk. If it is greater than the current file's size, then the file
1093 /// will be extended to `size` and have all of the intermediate data filled
1094 /// in with 0s.
1095 ///
1096 /// The file's cursor isn't changed. In particular, if the cursor was at the
1097 /// end and the file is shrunk using this operation, the cursor will now be
1098 /// past the end.
1099 ///
1100 /// # Errors
1101 ///
1102 /// This function will return an error if the file is not opened for writing.
1103 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
1104 /// will be returned if the desired length would cause an overflow due to
1105 /// the implementation specifics.
1106 ///
1107 /// # Examples
1108 ///
1109 /// ```no_run
1110 /// use std::fs::File;
1111 ///
1112 /// fn main() -> std::io::Result<()> {
1113 /// let mut f = File::create("foo.txt")?;
1114 /// f.set_len(10)?;
1115 /// Ok(())
1116 /// }
1117 /// ```
1118 ///
1119 /// Note that this method alters the content of the underlying file, even
1120 /// though it takes `&self` rather than `&mut self`.
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 pub fn set_len(&self, size: u64) -> io::Result<()> {
1123 self.inner.truncate(size)
1124 }
1125
1126 /// Queries metadata about the underlying file.
1127 ///
1128 /// # Examples
1129 ///
1130 /// ```no_run
1131 /// use std::fs::File;
1132 ///
1133 /// fn main() -> std::io::Result<()> {
1134 /// let mut f = File::open("foo.txt")?;
1135 /// let metadata = f.metadata()?;
1136 /// Ok(())
1137 /// }
1138 /// ```
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn metadata(&self) -> io::Result<Metadata> {
1141 self.inner.file_attr().map(Metadata)
1142 }
1143
1144 /// Creates a new `File` instance that shares the same underlying file handle
1145 /// as the existing `File` instance. Reads, writes, and seeks will affect
1146 /// both `File` instances simultaneously.
1147 ///
1148 /// # Examples
1149 ///
1150 /// Creates two handles for a file named `foo.txt`:
1151 ///
1152 /// ```no_run
1153 /// use std::fs::File;
1154 ///
1155 /// fn main() -> std::io::Result<()> {
1156 /// let mut file = File::open("foo.txt")?;
1157 /// let file_copy = file.try_clone()?;
1158 /// Ok(())
1159 /// }
1160 /// ```
1161 ///
1162 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
1163 /// two handles, seek one of them, and read the remaining bytes from the
1164 /// other handle:
1165 ///
1166 /// ```no_run
1167 /// use std::fs::File;
1168 /// use std::io::SeekFrom;
1169 /// use std::io::prelude::*;
1170 ///
1171 /// fn main() -> std::io::Result<()> {
1172 /// let mut file = File::open("foo.txt")?;
1173 /// let mut file_copy = file.try_clone()?;
1174 ///
1175 /// file.seek(SeekFrom::Start(3))?;
1176 ///
1177 /// let mut contents = vec![];
1178 /// file_copy.read_to_end(&mut contents)?;
1179 /// assert_eq!(contents, b"def\n");
1180 /// Ok(())
1181 /// }
1182 /// ```
1183 #[stable(feature = "file_try_clone", since = "1.9.0")]
1184 pub fn try_clone(&self) -> io::Result<File> {
1185 Ok(File { inner: self.inner.duplicate()? })
1186 }
1187
1188 /// Changes the permissions on the underlying file.
1189 ///
1190 /// # Platform-specific behavior
1191 ///
1192 /// This function currently corresponds to the `fchmod` function on Unix and
1193 /// the `SetFileInformationByHandle` function on Windows. Note that, this
1194 /// [may change in the future][changes].
1195 ///
1196 /// [changes]: io#platform-specific-behavior
1197 ///
1198 /// # Errors
1199 ///
1200 /// This function will return an error if the user lacks permission change
1201 /// attributes on the underlying file. It may also return an error in other
1202 /// os-specific unspecified cases.
1203 ///
1204 /// # Examples
1205 ///
1206 /// ```no_run
1207 /// fn main() -> std::io::Result<()> {
1208 /// use std::fs::File;
1209 ///
1210 /// let file = File::open("foo.txt")?;
1211 /// let mut perms = file.metadata()?.permissions();
1212 /// perms.set_readonly(true);
1213 /// file.set_permissions(perms)?;
1214 /// Ok(())
1215 /// }
1216 /// ```
1217 ///
1218 /// Note that this method alters the permissions of the underlying file,
1219 /// even though it takes `&self` rather than `&mut self`.
1220 #[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
1221 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
1222 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
1223 self.inner.set_permissions(perm.0)
1224 }
1225
1226 /// Changes the timestamps of the underlying file.
1227 ///
1228 /// # Platform-specific behavior
1229 ///
1230 /// This function currently corresponds to the `futimens` function on Unix (falling back to
1231 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
1232 /// [may change in the future][changes].
1233 ///
1234 /// On most platforms, including UNIX and Windows platforms, this function can also change the
1235 /// timestamps of a directory. To get a `File` representing a directory in order to call
1236 /// `set_times`, open the directory with `File::open` without attempting to obtain write
1237 /// permission.
1238 ///
1239 /// [changes]: io#platform-specific-behavior
1240 ///
1241 /// # Errors
1242 ///
1243 /// This function will return an error if the user lacks permission to change timestamps on the
1244 /// underlying file. It may also return an error in other os-specific unspecified cases.
1245 ///
1246 /// This function may return an error if the operating system lacks support to change one or
1247 /// more of the timestamps set in the `FileTimes` structure.
1248 ///
1249 /// # Examples
1250 ///
1251 /// ```no_run
1252 /// fn main() -> std::io::Result<()> {
1253 /// use std::fs::{self, File, FileTimes};
1254 ///
1255 /// let src = fs::metadata("src")?;
1256 /// let dest = File::open("dest")?;
1257 /// let times = FileTimes::new()
1258 /// .set_accessed(src.accessed()?)
1259 /// .set_modified(src.modified()?);
1260 /// dest.set_times(times)?;
1261 /// Ok(())
1262 /// }
1263 /// ```
1264 #[stable(feature = "file_set_times", since = "1.75.0")]
1265 #[doc(alias = "futimens")]
1266 #[doc(alias = "futimes")]
1267 #[doc(alias = "SetFileTime")]
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
1603impl AsInner<fs_imp::Dir> for Dir {
1604 #[inline]
1605 fn as_inner(&self) -> &fs_imp::Dir {
1606 &self.inner
1607 }
1608}
1609impl FromInner<fs_imp::Dir> for Dir {
1610 fn from_inner(f: fs_imp::Dir) -> Dir {
1611 Dir { inner: f }
1612 }
1613}
1614impl IntoInner<fs_imp::Dir> for Dir {
1615 fn into_inner(self) -> fs_imp::Dir {
1616 self.inner
1617 }
1618}
1619
1620#[unstable(feature = "dirfd", issue = "120426")]
1621impl fmt::Debug for Dir {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 self.inner.fmt(f)
1624 }
1625}
1626
1627impl OpenOptions {
1628 /// Creates a blank new set of options ready for configuration.
1629 ///
1630 /// All options are initially set to `false`.
1631 ///
1632 /// # Examples
1633 ///
1634 /// ```no_run
1635 /// use std::fs::OpenOptions;
1636 ///
1637 /// let mut options = OpenOptions::new();
1638 /// let file = options.read(true).open("foo.txt");
1639 /// ```
1640 #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 #[must_use]
1643 pub fn new() -> Self {
1644 OpenOptions(fs_imp::OpenOptions::new())
1645 }
1646
1647 /// Sets the option for read access.
1648 ///
1649 /// This option, when true, will indicate that the file should be
1650 /// `read`-able if opened.
1651 ///
1652 /// # Examples
1653 ///
1654 /// ```no_run
1655 /// use std::fs::OpenOptions;
1656 ///
1657 /// let file = OpenOptions::new().read(true).open("foo.txt");
1658 /// ```
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 pub fn read(&mut self, read: bool) -> &mut Self {
1661 self.0.read(read);
1662 self
1663 }
1664
1665 /// Sets the option for write access.
1666 ///
1667 /// This option, when true, will indicate that the file should be
1668 /// `write`-able if opened.
1669 ///
1670 /// If the file already exists, any write calls on it will overwrite its
1671 /// contents, without truncating it.
1672 ///
1673 /// # Examples
1674 ///
1675 /// ```no_run
1676 /// use std::fs::OpenOptions;
1677 ///
1678 /// let file = OpenOptions::new().write(true).open("foo.txt");
1679 /// ```
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 pub fn write(&mut self, write: bool) -> &mut Self {
1682 self.0.write(write);
1683 self
1684 }
1685
1686 /// Sets the option for the append mode.
1687 ///
1688 /// This option, when true, means that writes will append to a file instead
1689 /// of overwriting previous contents.
1690 /// Note that setting `.write(true).append(true)` has the same effect as
1691 /// setting only `.append(true)`.
1692 ///
1693 /// Append mode guarantees that writes will be positioned at the current end of file,
1694 /// even when there are other processes or threads appending to the same file. This is
1695 /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
1696 /// has a race between seeking and writing during which another writer can write, with
1697 /// our `write()` overwriting their data.
1698 ///
1699 /// Keep in mind that this does not necessarily guarantee that data appended by
1700 /// different processes or threads does not interleave. The amount of data accepted a
1701 /// single `write()` call depends on the operating system and file system. A
1702 /// successful `write()` is allowed to write only part of the given data, so even if
1703 /// you're careful to provide the whole message in a single call to `write()`, there
1704 /// is no guarantee that it will be written out in full. If you rely on the filesystem
1705 /// accepting the message in a single write, make sure that all data that belongs
1706 /// together is written in one operation. This can be done by concatenating strings
1707 /// before passing them to [`write()`].
1708 ///
1709 /// If a file is opened with both read and append access, beware that after
1710 /// opening, and after every write, the position for reading may be set at the
1711 /// end of the file. So, before writing, save the current position (using
1712 /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
1713 ///
1714 /// ## Note
1715 ///
1716 /// This function doesn't create the file if it doesn't exist. Use the
1717 /// [`OpenOptions::create`] method to do so.
1718 ///
1719 /// [`write()`]: Write::write "io::Write::write"
1720 /// [`flush()`]: Write::flush "io::Write::flush"
1721 /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
1722 /// [seek]: Seek::seek "io::Seek::seek"
1723 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
1724 /// [End]: SeekFrom::End "io::SeekFrom::End"
1725 ///
1726 /// # Examples
1727 ///
1728 /// ```no_run
1729 /// use std::fs::OpenOptions;
1730 ///
1731 /// let file = OpenOptions::new().append(true).open("foo.txt");
1732 /// ```
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub fn append(&mut self, append: bool) -> &mut Self {
1735 self.0.append(append);
1736 self
1737 }
1738
1739 /// Sets the option for truncating a previous file.
1740 ///
1741 /// If a file is successfully opened with this option set to true, it will truncate
1742 /// the file to 0 length if it already exists.
1743 ///
1744 /// The file must be opened with write access for truncate to work.
1745 ///
1746 /// # Examples
1747 ///
1748 /// ```no_run
1749 /// use std::fs::OpenOptions;
1750 ///
1751 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
1752 /// ```
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
1755 self.0.truncate(truncate);
1756 self
1757 }
1758
1759 /// Sets the option to create a new file, or open it if it already exists.
1760 ///
1761 /// In order for the file to be created, [`OpenOptions::write`] or
1762 /// [`OpenOptions::append`] access must be used.
1763 ///
1764 /// See also [`std::fs::write()`][self::write] for a simple function to
1765 /// create a file with some given data.
1766 ///
1767 /// # Errors
1768 ///
1769 /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
1770 /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
1771 /// # Examples
1772 ///
1773 /// ```no_run
1774 /// use std::fs::OpenOptions;
1775 ///
1776 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
1777 /// ```
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 pub fn create(&mut self, create: bool) -> &mut Self {
1780 self.0.create(create);
1781 self
1782 }
1783
1784 /// Sets the option to create a new file, failing if it already exists.
1785 ///
1786 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1787 /// way, if the call succeeds, the file returned is guaranteed to be new.
1788 /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
1789 /// or another error based on the situation. See [`OpenOptions::open`] for a
1790 /// non-exhaustive list of likely errors.
1791 ///
1792 /// This option is useful because it is atomic. Otherwise between checking
1793 /// whether a file exists and creating a new one, the file may have been
1794 /// created by another process (a [TOCTOU] race condition / attack).
1795 ///
1796 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1797 /// ignored.
1798 ///
1799 /// The file must be opened with write or append access in order to create
1800 /// a new file.
1801 ///
1802 /// [`.create()`]: OpenOptions::create
1803 /// [`.truncate()`]: OpenOptions::truncate
1804 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1805 /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
1806 ///
1807 /// # Examples
1808 ///
1809 /// ```no_run
1810 /// use std::fs::OpenOptions;
1811 ///
1812 /// let file = OpenOptions::new().write(true)
1813 /// .create_new(true)
1814 /// .open("foo.txt");
1815 /// ```
1816 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1817 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1818 self.0.create_new(create_new);
1819 self
1820 }
1821
1822 /// Opens a file at `path` with the options specified by `self`.
1823 ///
1824 /// # Errors
1825 ///
1826 /// This function will return an error under a number of different
1827 /// circumstances. Some of these error conditions are listed here, together
1828 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1829 /// part of the compatibility contract of the function.
1830 ///
1831 /// * [`NotFound`]: The specified file does not exist and neither `create`
1832 /// or `create_new` is set.
1833 /// * [`NotFound`]: One of the directory components of the file path does
1834 /// not exist.
1835 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1836 /// access rights for the file.
1837 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1838 /// directory components of the specified path.
1839 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1840 /// exists.
1841 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1842 /// without write access, create without write or append access,
1843 /// no access mode set, etc.).
1844 ///
1845 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1846 /// * One of the directory components of the specified file path
1847 /// was not, in fact, a directory.
1848 /// * Filesystem-level errors: full disk, write permission
1849 /// requested on a read-only file system, exceeded disk quota, too many
1850 /// open files, too long filename, too many symbolic links in the
1851 /// specified path (Unix-like systems only), etc.
1852 ///
1853 /// # Examples
1854 ///
1855 /// ```no_run
1856 /// use std::fs::OpenOptions;
1857 ///
1858 /// let file = OpenOptions::new().read(true).open("foo.txt");
1859 /// ```
1860 ///
1861 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1862 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1863 /// [`NotFound`]: io::ErrorKind::NotFound
1864 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1867 self._open(path.as_ref())
1868 }
1869
1870 fn _open(&self, path: &Path) -> io::Result<File> {
1871 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1872 }
1873}
1874
1875impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1876 #[inline]
1877 fn as_inner(&self) -> &fs_imp::OpenOptions {
1878 &self.0
1879 }
1880}
1881
1882impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1883 #[inline]
1884 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1885 &mut self.0
1886 }
1887}
1888
1889impl Metadata {
1890 /// Returns the file type for this metadata.
1891 ///
1892 /// # Examples
1893 ///
1894 /// ```no_run
1895 /// fn main() -> std::io::Result<()> {
1896 /// use std::fs;
1897 ///
1898 /// let metadata = fs::metadata("foo.txt")?;
1899 ///
1900 /// println!("{:?}", metadata.file_type());
1901 /// Ok(())
1902 /// }
1903 /// ```
1904 #[must_use]
1905 #[stable(feature = "file_type", since = "1.1.0")]
1906 pub fn file_type(&self) -> FileType {
1907 FileType(self.0.file_type())
1908 }
1909
1910 /// Returns `true` if this metadata is for a directory. The
1911 /// result is mutually exclusive to the result of
1912 /// [`Metadata::is_file`], and will be false for symlink metadata
1913 /// obtained from [`symlink_metadata`].
1914 ///
1915 /// # Examples
1916 ///
1917 /// ```no_run
1918 /// fn main() -> std::io::Result<()> {
1919 /// use std::fs;
1920 ///
1921 /// let metadata = fs::metadata("foo.txt")?;
1922 ///
1923 /// assert!(!metadata.is_dir());
1924 /// Ok(())
1925 /// }
1926 /// ```
1927 #[must_use]
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub fn is_dir(&self) -> bool {
1930 self.file_type().is_dir()
1931 }
1932
1933 /// Returns `true` if this metadata is for a regular file. The
1934 /// result is mutually exclusive to the result of
1935 /// [`Metadata::is_dir`], and will be false for symlink metadata
1936 /// obtained from [`symlink_metadata`].
1937 ///
1938 /// When the goal is simply to read from (or write to) the source, the most
1939 /// reliable way to test the source can be read (or written to) is to open
1940 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1941 /// a Unix-like system for example. See [`File::open`] or
1942 /// [`OpenOptions::open`] for more information.
1943 ///
1944 /// # Examples
1945 ///
1946 /// ```no_run
1947 /// use std::fs;
1948 ///
1949 /// fn main() -> std::io::Result<()> {
1950 /// let metadata = fs::metadata("foo.txt")?;
1951 ///
1952 /// assert!(metadata.is_file());
1953 /// Ok(())
1954 /// }
1955 /// ```
1956 #[must_use]
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 pub fn is_file(&self) -> bool {
1959 self.file_type().is_file()
1960 }
1961
1962 /// Returns `true` if this metadata is for a symbolic link.
1963 ///
1964 /// # Examples
1965 ///
1966 #[cfg_attr(unix, doc = "```no_run")]
1967 #[cfg_attr(not(unix), doc = "```ignore")]
1968 /// use std::fs;
1969 /// use std::path::Path;
1970 /// use std::os::unix::fs::symlink;
1971 ///
1972 /// fn main() -> std::io::Result<()> {
1973 /// let link_path = Path::new("link");
1974 /// symlink("/origin_does_not_exist/", link_path)?;
1975 ///
1976 /// let metadata = fs::symlink_metadata(link_path)?;
1977 ///
1978 /// assert!(metadata.is_symlink());
1979 /// Ok(())
1980 /// }
1981 /// ```
1982 #[must_use]
1983 #[stable(feature = "is_symlink", since = "1.58.0")]
1984 pub fn is_symlink(&self) -> bool {
1985 self.file_type().is_symlink()
1986 }
1987
1988 /// Returns the size of the file, in bytes, this metadata is for.
1989 ///
1990 /// # Examples
1991 ///
1992 /// ```no_run
1993 /// use std::fs;
1994 ///
1995 /// fn main() -> std::io::Result<()> {
1996 /// let metadata = fs::metadata("foo.txt")?;
1997 ///
1998 /// assert_eq!(0, metadata.len());
1999 /// Ok(())
2000 /// }
2001 /// ```
2002 #[must_use]
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 pub fn len(&self) -> u64 {
2005 self.0.size()
2006 }
2007
2008 /// Returns the permissions of the file this metadata is for.
2009 ///
2010 /// # Examples
2011 ///
2012 /// ```no_run
2013 /// use std::fs;
2014 ///
2015 /// fn main() -> std::io::Result<()> {
2016 /// let metadata = fs::metadata("foo.txt")?;
2017 ///
2018 /// assert!(!metadata.permissions().readonly());
2019 /// Ok(())
2020 /// }
2021 /// ```
2022 #[must_use]
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 pub fn permissions(&self) -> Permissions {
2025 Permissions(self.0.perm())
2026 }
2027
2028 /// Returns the last modification time listed in this metadata.
2029 ///
2030 /// The returned value corresponds to the `mtime` field of `stat` on Unix
2031 /// platforms and the `ftLastWriteTime` field on Windows platforms.
2032 ///
2033 /// # Errors
2034 ///
2035 /// This field might not be available on all platforms, and will return an
2036 /// `Err` on platforms where it is not available.
2037 ///
2038 /// # Examples
2039 ///
2040 /// ```no_run
2041 /// use std::fs;
2042 ///
2043 /// fn main() -> std::io::Result<()> {
2044 /// let metadata = fs::metadata("foo.txt")?;
2045 ///
2046 /// if let Ok(time) = metadata.modified() {
2047 /// println!("{time:?}");
2048 /// } else {
2049 /// println!("Not supported on this platform");
2050 /// }
2051 /// Ok(())
2052 /// }
2053 /// ```
2054 #[doc(alias = "mtime", alias = "ftLastWriteTime")]
2055 #[stable(feature = "fs_time", since = "1.10.0")]
2056 pub fn modified(&self) -> io::Result<SystemTime> {
2057 self.0.modified().map(FromInner::from_inner)
2058 }
2059
2060 /// Returns the last access time of this metadata.
2061 ///
2062 /// The returned value corresponds to the `atime` field of `stat` on Unix
2063 /// platforms and the `ftLastAccessTime` field on Windows platforms.
2064 ///
2065 /// Note that not all platforms will keep this field update in a file's
2066 /// metadata, for example Windows has an option to disable updating this
2067 /// time when files are accessed and Linux similarly has `noatime`.
2068 ///
2069 /// # Errors
2070 ///
2071 /// This field might not be available on all platforms, and will return an
2072 /// `Err` on platforms where it is not available.
2073 ///
2074 /// # Examples
2075 ///
2076 /// ```no_run
2077 /// use std::fs;
2078 ///
2079 /// fn main() -> std::io::Result<()> {
2080 /// let metadata = fs::metadata("foo.txt")?;
2081 ///
2082 /// if let Ok(time) = metadata.accessed() {
2083 /// println!("{time:?}");
2084 /// } else {
2085 /// println!("Not supported on this platform");
2086 /// }
2087 /// Ok(())
2088 /// }
2089 /// ```
2090 #[doc(alias = "atime", alias = "ftLastAccessTime")]
2091 #[stable(feature = "fs_time", since = "1.10.0")]
2092 pub fn accessed(&self) -> io::Result<SystemTime> {
2093 self.0.accessed().map(FromInner::from_inner)
2094 }
2095
2096 /// Returns the creation time listed in this metadata.
2097 ///
2098 /// The returned value corresponds to the `btime` field of `statx` on
2099 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
2100 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
2101 ///
2102 /// # Errors
2103 ///
2104 /// This field might not be available on all platforms, and will return an
2105 /// `Err` on platforms or filesystems where it is not available.
2106 ///
2107 /// # Examples
2108 ///
2109 /// ```no_run
2110 /// use std::fs;
2111 ///
2112 /// fn main() -> std::io::Result<()> {
2113 /// let metadata = fs::metadata("foo.txt")?;
2114 ///
2115 /// if let Ok(time) = metadata.created() {
2116 /// println!("{time:?}");
2117 /// } else {
2118 /// println!("Not supported on this platform or filesystem");
2119 /// }
2120 /// Ok(())
2121 /// }
2122 /// ```
2123 #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
2124 #[stable(feature = "fs_time", since = "1.10.0")]
2125 pub fn created(&self) -> io::Result<SystemTime> {
2126 self.0.created().map(FromInner::from_inner)
2127 }
2128}
2129
2130#[stable(feature = "std_debug", since = "1.16.0")]
2131impl fmt::Debug for Metadata {
2132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2133 let mut debug = f.debug_struct("Metadata");
2134 debug.field("file_type", &self.file_type());
2135 debug.field("permissions", &self.permissions());
2136 debug.field("len", &self.len());
2137 if let Ok(modified) = self.modified() {
2138 debug.field("modified", &modified);
2139 }
2140 if let Ok(accessed) = self.accessed() {
2141 debug.field("accessed", &accessed);
2142 }
2143 if let Ok(created) = self.created() {
2144 debug.field("created", &created);
2145 }
2146 debug.finish_non_exhaustive()
2147 }
2148}
2149
2150impl AsInner<fs_imp::FileAttr> for Metadata {
2151 #[inline]
2152 fn as_inner(&self) -> &fs_imp::FileAttr {
2153 &self.0
2154 }
2155}
2156
2157impl FromInner<fs_imp::FileAttr> for Metadata {
2158 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2159 Metadata(attr)
2160 }
2161}
2162
2163impl FileTimes {
2164 /// Creates a new `FileTimes` with no times set.
2165 ///
2166 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2167 #[stable(feature = "file_set_times", since = "1.75.0")]
2168 pub fn new() -> Self {
2169 Self::default()
2170 }
2171
2172 /// Set the last access time of a file.
2173 #[stable(feature = "file_set_times", since = "1.75.0")]
2174 pub fn set_accessed(mut self, t: SystemTime) -> Self {
2175 self.0.set_accessed(t.into_inner());
2176 self
2177 }
2178
2179 /// Set the last modified time of a file.
2180 #[stable(feature = "file_set_times", since = "1.75.0")]
2181 pub fn set_modified(mut self, t: SystemTime) -> Self {
2182 self.0.set_modified(t.into_inner());
2183 self
2184 }
2185}
2186
2187impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2188 fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2189 &mut self.0
2190 }
2191}
2192
2193// For implementing OS extension traits in `std::os`
2194#[stable(feature = "file_set_times", since = "1.75.0")]
2195impl Sealed for FileTimes {}
2196
2197impl Permissions {
2198 /// Returns `true` if these permissions describe a readonly (unwritable) file.
2199 ///
2200 /// # Note
2201 ///
2202 /// This function does not take Access Control Lists (ACLs), Unix group
2203 /// membership and other nuances into account.
2204 /// Therefore the return value of this function cannot be relied upon
2205 /// to predict whether attempts to read or write the file will actually succeed.
2206 ///
2207 /// # Windows
2208 ///
2209 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2210 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2211 /// but the user may still have permission to change this flag. If
2212 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2213 /// to lack of write permission.
2214 /// The behavior of this attribute for directories depends on the Windows
2215 /// version.
2216 ///
2217 /// # Unix (including macOS)
2218 ///
2219 /// On Unix-based platforms this checks if *any* of the owner, group or others
2220 /// write permission bits are set. It does not consider anything else, including:
2221 ///
2222 /// * Whether the current user is in the file's assigned group.
2223 /// * Permissions granted by ACL.
2224 /// * That `root` user can write to files that do not have any write bits set.
2225 /// * Writable files on a filesystem that is mounted read-only.
2226 ///
2227 /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2228 /// also does not read ACLs.
2229 ///
2230 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2231 ///
2232 /// # Examples
2233 ///
2234 /// ```no_run
2235 /// use std::fs::File;
2236 ///
2237 /// fn main() -> std::io::Result<()> {
2238 /// let mut f = File::create("foo.txt")?;
2239 /// let metadata = f.metadata()?;
2240 ///
2241 /// assert_eq!(false, metadata.permissions().readonly());
2242 /// Ok(())
2243 /// }
2244 /// ```
2245 #[must_use = "call `set_readonly` to modify the readonly flag"]
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 pub fn readonly(&self) -> bool {
2248 self.0.readonly()
2249 }
2250
2251 /// Modifies the readonly flag for this set of permissions. If the
2252 /// `readonly` argument is `true`, using the resulting `Permission` will
2253 /// update file permissions to forbid writing. Conversely, if it's `false`,
2254 /// using the resulting `Permission` will update file permissions to allow
2255 /// writing.
2256 ///
2257 /// This operation does **not** modify the files attributes. This only
2258 /// changes the in-memory value of these attributes for this `Permissions`
2259 /// instance. To modify the files attributes use the [`set_permissions`]
2260 /// function which commits these attribute changes to the file.
2261 ///
2262 /// # Note
2263 ///
2264 /// `set_readonly(false)` makes the file *world-writable* on Unix.
2265 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2266 ///
2267 /// It also does not take Access Control Lists (ACLs) or Unix group
2268 /// membership into account.
2269 ///
2270 /// # Windows
2271 ///
2272 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2273 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2274 /// but the user may still have permission to change this flag. If
2275 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2276 /// the user does not have permission to write to the file.
2277 ///
2278 /// In Windows 7 and earlier this attribute prevents deleting empty
2279 /// directories. It does not prevent modifying the directory contents.
2280 /// On later versions of Windows this attribute is ignored for directories.
2281 ///
2282 /// # Unix (including macOS)
2283 ///
2284 /// On Unix-based platforms this sets or clears the write access bit for
2285 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2286 /// or `chmod a-w <file>` respectively. The latter will grant write access
2287 /// to all users! You can use the [`PermissionsExt`] trait on Unix
2288 /// to avoid this issue.
2289 ///
2290 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2291 ///
2292 /// # Examples
2293 ///
2294 /// ```no_run
2295 /// use std::fs::File;
2296 ///
2297 /// fn main() -> std::io::Result<()> {
2298 /// let f = File::create("foo.txt")?;
2299 /// let metadata = f.metadata()?;
2300 /// let mut permissions = metadata.permissions();
2301 ///
2302 /// permissions.set_readonly(true);
2303 ///
2304 /// // filesystem doesn't change, only the in memory state of the
2305 /// // readonly permission
2306 /// assert_eq!(false, metadata.permissions().readonly());
2307 ///
2308 /// // just this particular `permissions`.
2309 /// assert_eq!(true, permissions.readonly());
2310 /// Ok(())
2311 /// }
2312 /// ```
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 pub fn set_readonly(&mut self, readonly: bool) {
2315 self.0.set_readonly(readonly)
2316 }
2317}
2318
2319impl FileType {
2320 /// Tests whether this file type represents a directory. The
2321 /// result is mutually exclusive to the results of
2322 /// [`is_file`] and [`is_symlink`]; only zero or one of these
2323 /// tests may pass.
2324 ///
2325 /// [`is_file`]: FileType::is_file
2326 /// [`is_symlink`]: FileType::is_symlink
2327 ///
2328 /// # Examples
2329 ///
2330 /// ```no_run
2331 /// fn main() -> std::io::Result<()> {
2332 /// use std::fs;
2333 ///
2334 /// let metadata = fs::metadata("foo.txt")?;
2335 /// let file_type = metadata.file_type();
2336 ///
2337 /// assert_eq!(file_type.is_dir(), false);
2338 /// Ok(())
2339 /// }
2340 /// ```
2341 #[must_use]
2342 #[stable(feature = "file_type", since = "1.1.0")]
2343 pub fn is_dir(&self) -> bool {
2344 self.0.is_dir()
2345 }
2346
2347 /// Tests whether this file type represents a regular file.
2348 /// The result is mutually exclusive to the results of
2349 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2350 /// tests may pass.
2351 ///
2352 /// When the goal is simply to read from (or write to) the source, the most
2353 /// reliable way to test the source can be read (or written to) is to open
2354 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2355 /// a Unix-like system for example. See [`File::open`] or
2356 /// [`OpenOptions::open`] for more information.
2357 ///
2358 /// [`is_dir`]: FileType::is_dir
2359 /// [`is_symlink`]: FileType::is_symlink
2360 ///
2361 /// # Examples
2362 ///
2363 /// ```no_run
2364 /// fn main() -> std::io::Result<()> {
2365 /// use std::fs;
2366 ///
2367 /// let metadata = fs::metadata("foo.txt")?;
2368 /// let file_type = metadata.file_type();
2369 ///
2370 /// assert_eq!(file_type.is_file(), true);
2371 /// Ok(())
2372 /// }
2373 /// ```
2374 #[must_use]
2375 #[stable(feature = "file_type", since = "1.1.0")]
2376 pub fn is_file(&self) -> bool {
2377 self.0.is_file()
2378 }
2379
2380 /// Tests whether this file type represents a symbolic link.
2381 /// The result is mutually exclusive to the results of
2382 /// [`is_dir`] and [`is_file`]; only zero or one of these
2383 /// tests may pass.
2384 ///
2385 /// The underlying [`Metadata`] struct needs to be retrieved
2386 /// with the [`fs::symlink_metadata`] function and not the
2387 /// [`fs::metadata`] function. The [`fs::metadata`] function
2388 /// follows symbolic links, so [`is_symlink`] would always
2389 /// return `false` for the target file.
2390 ///
2391 /// [`fs::metadata`]: metadata
2392 /// [`fs::symlink_metadata`]: symlink_metadata
2393 /// [`is_dir`]: FileType::is_dir
2394 /// [`is_file`]: FileType::is_file
2395 /// [`is_symlink`]: FileType::is_symlink
2396 ///
2397 /// # Examples
2398 ///
2399 /// ```no_run
2400 /// use std::fs;
2401 ///
2402 /// fn main() -> std::io::Result<()> {
2403 /// let metadata = fs::symlink_metadata("foo.txt")?;
2404 /// let file_type = metadata.file_type();
2405 ///
2406 /// assert_eq!(file_type.is_symlink(), false);
2407 /// Ok(())
2408 /// }
2409 /// ```
2410 #[must_use]
2411 #[stable(feature = "file_type", since = "1.1.0")]
2412 pub fn is_symlink(&self) -> bool {
2413 self.0.is_symlink()
2414 }
2415}
2416
2417#[stable(feature = "std_debug", since = "1.16.0")]
2418impl fmt::Debug for FileType {
2419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2420 f.debug_struct("FileType")
2421 .field("is_file", &self.is_file())
2422 .field("is_dir", &self.is_dir())
2423 .field("is_symlink", &self.is_symlink())
2424 .finish_non_exhaustive()
2425 }
2426}
2427
2428impl AsInner<fs_imp::FileType> for FileType {
2429 #[inline]
2430 fn as_inner(&self) -> &fs_imp::FileType {
2431 &self.0
2432 }
2433}
2434
2435impl FromInner<fs_imp::FilePermissions> for Permissions {
2436 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2437 Permissions(f)
2438 }
2439}
2440
2441impl AsInner<fs_imp::FilePermissions> for Permissions {
2442 #[inline]
2443 fn as_inner(&self) -> &fs_imp::FilePermissions {
2444 &self.0
2445 }
2446}
2447
2448#[stable(feature = "rust1", since = "1.0.0")]
2449impl Iterator for ReadDir {
2450 type Item = io::Result<DirEntry>;
2451
2452 fn next(&mut self) -> Option<io::Result<DirEntry>> {
2453 self.0.next().map(|entry| entry.map(DirEntry))
2454 }
2455}
2456
2457impl DirEntry {
2458 /// Returns the full path to the file that this entry represents.
2459 ///
2460 /// The full path is created by joining the original path to `read_dir`
2461 /// with the filename of this entry.
2462 ///
2463 /// # Examples
2464 ///
2465 /// ```no_run
2466 /// use std::fs;
2467 ///
2468 /// fn main() -> std::io::Result<()> {
2469 /// for entry in fs::read_dir(".")? {
2470 /// let dir = entry?;
2471 /// println!("{:?}", dir.path());
2472 /// }
2473 /// Ok(())
2474 /// }
2475 /// ```
2476 ///
2477 /// This prints output like:
2478 ///
2479 /// ```text
2480 /// "./whatever.txt"
2481 /// "./foo.html"
2482 /// "./hello_world.rs"
2483 /// ```
2484 ///
2485 /// The exact text, of course, depends on what files you have in `.`.
2486 #[must_use]
2487 #[stable(feature = "rust1", since = "1.0.0")]
2488 pub fn path(&self) -> PathBuf {
2489 self.0.path()
2490 }
2491
2492 /// Returns the metadata for the file that this entry points at.
2493 ///
2494 /// This function will not traverse symlinks if this entry points at a
2495 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2496 ///
2497 /// [`fs::metadata`]: metadata
2498 /// [`fs::File::metadata`]: File::metadata
2499 ///
2500 /// # Platform-specific behavior
2501 ///
2502 /// On Windows this function is cheap to call (no extra system calls
2503 /// needed), but on Unix platforms this function is the equivalent of
2504 /// calling `symlink_metadata` on the path.
2505 ///
2506 /// # Examples
2507 ///
2508 /// ```
2509 /// use std::fs;
2510 ///
2511 /// if let Ok(entries) = fs::read_dir(".") {
2512 /// for entry in entries {
2513 /// if let Ok(entry) = entry {
2514 /// // Here, `entry` is a `DirEntry`.
2515 /// if let Ok(metadata) = entry.metadata() {
2516 /// // Now let's show our entry's permissions!
2517 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
2518 /// } else {
2519 /// println!("Couldn't get metadata for {:?}", entry.path());
2520 /// }
2521 /// }
2522 /// }
2523 /// }
2524 /// ```
2525 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2526 pub fn metadata(&self) -> io::Result<Metadata> {
2527 self.0.metadata().map(Metadata)
2528 }
2529
2530 /// Returns the file type for the file that this entry points at.
2531 ///
2532 /// This function will not traverse symlinks if this entry points at a
2533 /// symlink.
2534 ///
2535 /// # Platform-specific behavior
2536 ///
2537 /// On Windows and most Unix platforms this function is free (no extra
2538 /// system calls needed), but some Unix platforms may require the equivalent
2539 /// call to `symlink_metadata` to learn about the target file type.
2540 ///
2541 /// # Examples
2542 ///
2543 /// ```
2544 /// use std::fs;
2545 ///
2546 /// if let Ok(entries) = fs::read_dir(".") {
2547 /// for entry in entries {
2548 /// if let Ok(entry) = entry {
2549 /// // Here, `entry` is a `DirEntry`.
2550 /// if let Ok(file_type) = entry.file_type() {
2551 /// // Now let's show our entry's file type!
2552 /// println!("{:?}: {:?}", entry.path(), file_type);
2553 /// } else {
2554 /// println!("Couldn't get file type for {:?}", entry.path());
2555 /// }
2556 /// }
2557 /// }
2558 /// }
2559 /// ```
2560 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2561 pub fn file_type(&self) -> io::Result<FileType> {
2562 self.0.file_type().map(FileType)
2563 }
2564
2565 /// Returns the file name of this directory entry without any
2566 /// leading path component(s).
2567 ///
2568 /// As an example,
2569 /// the output of the function will result in "foo" for all the following paths:
2570 /// - "./foo"
2571 /// - "/the/foo"
2572 /// - "../../foo"
2573 ///
2574 /// # Examples
2575 ///
2576 /// ```
2577 /// use std::fs;
2578 ///
2579 /// if let Ok(entries) = fs::read_dir(".") {
2580 /// for entry in entries {
2581 /// if let Ok(entry) = entry {
2582 /// // Here, `entry` is a `DirEntry`.
2583 /// println!("{:?}", entry.file_name());
2584 /// }
2585 /// }
2586 /// }
2587 /// ```
2588 #[must_use]
2589 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2590 pub fn file_name(&self) -> OsString {
2591 self.0.file_name()
2592 }
2593}
2594
2595#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2596impl fmt::Debug for DirEntry {
2597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2598 f.debug_tuple("DirEntry").field(&self.path()).finish()
2599 }
2600}
2601
2602impl AsInner<fs_imp::DirEntry> for DirEntry {
2603 #[inline]
2604 fn as_inner(&self) -> &fs_imp::DirEntry {
2605 &self.0
2606 }
2607}
2608
2609/// Removes a file from the filesystem.
2610///
2611/// Note that there is no
2612/// guarantee that the file is immediately deleted (e.g., depending on
2613/// platform, other open file descriptors may prevent immediate removal).
2614///
2615/// # Platform-specific behavior
2616///
2617/// This function currently corresponds to the `unlink` function on Unix.
2618/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2619/// Note that, this [may change in the future][changes].
2620///
2621/// [changes]: io#platform-specific-behavior
2622///
2623/// # Errors
2624///
2625/// This function will return an error in the following situations, but is not
2626/// limited to just these cases:
2627///
2628/// * `path` points to a directory.
2629/// * The file doesn't exist.
2630/// * The user lacks permissions to remove the file.
2631///
2632/// This function will only ever return an error of kind `NotFound` if the given
2633/// path does not exist. Note that the inverse is not true,
2634/// i.e. if a path does not exist, its removal may fail for a number of reasons,
2635/// such as insufficient permissions.
2636///
2637/// # Examples
2638///
2639/// ```no_run
2640/// use std::fs;
2641///
2642/// fn main() -> std::io::Result<()> {
2643/// fs::remove_file("a.txt")?;
2644/// Ok(())
2645/// }
2646/// ```
2647#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
2648#[stable(feature = "rust1", since = "1.0.0")]
2649pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
2650 fs_imp::remove_file(path.as_ref())
2651}
2652
2653/// Given a path, queries the file system to get information about a file,
2654/// directory, etc.
2655///
2656/// This function will traverse symbolic links to query information about the
2657/// destination file.
2658///
2659/// # Platform-specific behavior
2660///
2661/// This function currently corresponds to the `stat` function on Unix
2662/// and the `GetFileInformationByHandle` function on Windows.
2663/// Note that, this [may change in the future][changes].
2664///
2665/// [changes]: io#platform-specific-behavior
2666///
2667/// # Errors
2668///
2669/// This function will return an error in the following situations, but is not
2670/// limited to just these cases:
2671///
2672/// * The user lacks permissions to perform `metadata` call on `path`.
2673/// * `path` does not exist.
2674///
2675/// # Examples
2676///
2677/// ```rust,no_run
2678/// use std::fs;
2679///
2680/// fn main() -> std::io::Result<()> {
2681/// let attr = fs::metadata("/some/file/path.txt")?;
2682/// // inspect attr ...
2683/// Ok(())
2684/// }
2685/// ```
2686#[doc(alias = "stat")]
2687#[stable(feature = "rust1", since = "1.0.0")]
2688pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2689 fs_imp::metadata(path.as_ref()).map(Metadata)
2690}
2691
2692/// Queries the metadata about a file without following symlinks.
2693///
2694/// # Platform-specific behavior
2695///
2696/// This function currently corresponds to the `lstat` function on Unix
2697/// and the `GetFileInformationByHandle` function on Windows.
2698/// Note that, this [may change in the future][changes].
2699///
2700/// [changes]: io#platform-specific-behavior
2701///
2702/// # Errors
2703///
2704/// This function will return an error in the following situations, but is not
2705/// limited to just these cases:
2706///
2707/// * The user lacks permissions to perform `metadata` call on `path`.
2708/// * `path` does not exist.
2709///
2710/// # Examples
2711///
2712/// ```rust,no_run
2713/// use std::fs;
2714///
2715/// fn main() -> std::io::Result<()> {
2716/// let attr = fs::symlink_metadata("/some/file/path.txt")?;
2717/// // inspect attr ...
2718/// Ok(())
2719/// }
2720/// ```
2721#[doc(alias = "lstat")]
2722#[stable(feature = "symlink_metadata", since = "1.1.0")]
2723pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2724 fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
2725}
2726
2727/// Renames a file or directory to a new name, replacing the original file if
2728/// `to` already exists.
2729///
2730/// This will not work if the new name is on a different mount point.
2731///
2732/// # Platform-specific behavior
2733///
2734/// This function currently corresponds to the `rename` function on Unix
2735/// and the `MoveFileExW` or `SetFileInformationByHandle` function on Windows.
2736///
2737/// Because of this, the behavior when both `from` and `to` exist differs. On
2738/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
2739/// `from` is not a directory, `to` must also be not a directory. The behavior
2740/// on Windows is the same on Windows 10 1607 and higher if `FileRenameInfoEx`
2741/// is supported by the filesystem; otherwise, `from` can be anything, but
2742/// `to` must *not* be a directory.
2743///
2744/// Note that, this [may change in the future][changes].
2745///
2746/// [changes]: io#platform-specific-behavior
2747///
2748/// # Errors
2749///
2750/// This function will return an error in the following situations, but is not
2751/// limited to just these cases:
2752///
2753/// * `from` does not exist.
2754/// * The user lacks permissions to view contents.
2755/// * `from` and `to` are on separate filesystems.
2756///
2757/// # Examples
2758///
2759/// ```no_run
2760/// use std::fs;
2761///
2762/// fn main() -> std::io::Result<()> {
2763/// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
2764/// Ok(())
2765/// }
2766/// ```
2767#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
2768#[stable(feature = "rust1", since = "1.0.0")]
2769pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
2770 fs_imp::rename(from.as_ref(), to.as_ref())
2771}
2772
2773/// Copies the contents of one file to another. This function will also
2774/// copy the permission bits of the original file to the destination file.
2775///
2776/// This function will **overwrite** the contents of `to`.
2777///
2778/// Note that if `from` and `to` both point to the same file, then the file
2779/// will likely get truncated by this operation.
2780///
2781/// On success, the total number of bytes copied is returned and it is equal to
2782/// the length of the `to` file as reported by `metadata`.
2783///
2784/// If you want to copy the contents of one file to another and you’re
2785/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
2786///
2787/// # Platform-specific behavior
2788///
2789/// This function currently corresponds to the `open` function in Unix
2790/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
2791/// `O_CLOEXEC` is set for returned file descriptors.
2792///
2793/// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
2794/// and falls back to reading and writing if that is not possible.
2795///
2796/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
2797/// NTFS streams are copied but only the size of the main stream is returned by
2798/// this function.
2799///
2800/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
2801///
2802/// Note that platform-specific behavior [may change in the future][changes].
2803///
2804/// [changes]: io#platform-specific-behavior
2805///
2806/// # Errors
2807///
2808/// This function will return an error in the following situations, but is not
2809/// limited to just these cases:
2810///
2811/// * `from` is neither a regular file nor a symlink to a regular file.
2812/// * `from` does not exist.
2813/// * The current process does not have the permission rights to read
2814/// `from` or write `to`.
2815/// * The parent directory of `to` doesn't exist.
2816///
2817/// # Examples
2818///
2819/// ```no_run
2820/// use std::fs;
2821///
2822/// fn main() -> std::io::Result<()> {
2823/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
2824/// Ok(())
2825/// }
2826/// ```
2827#[doc(alias = "cp")]
2828#[doc(alias = "CopyFile", alias = "CopyFileEx")]
2829#[doc(alias = "fclonefileat", alias = "fcopyfile")]
2830#[stable(feature = "rust1", since = "1.0.0")]
2831pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
2832 fs_imp::copy(from.as_ref(), to.as_ref())
2833}
2834
2835/// Creates a new hard link on the filesystem.
2836///
2837/// The `link` path will be a link pointing to the `original` path. Note that
2838/// systems often require these two paths to both be located on the same
2839/// filesystem.
2840///
2841/// If `original` names a symbolic link, it is platform-specific whether the
2842/// symbolic link is followed. On platforms where it's possible to not follow
2843/// it, it is not followed, and the created hard link points to the symbolic
2844/// link itself.
2845///
2846/// # Platform-specific behavior
2847///
2848/// This function currently corresponds to the `CreateHardLink` function on Windows.
2849/// On most Unix systems, it corresponds to the `linkat` function with no flags.
2850/// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2851/// On MacOS, it uses the `linkat` function if it is available, but on very old
2852/// systems where `linkat` is not available, `link` is selected at runtime instead.
2853/// Note that, this [may change in the future][changes].
2854///
2855/// [changes]: io#platform-specific-behavior
2856///
2857/// # Errors
2858///
2859/// This function will return an error in the following situations, but is not
2860/// limited to just these cases:
2861///
2862/// * The `original` path is not a file or doesn't exist.
2863/// * The 'link' path already exists.
2864///
2865/// # Examples
2866///
2867/// ```no_run
2868/// use std::fs;
2869///
2870/// fn main() -> std::io::Result<()> {
2871/// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2872/// Ok(())
2873/// }
2874/// ```
2875#[doc(alias = "CreateHardLink", alias = "linkat")]
2876#[stable(feature = "rust1", since = "1.0.0")]
2877pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2878 fs_imp::hard_link(original.as_ref(), link.as_ref())
2879}
2880
2881/// Creates a new symbolic link on the filesystem.
2882///
2883/// The `link` path will be a symbolic link pointing to the `original` path.
2884/// On Windows, this will be a file symlink, not a directory symlink;
2885/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2886/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2887/// used instead to make the intent explicit.
2888///
2889/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2890/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2891/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2892///
2893/// # Examples
2894///
2895/// ```no_run
2896/// use std::fs;
2897///
2898/// fn main() -> std::io::Result<()> {
2899/// fs::soft_link("a.txt", "b.txt")?;
2900/// Ok(())
2901/// }
2902/// ```
2903#[stable(feature = "rust1", since = "1.0.0")]
2904#[deprecated(
2905 since = "1.1.0",
2906 note = "replaced with std::os::unix::fs::symlink and \
2907 std::os::windows::fs::{symlink_file, symlink_dir}"
2908)]
2909pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2910 fs_imp::symlink(original.as_ref(), link.as_ref())
2911}
2912
2913/// Reads a symbolic link, returning the file that the link points to.
2914///
2915/// # Platform-specific behavior
2916///
2917/// This function currently corresponds to the `readlink` function on Unix
2918/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2919/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2920/// Note that, this [may change in the future][changes].
2921///
2922/// [changes]: io#platform-specific-behavior
2923///
2924/// # Errors
2925///
2926/// This function will return an error in the following situations, but is not
2927/// limited to just these cases:
2928///
2929/// * `path` is not a symbolic link.
2930/// * `path` does not exist.
2931///
2932/// # Examples
2933///
2934/// ```no_run
2935/// use std::fs;
2936///
2937/// fn main() -> std::io::Result<()> {
2938/// let path = fs::read_link("a.txt")?;
2939/// Ok(())
2940/// }
2941/// ```
2942#[stable(feature = "rust1", since = "1.0.0")]
2943pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2944 fs_imp::read_link(path.as_ref())
2945}
2946
2947/// Returns the canonical, absolute form of a path with all intermediate
2948/// components normalized and symbolic links resolved.
2949///
2950/// # Platform-specific behavior
2951///
2952/// This function currently corresponds to the `realpath` function on Unix
2953/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2954/// Note that this [may change in the future][changes].
2955///
2956/// On Windows, this converts the path to use [extended length path][path]
2957/// syntax, which allows your program to use longer path names, but means you
2958/// can only join backslash-delimited paths to it, and it may be incompatible
2959/// with other applications (if passed to the application on the command-line,
2960/// or written to a file another application may read).
2961///
2962/// [changes]: io#platform-specific-behavior
2963/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2964///
2965/// # Errors
2966///
2967/// This function will return an error in the following situations, but is not
2968/// limited to just these cases:
2969///
2970/// * `path` does not exist.
2971/// * A non-final component in path is not a directory.
2972///
2973/// # Examples
2974///
2975/// ```no_run
2976/// use std::fs;
2977///
2978/// fn main() -> std::io::Result<()> {
2979/// let path = fs::canonicalize("../a/../foo.txt")?;
2980/// Ok(())
2981/// }
2982/// ```
2983#[doc(alias = "realpath")]
2984#[doc(alias = "GetFinalPathNameByHandle")]
2985#[stable(feature = "fs_canonicalize", since = "1.5.0")]
2986pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2987 fs_imp::canonicalize(path.as_ref())
2988}
2989
2990/// Creates a new, empty directory at the provided path.
2991///
2992/// # Platform-specific behavior
2993///
2994/// This function currently corresponds to the `mkdir` function on Unix
2995/// and the `CreateDirectoryW` function on Windows.
2996/// Note that, this [may change in the future][changes].
2997///
2998/// [changes]: io#platform-specific-behavior
2999///
3000/// **NOTE**: If a parent of the given path doesn't exist, this function will
3001/// return an error. To create a directory and all its missing parents at the
3002/// same time, use the [`create_dir_all`] function.
3003///
3004/// # Errors
3005///
3006/// This function will return an error in the following situations, but is not
3007/// limited to just these cases:
3008///
3009/// * User lacks permissions to create directory at `path`.
3010/// * A parent of the given path doesn't exist. (To create a directory and all
3011/// its missing parents at the same time, use the [`create_dir_all`]
3012/// function.)
3013/// * `path` already exists.
3014///
3015/// # Examples
3016///
3017/// ```no_run
3018/// use std::fs;
3019///
3020/// fn main() -> std::io::Result<()> {
3021/// fs::create_dir("/some/dir")?;
3022/// Ok(())
3023/// }
3024/// ```
3025#[doc(alias = "mkdir", alias = "CreateDirectory")]
3026#[stable(feature = "rust1", since = "1.0.0")]
3027#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
3028pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3029 DirBuilder::new().create(path.as_ref())
3030}
3031
3032/// Recursively create a directory and all of its parent components if they
3033/// are missing.
3034///
3035/// This function is not atomic. If it returns an error, any parent components it was able to create
3036/// will remain.
3037///
3038/// If the empty path is passed to this function, it always succeeds without
3039/// creating any directories.
3040///
3041/// # Platform-specific behavior
3042///
3043/// This function currently corresponds to multiple calls to the `mkdir`
3044/// function on Unix and the `CreateDirectoryW` function on Windows.
3045///
3046/// Note that, this [may change in the future][changes].
3047///
3048/// [changes]: io#platform-specific-behavior
3049///
3050/// # Errors
3051///
3052/// The function will return an error if any directory specified in path does not exist and
3053/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
3054///
3055/// Notable exception is made for situations where any of the directories
3056/// specified in the `path` could not be created as it was being created concurrently.
3057/// Such cases are considered to be successful. That is, calling `create_dir_all`
3058/// concurrently from multiple threads or processes is guaranteed not to fail
3059/// due to a race condition with itself.
3060///
3061/// [`fs::create_dir`]: create_dir
3062///
3063/// # Examples
3064///
3065/// ```no_run
3066/// use std::fs;
3067///
3068/// fn main() -> std::io::Result<()> {
3069/// fs::create_dir_all("/some/dir")?;
3070/// Ok(())
3071/// }
3072/// ```
3073#[stable(feature = "rust1", since = "1.0.0")]
3074pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3075 DirBuilder::new().recursive(true).create(path.as_ref())
3076}
3077
3078/// Removes an empty directory.
3079///
3080/// If you want to remove a directory that is not empty, as well as all
3081/// of its contents recursively, consider using [`remove_dir_all`]
3082/// instead.
3083///
3084/// # Platform-specific behavior
3085///
3086/// This function currently corresponds to the `rmdir` function on Unix
3087/// and the `RemoveDirectory` function on Windows.
3088/// Note that, this [may change in the future][changes].
3089///
3090/// [changes]: io#platform-specific-behavior
3091///
3092/// # Errors
3093///
3094/// This function will return an error in the following situations, but is not
3095/// limited to just these cases:
3096///
3097/// * `path` doesn't exist.
3098/// * `path` isn't a directory.
3099/// * The user lacks permissions to remove the directory at the provided `path`.
3100/// * The directory isn't empty.
3101///
3102/// This function will only ever return an error of kind `NotFound` if the given
3103/// path does not exist. Note that the inverse is not true,
3104/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3105/// such as insufficient permissions.
3106///
3107/// # Examples
3108///
3109/// ```no_run
3110/// use std::fs;
3111///
3112/// fn main() -> std::io::Result<()> {
3113/// fs::remove_dir("/some/dir")?;
3114/// Ok(())
3115/// }
3116/// ```
3117#[doc(alias = "rmdir", alias = "RemoveDirectory")]
3118#[stable(feature = "rust1", since = "1.0.0")]
3119pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3120 fs_imp::remove_dir(path.as_ref())
3121}
3122
3123/// Removes a directory at this path, after removing all its contents. Use
3124/// carefully!
3125///
3126/// This function does **not** follow symbolic links and it will simply remove the
3127/// symbolic link itself.
3128///
3129/// # Platform-specific behavior
3130///
3131/// These implementation details [may change in the future][changes].
3132///
3133/// - "Unix-like": By default, this function currently corresponds to
3134/// `openat`, `fdopendir`, `unlinkat` and `lstat`
3135/// on Unix-family platforms, except where noted otherwise.
3136/// - "Windows": This function currently corresponds to `CreateFileW`,
3137/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
3138///
3139/// ## Time-of-check to time-of-use (TOCTOU) race conditions
3140/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
3141///
3142/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
3143/// However, on the following platforms, this protection is not provided and the function should
3144/// not be used in security-sensitive contexts:
3145/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
3146/// TOCTOU races, Miri will not do so.
3147/// - **Redox OS**: This function does not protect against TOCTOU races, as Redox does not implement
3148/// the required platform support to do so.
3149///
3150/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3151/// [changes]: io#platform-specific-behavior
3152///
3153/// # Errors
3154///
3155/// See [`fs::remove_file`] and [`fs::remove_dir`].
3156///
3157/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3158/// paths, *including* the root `path`. Consequently,
3159///
3160/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3161/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3162///
3163/// Consider ignoring the error if validating the removal is not required for your use case.
3164///
3165/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3166/// written into, which typically indicates some contents were removed but not all.
3167/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3168///
3169/// [`fs::remove_file`]: remove_file
3170/// [`fs::remove_dir`]: remove_dir
3171///
3172/// # Examples
3173///
3174/// ```no_run
3175/// use std::fs;
3176///
3177/// fn main() -> std::io::Result<()> {
3178/// fs::remove_dir_all("/some/dir")?;
3179/// Ok(())
3180/// }
3181/// ```
3182#[stable(feature = "rust1", since = "1.0.0")]
3183pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3184 fs_imp::remove_dir_all(path.as_ref())
3185}
3186
3187/// Returns an iterator over the entries within a directory.
3188///
3189/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3190/// New errors may be encountered after an iterator is initially constructed.
3191/// Entries for the current and parent directories (typically `.` and `..`) are
3192/// skipped.
3193///
3194/// The order in which `read_dir` returns entries can change between calls. If reproducible
3195/// ordering is required, the entries should be explicitly sorted.
3196///
3197/// # Platform-specific behavior
3198///
3199/// This function currently corresponds to the `opendir` function on Unix
3200/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3201/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3202/// Note that, this [may change in the future][changes].
3203///
3204/// [changes]: io#platform-specific-behavior
3205///
3206/// The order in which this iterator returns entries is platform and filesystem
3207/// dependent.
3208///
3209/// # Errors
3210///
3211/// This function will return an error in the following situations, but is not
3212/// limited to just these cases:
3213///
3214/// * The provided `path` doesn't exist.
3215/// * The process lacks permissions to view the contents.
3216/// * The `path` points at a non-directory file.
3217///
3218/// # Examples
3219///
3220/// ```
3221/// use std::io;
3222/// use std::fs::{self, DirEntry};
3223/// use std::path::Path;
3224///
3225/// // one possible implementation of walking a directory only visiting files
3226/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3227/// if dir.is_dir() {
3228/// for entry in fs::read_dir(dir)? {
3229/// let entry = entry?;
3230/// let path = entry.path();
3231/// if path.is_dir() {
3232/// visit_dirs(&path, cb)?;
3233/// } else {
3234/// cb(&entry);
3235/// }
3236/// }
3237/// }
3238/// Ok(())
3239/// }
3240/// ```
3241///
3242/// ```rust,no_run
3243/// use std::{fs, io};
3244///
3245/// fn main() -> io::Result<()> {
3246/// let mut entries = fs::read_dir(".")?
3247/// .map(|res| res.map(|e| e.path()))
3248/// .collect::<Result<Vec<_>, io::Error>>()?;
3249///
3250/// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3251/// // ordering is required the entries should be explicitly sorted.
3252///
3253/// entries.sort();
3254///
3255/// // The entries have now been sorted by their path.
3256///
3257/// Ok(())
3258/// }
3259/// ```
3260#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3261#[stable(feature = "rust1", since = "1.0.0")]
3262pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3263 fs_imp::read_dir(path.as_ref()).map(ReadDir)
3264}
3265
3266/// Changes the permissions found on a file or a directory.
3267///
3268/// # Platform-specific behavior
3269///
3270/// This function currently corresponds to the `chmod` function on Unix
3271/// and the `SetFileAttributes` function on Windows.
3272/// Note that, this [may change in the future][changes].
3273///
3274/// [changes]: io#platform-specific-behavior
3275///
3276/// ## Symlinks
3277/// On UNIX-like systems, this function will update the permission bits
3278/// of the file pointed to by the symlink.
3279///
3280/// Note that this behavior can lead to privilege escalation vulnerabilities,
3281/// where the ability to create a symlink in one directory allows you to
3282/// cause the permissions of another file or directory to be modified.
3283///
3284/// For this reason, using this function with symlinks should be avoided.
3285/// When possible, permissions should be set at creation time instead.
3286///
3287/// # Rationale
3288/// POSIX does not specify an `lchmod` function,
3289/// and symlinks can be followed regardless of what permission bits are set.
3290///
3291/// # Errors
3292///
3293/// This function will return an error in the following situations, but is not
3294/// limited to just these cases:
3295///
3296/// * `path` does not exist.
3297/// * The user lacks the permission to change attributes of the file.
3298///
3299/// # Examples
3300///
3301/// ```no_run
3302/// use std::fs;
3303///
3304/// fn main() -> std::io::Result<()> {
3305/// let mut perms = fs::metadata("foo.txt")?.permissions();
3306/// perms.set_readonly(true);
3307/// fs::set_permissions("foo.txt", perms)?;
3308/// Ok(())
3309/// }
3310/// ```
3311#[doc(alias = "chmod", alias = "SetFileAttributes")]
3312#[stable(feature = "set_permissions", since = "1.1.0")]
3313pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3314 fs_imp::set_permissions(path.as_ref(), perm.0)
3315}
3316
3317/// Set the permissions of a file, unless it is a symlink.
3318///
3319/// Note that the non-final path elements are allowed to be symlinks.
3320///
3321/// # Platform-specific behavior
3322///
3323/// Currently unimplemented on Windows.
3324///
3325/// On Unix platforms, this results in a [`FilesystemLoop`] error if the last element is a symlink.
3326///
3327/// This behavior may change in the future.
3328///
3329/// [`FilesystemLoop`]: crate::io::ErrorKind::FilesystemLoop
3330#[doc(alias = "chmod", alias = "SetFileAttributes")]
3331#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
3332pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3333 fs_imp::set_permissions_nofollow(path.as_ref(), perm)
3334}
3335
3336impl DirBuilder {
3337 /// Creates a new set of options with default mode/security settings for all
3338 /// platforms and also non-recursive.
3339 ///
3340 /// # Examples
3341 ///
3342 /// ```
3343 /// use std::fs::DirBuilder;
3344 ///
3345 /// let builder = DirBuilder::new();
3346 /// ```
3347 #[stable(feature = "dir_builder", since = "1.6.0")]
3348 #[must_use]
3349 pub fn new() -> DirBuilder {
3350 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3351 }
3352
3353 /// Indicates that directories should be created recursively, creating all
3354 /// parent directories. Parents that do not exist are created with the same
3355 /// security and permissions settings.
3356 ///
3357 /// This option defaults to `false`.
3358 ///
3359 /// # Examples
3360 ///
3361 /// ```
3362 /// use std::fs::DirBuilder;
3363 ///
3364 /// let mut builder = DirBuilder::new();
3365 /// builder.recursive(true);
3366 /// ```
3367 #[stable(feature = "dir_builder", since = "1.6.0")]
3368 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3369 self.recursive = recursive;
3370 self
3371 }
3372
3373 /// Creates the specified directory with the options configured in this
3374 /// builder.
3375 ///
3376 /// It is considered an error if the directory already exists unless
3377 /// recursive mode is enabled.
3378 ///
3379 /// # Examples
3380 ///
3381 /// ```no_run
3382 /// use std::fs::{self, DirBuilder};
3383 ///
3384 /// let path = "/tmp/foo/bar/baz";
3385 /// DirBuilder::new()
3386 /// .recursive(true)
3387 /// .create(path).unwrap();
3388 ///
3389 /// assert!(fs::metadata(path).unwrap().is_dir());
3390 /// ```
3391 #[stable(feature = "dir_builder", since = "1.6.0")]
3392 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3393 self._create(path.as_ref())
3394 }
3395
3396 fn _create(&self, path: &Path) -> io::Result<()> {
3397 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3398 }
3399
3400 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3401 // if path's parent is None, it is "/" path, which should
3402 // return Ok immediately
3403 if path == Path::new("") || path.parent() == None {
3404 return Ok(());
3405 }
3406
3407 let ancestors = path.ancestors();
3408 let mut uncreated_dirs = 0;
3409
3410 for ancestor in ancestors {
3411 // for relative paths like "foo/bar", the parent of
3412 // "foo" will be "" which there's no need to invoke
3413 // a mkdir syscall on
3414 if ancestor == Path::new("") || ancestor.parent() == None {
3415 break;
3416 }
3417
3418 match self.inner.mkdir(ancestor) {
3419 Ok(()) => break,
3420 Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
3421 // we check if the err is AlreadyExists for two reasons
3422 // - in case the path exists as a *file*
3423 // - and to avoid calls to .is_dir() in case of other errs
3424 // (i.e. PermissionDenied)
3425 Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
3426 Err(e) => return Err(e),
3427 }
3428 }
3429
3430 // collect only the uncreated directories w/o letting the vec resize
3431 let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
3432 uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
3433
3434 for uncreated_dir in uncreated_dirs_vec.iter().rev() {
3435 if let Err(e) = self.inner.mkdir(uncreated_dir) {
3436 if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
3437 return Err(e);
3438 }
3439 }
3440 }
3441
3442 Ok(())
3443 }
3444}
3445
3446impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3447 #[inline]
3448 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3449 &mut self.inner
3450 }
3451}
3452
3453/// Returns `Ok(true)` if the path points at an existing entity.
3454///
3455/// This function will traverse symbolic links to query information about the
3456/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3457///
3458/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3459/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3460/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3461/// permission is denied on one of the parent directories.
3462///
3463/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3464/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3465/// where those bugs are not an issue.
3466///
3467/// # Examples
3468///
3469/// ```no_run
3470/// use std::fs;
3471///
3472/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3473/// assert!(fs::exists("/root/secret_file.txt").is_err());
3474/// ```
3475///
3476/// [`Path::exists`]: crate::path::Path::exists
3477/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3478#[stable(feature = "fs_try_exists", since = "1.81.0")]
3479#[inline]
3480pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
3481 fs_imp::exists(path.as_ref())
3482}