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 #[doc(alias = "filetime")]
1269 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1270 self.inner.set_times(times.0)
1271 }
1272
1273 /// Changes the modification time of the underlying file.
1274 ///
1275 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
1276 #[stable(feature = "file_set_times", since = "1.75.0")]
1277 #[inline]
1278 pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
1279 self.set_times(FileTimes::new().set_modified(time))
1280 }
1281}
1282
1283// In addition to the `impl`s here, `File` also has `impl`s for
1284// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1285// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1286// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
1287// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
1288
1289impl AsInner<fs_imp::File> for File {
1290 #[inline]
1291 fn as_inner(&self) -> &fs_imp::File {
1292 &self.inner
1293 }
1294}
1295impl FromInner<fs_imp::File> for File {
1296 fn from_inner(f: fs_imp::File) -> File {
1297 File { inner: f }
1298 }
1299}
1300impl IntoInner<fs_imp::File> for File {
1301 fn into_inner(self) -> fs_imp::File {
1302 self.inner
1303 }
1304}
1305
1306#[stable(feature = "rust1", since = "1.0.0")]
1307impl fmt::Debug for File {
1308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1309 self.inner.fmt(f)
1310 }
1311}
1312
1313/// Indicates how much extra capacity is needed to read the rest of the file.
1314fn buffer_capacity_required(mut file: &File) -> Option<usize> {
1315 let size = file.metadata().map(|m| m.len()).ok()?;
1316 let pos = file.stream_position().ok()?;
1317 // Don't worry about `usize` overflow because reading will fail regardless
1318 // in that case.
1319 Some(size.saturating_sub(pos) as usize)
1320}
1321
1322#[stable(feature = "rust1", since = "1.0.0")]
1323impl Read for &File {
1324 /// Reads some bytes from the file.
1325 ///
1326 /// See [`Read::read`] docs for more info.
1327 ///
1328 /// # Platform-specific behavior
1329 ///
1330 /// This function currently corresponds to the `read` function on Unix and
1331 /// the `NtReadFile` function on Windows. Note that this [may change in
1332 /// the future][changes].
1333 ///
1334 /// [changes]: io#platform-specific-behavior
1335 #[inline]
1336 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1337 self.inner.read(buf)
1338 }
1339
1340 /// Like `read`, except that it reads into a slice of buffers.
1341 ///
1342 /// See [`Read::read_vectored`] docs for more info.
1343 ///
1344 /// # Platform-specific behavior
1345 ///
1346 /// This function currently corresponds to the `readv` function on Unix and
1347 /// falls back to the `read` implementation on Windows. Note that this
1348 /// [may change in the future][changes].
1349 ///
1350 /// [changes]: io#platform-specific-behavior
1351 #[inline]
1352 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1353 self.inner.read_vectored(bufs)
1354 }
1355
1356 #[inline]
1357 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1358 self.inner.read_buf(cursor)
1359 }
1360
1361 /// Determines if `File` has an efficient `read_vectored` implementation.
1362 ///
1363 /// See [`Read::is_read_vectored`] docs for more info.
1364 ///
1365 /// # Platform-specific behavior
1366 ///
1367 /// This function currently returns `true` on Unix and `false` on Windows.
1368 /// Note that this [may change in the future][changes].
1369 ///
1370 /// [changes]: io#platform-specific-behavior
1371 #[inline]
1372 fn is_read_vectored(&self) -> bool {
1373 self.inner.is_read_vectored()
1374 }
1375
1376 // Reserves space in the buffer based on the file size when available.
1377 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1378 let size = buffer_capacity_required(self);
1379 buf.try_reserve(size.unwrap_or(0))?;
1380 io::default_read_to_end(self, buf, size)
1381 }
1382
1383 // Reserves space in the buffer based on the file size when available.
1384 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1385 let size = buffer_capacity_required(self);
1386 buf.try_reserve(size.unwrap_or(0))?;
1387 io::default_read_to_string(self, buf, size)
1388 }
1389}
1390#[stable(feature = "rust1", since = "1.0.0")]
1391impl Write for &File {
1392 /// Writes some bytes to the file.
1393 ///
1394 /// See [`Write::write`] docs for more info.
1395 ///
1396 /// # Platform-specific behavior
1397 ///
1398 /// This function currently corresponds to the `write` function on Unix and
1399 /// the `NtWriteFile` function on Windows. Note that this [may change in
1400 /// the future][changes].
1401 ///
1402 /// [changes]: io#platform-specific-behavior
1403 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1404 self.inner.write(buf)
1405 }
1406
1407 /// Like `write`, except that it writes into a slice of buffers.
1408 ///
1409 /// See [`Write::write_vectored`] docs for more info.
1410 ///
1411 /// # Platform-specific behavior
1412 ///
1413 /// This function currently corresponds to the `writev` function on Unix
1414 /// and falls back to the `write` implementation on Windows. Note that this
1415 /// [may change in the future][changes].
1416 ///
1417 /// [changes]: io#platform-specific-behavior
1418 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1419 self.inner.write_vectored(bufs)
1420 }
1421
1422 /// Determines if `File` has an efficient `write_vectored` implementation.
1423 ///
1424 /// See [`Write::is_write_vectored`] docs for more info.
1425 ///
1426 /// # Platform-specific behavior
1427 ///
1428 /// This function currently returns `true` on Unix and `false` on Windows.
1429 /// Note that this [may change in the future][changes].
1430 ///
1431 /// [changes]: io#platform-specific-behavior
1432 #[inline]
1433 fn is_write_vectored(&self) -> bool {
1434 self.inner.is_write_vectored()
1435 }
1436
1437 /// Flushes the file, ensuring that all intermediately buffered contents
1438 /// reach their destination.
1439 ///
1440 /// See [`Write::flush`] docs for more info.
1441 ///
1442 /// # Platform-specific behavior
1443 ///
1444 /// Since a `File` structure doesn't contain any buffers, this function is
1445 /// currently a no-op on Unix and Windows. Note that this [may change in
1446 /// the future][changes].
1447 ///
1448 /// [changes]: io#platform-specific-behavior
1449 #[inline]
1450 fn flush(&mut self) -> io::Result<()> {
1451 self.inner.flush()
1452 }
1453}
1454#[stable(feature = "rust1", since = "1.0.0")]
1455impl Seek for &File {
1456 /// Seek to an offset, in bytes in a file.
1457 ///
1458 /// See [`Seek::seek`] docs for more info.
1459 ///
1460 /// # Platform-specific behavior
1461 ///
1462 /// This function currently corresponds to the `lseek64` function on Unix
1463 /// and the `SetFilePointerEx` function on Windows. Note that this [may
1464 /// change in the future][changes].
1465 ///
1466 /// [changes]: io#platform-specific-behavior
1467 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1468 self.inner.seek(pos)
1469 }
1470
1471 /// Returns the length of this file (in bytes).
1472 ///
1473 /// See [`Seek::stream_len`] docs for more info.
1474 ///
1475 /// # Platform-specific behavior
1476 ///
1477 /// This function currently corresponds to the `statx` function on Linux
1478 /// (with fallbacks) and the `GetFileSizeEx` function on Windows. Note that
1479 /// this [may change in the future][changes].
1480 ///
1481 /// [changes]: io#platform-specific-behavior
1482 fn stream_len(&mut self) -> io::Result<u64> {
1483 if let Some(result) = self.inner.size() {
1484 return result;
1485 }
1486 io::stream_len_default(self)
1487 }
1488
1489 fn stream_position(&mut self) -> io::Result<u64> {
1490 self.inner.tell()
1491 }
1492}
1493
1494#[stable(feature = "rust1", since = "1.0.0")]
1495impl Read for File {
1496 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1497 (&*self).read(buf)
1498 }
1499 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1500 (&*self).read_vectored(bufs)
1501 }
1502 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1503 (&*self).read_buf(cursor)
1504 }
1505 #[inline]
1506 fn is_read_vectored(&self) -> bool {
1507 (&&*self).is_read_vectored()
1508 }
1509 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1510 (&*self).read_to_end(buf)
1511 }
1512 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
1513 (&*self).read_to_string(buf)
1514 }
1515}
1516#[stable(feature = "rust1", since = "1.0.0")]
1517impl Write for File {
1518 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1519 (&*self).write(buf)
1520 }
1521 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1522 (&*self).write_vectored(bufs)
1523 }
1524 #[inline]
1525 fn is_write_vectored(&self) -> bool {
1526 (&&*self).is_write_vectored()
1527 }
1528 #[inline]
1529 fn flush(&mut self) -> io::Result<()> {
1530 (&*self).flush()
1531 }
1532}
1533#[stable(feature = "rust1", since = "1.0.0")]
1534impl Seek for File {
1535 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1536 (&*self).seek(pos)
1537 }
1538 fn stream_len(&mut self) -> io::Result<u64> {
1539 (&*self).stream_len()
1540 }
1541 fn stream_position(&mut self) -> io::Result<u64> {
1542 (&*self).stream_position()
1543 }
1544}
1545impl crate::io::IoHandle for File {}
1546
1547impl Dir {
1548 /// Attempts to open a directory at `path` in read-only mode.
1549 ///
1550 /// # Errors
1551 ///
1552 /// This function will return an error if `path` does not point to an existing directory.
1553 /// Other errors may also be returned according to [`OpenOptions::open`].
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```no_run
1558 /// #![feature(dirfd)]
1559 /// use std::{fs::Dir, io};
1560 ///
1561 /// fn main() -> std::io::Result<()> {
1562 /// let dir = Dir::open("foo")?;
1563 /// let mut f = dir.open_file("bar.txt")?;
1564 /// let contents = io::read_to_string(f)?;
1565 /// assert_eq!(contents, "Hello, world!");
1566 /// Ok(())
1567 /// }
1568 /// ```
1569 #[unstable(feature = "dirfd", issue = "120426")]
1570 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1571 fs_imp::Dir::open(path.as_ref(), &OpenOptions::new().read(true).0)
1572 .map(|inner| Self { inner })
1573 }
1574
1575 /// Attempts to open a file in read-only mode relative to this directory.
1576 ///
1577 /// # Errors
1578 ///
1579 /// This function will return an error if `path` does not point to an existing file.
1580 /// Other errors may also be returned according to [`OpenOptions::open`].
1581 ///
1582 /// # Examples
1583 ///
1584 /// ```no_run
1585 /// #![feature(dirfd)]
1586 /// use std::{fs::Dir, io};
1587 ///
1588 /// fn main() -> std::io::Result<()> {
1589 /// let dir = Dir::open("foo")?;
1590 /// let mut f = dir.open_file("bar.txt")?;
1591 /// let contents = io::read_to_string(f)?;
1592 /// assert_eq!(contents, "Hello, world!");
1593 /// Ok(())
1594 /// }
1595 /// ```
1596 #[unstable(feature = "dirfd", issue = "120426")]
1597 pub fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1598 self.inner
1599 .open_file(path.as_ref(), &OpenOptions::new().read(true).0)
1600 .map(|f| File { inner: f })
1601 }
1602}
1603
1604impl AsInner<fs_imp::Dir> for Dir {
1605 #[inline]
1606 fn as_inner(&self) -> &fs_imp::Dir {
1607 &self.inner
1608 }
1609}
1610impl FromInner<fs_imp::Dir> for Dir {
1611 fn from_inner(f: fs_imp::Dir) -> Dir {
1612 Dir { inner: f }
1613 }
1614}
1615impl IntoInner<fs_imp::Dir> for Dir {
1616 fn into_inner(self) -> fs_imp::Dir {
1617 self.inner
1618 }
1619}
1620
1621#[unstable(feature = "dirfd", issue = "120426")]
1622impl fmt::Debug for Dir {
1623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1624 self.inner.fmt(f)
1625 }
1626}
1627
1628impl OpenOptions {
1629 /// Creates a blank new set of options ready for configuration.
1630 ///
1631 /// All options are initially set to `false`.
1632 ///
1633 /// # Examples
1634 ///
1635 /// ```no_run
1636 /// use std::fs::OpenOptions;
1637 ///
1638 /// let mut options = OpenOptions::new();
1639 /// let file = options.read(true).open("foo.txt");
1640 /// ```
1641 #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 #[must_use]
1644 pub fn new() -> Self {
1645 OpenOptions(fs_imp::OpenOptions::new())
1646 }
1647
1648 /// Sets the option for read access.
1649 ///
1650 /// This option, when true, will indicate that the file should be
1651 /// `read`-able if opened.
1652 ///
1653 /// # Examples
1654 ///
1655 /// ```no_run
1656 /// use std::fs::OpenOptions;
1657 ///
1658 /// let file = OpenOptions::new().read(true).open("foo.txt");
1659 /// ```
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 pub fn read(&mut self, read: bool) -> &mut Self {
1662 self.0.read(read);
1663 self
1664 }
1665
1666 /// Sets the option for write access.
1667 ///
1668 /// This option, when true, will indicate that the file should be
1669 /// `write`-able if opened.
1670 ///
1671 /// If the file already exists, any write calls on it will overwrite its
1672 /// contents, without truncating it.
1673 ///
1674 /// # Examples
1675 ///
1676 /// ```no_run
1677 /// use std::fs::OpenOptions;
1678 ///
1679 /// let file = OpenOptions::new().write(true).open("foo.txt");
1680 /// ```
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 pub fn write(&mut self, write: bool) -> &mut Self {
1683 self.0.write(write);
1684 self
1685 }
1686
1687 /// Sets the option for the append mode.
1688 ///
1689 /// This option, when true, means that writes will append to a file instead
1690 /// of overwriting previous contents.
1691 /// Note that setting `.write(true).append(true)` has the same effect as
1692 /// setting only `.append(true)`.
1693 ///
1694 /// Append mode guarantees that writes will be positioned at the current end of file,
1695 /// even when there are other processes or threads appending to the same file. This is
1696 /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
1697 /// has a race between seeking and writing during which another writer can write, with
1698 /// our `write()` overwriting their data.
1699 ///
1700 /// Keep in mind that this does not necessarily guarantee that data appended by
1701 /// different processes or threads does not interleave. The amount of data accepted a
1702 /// single `write()` call depends on the operating system and file system. A
1703 /// successful `write()` is allowed to write only part of the given data, so even if
1704 /// you're careful to provide the whole message in a single call to `write()`, there
1705 /// is no guarantee that it will be written out in full. If you rely on the filesystem
1706 /// accepting the message in a single write, make sure that all data that belongs
1707 /// together is written in one operation. This can be done by concatenating strings
1708 /// before passing them to [`write()`].
1709 ///
1710 /// If a file is opened with both read and append access, beware that after
1711 /// opening, and after every write, the position for reading may be set at the
1712 /// end of the file. So, before writing, save the current position (using
1713 /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
1714 ///
1715 /// ## Note
1716 ///
1717 /// This function doesn't create the file if it doesn't exist. Use the
1718 /// [`OpenOptions::create`] method to do so.
1719 ///
1720 /// [`write()`]: Write::write "io::Write::write"
1721 /// [`flush()`]: Write::flush "io::Write::flush"
1722 /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
1723 /// [seek]: Seek::seek "io::Seek::seek"
1724 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
1725 /// [End]: SeekFrom::End "io::SeekFrom::End"
1726 ///
1727 /// # Examples
1728 ///
1729 /// ```no_run
1730 /// use std::fs::OpenOptions;
1731 ///
1732 /// let file = OpenOptions::new().append(true).open("foo.txt");
1733 /// ```
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 pub fn append(&mut self, append: bool) -> &mut Self {
1736 self.0.append(append);
1737 self
1738 }
1739
1740 /// Sets the option for truncating a previous file.
1741 ///
1742 /// If a file is successfully opened with this option set to true, it will truncate
1743 /// the file to 0 length if it already exists.
1744 ///
1745 /// The file must be opened with write access for truncate to work.
1746 ///
1747 /// # Examples
1748 ///
1749 /// ```no_run
1750 /// use std::fs::OpenOptions;
1751 ///
1752 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
1753 /// ```
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
1756 self.0.truncate(truncate);
1757 self
1758 }
1759
1760 /// Sets the option to create a new file, or open it if it already exists.
1761 ///
1762 /// In order for the file to be created, [`OpenOptions::write`] or
1763 /// [`OpenOptions::append`] access must be used.
1764 ///
1765 /// See also [`std::fs::write()`][self::write] for a simple function to
1766 /// create a file with some given data.
1767 ///
1768 /// # Errors
1769 ///
1770 /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
1771 /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
1772 /// # Examples
1773 ///
1774 /// ```no_run
1775 /// use std::fs::OpenOptions;
1776 ///
1777 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
1778 /// ```
1779 #[stable(feature = "rust1", since = "1.0.0")]
1780 pub fn create(&mut self, create: bool) -> &mut Self {
1781 self.0.create(create);
1782 self
1783 }
1784
1785 /// Sets the option to create a new file, failing if it already exists.
1786 ///
1787 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1788 /// way, if the call succeeds, the file returned is guaranteed to be new.
1789 /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
1790 /// or another error based on the situation. See [`OpenOptions::open`] for a
1791 /// non-exhaustive list of likely errors.
1792 ///
1793 /// This option is useful because it is atomic. Otherwise between checking
1794 /// whether a file exists and creating a new one, the file may have been
1795 /// created by another process (a [TOCTOU] race condition / attack).
1796 ///
1797 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1798 /// ignored.
1799 ///
1800 /// The file must be opened with write or append access in order to create
1801 /// a new file.
1802 ///
1803 /// [`.create()`]: OpenOptions::create
1804 /// [`.truncate()`]: OpenOptions::truncate
1805 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1806 /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
1807 ///
1808 /// # Examples
1809 ///
1810 /// ```no_run
1811 /// use std::fs::OpenOptions;
1812 ///
1813 /// let file = OpenOptions::new().write(true)
1814 /// .create_new(true)
1815 /// .open("foo.txt");
1816 /// ```
1817 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1818 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1819 self.0.create_new(create_new);
1820 self
1821 }
1822
1823 /// Opens a file at `path` with the options specified by `self`.
1824 ///
1825 /// # Errors
1826 ///
1827 /// This function will return an error under a number of different
1828 /// circumstances. Some of these error conditions are listed here, together
1829 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1830 /// part of the compatibility contract of the function.
1831 ///
1832 /// * [`NotFound`]: The specified file does not exist and neither `create`
1833 /// or `create_new` is set.
1834 /// * [`NotFound`]: One of the directory components of the file path does
1835 /// not exist.
1836 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1837 /// access rights for the file.
1838 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1839 /// directory components of the specified path.
1840 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1841 /// exists.
1842 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1843 /// without write access, create without write or append access,
1844 /// no access mode set, etc.).
1845 ///
1846 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1847 /// * One of the directory components of the specified file path
1848 /// was not, in fact, a directory.
1849 /// * Filesystem-level errors: full disk, write permission
1850 /// requested on a read-only file system, exceeded disk quota, too many
1851 /// open files, too long filename, too many symbolic links in the
1852 /// specified path (Unix-like systems only), etc.
1853 ///
1854 /// # Examples
1855 ///
1856 /// ```no_run
1857 /// use std::fs::OpenOptions;
1858 ///
1859 /// let file = OpenOptions::new().read(true).open("foo.txt");
1860 /// ```
1861 ///
1862 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1863 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1864 /// [`NotFound`]: io::ErrorKind::NotFound
1865 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1868 self._open(path.as_ref())
1869 }
1870
1871 fn _open(&self, path: &Path) -> io::Result<File> {
1872 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1873 }
1874}
1875
1876impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1877 #[inline]
1878 fn as_inner(&self) -> &fs_imp::OpenOptions {
1879 &self.0
1880 }
1881}
1882
1883impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1884 #[inline]
1885 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1886 &mut self.0
1887 }
1888}
1889
1890impl Metadata {
1891 /// Returns the file type for this metadata.
1892 ///
1893 /// # Examples
1894 ///
1895 /// ```no_run
1896 /// fn main() -> std::io::Result<()> {
1897 /// use std::fs;
1898 ///
1899 /// let metadata = fs::metadata("foo.txt")?;
1900 ///
1901 /// println!("{:?}", metadata.file_type());
1902 /// Ok(())
1903 /// }
1904 /// ```
1905 #[must_use]
1906 #[stable(feature = "file_type", since = "1.1.0")]
1907 pub fn file_type(&self) -> FileType {
1908 FileType(self.0.file_type())
1909 }
1910
1911 /// Returns `true` if this metadata is for a directory. The
1912 /// result is mutually exclusive to the result of
1913 /// [`Metadata::is_file`], and will be false for symlink metadata
1914 /// obtained from [`symlink_metadata`].
1915 ///
1916 /// # Examples
1917 ///
1918 /// ```no_run
1919 /// fn main() -> std::io::Result<()> {
1920 /// use std::fs;
1921 ///
1922 /// let metadata = fs::metadata("foo.txt")?;
1923 ///
1924 /// assert!(!metadata.is_dir());
1925 /// Ok(())
1926 /// }
1927 /// ```
1928 #[must_use]
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 pub fn is_dir(&self) -> bool {
1931 self.file_type().is_dir()
1932 }
1933
1934 /// Returns `true` if this metadata is for a regular file. The
1935 /// result is mutually exclusive to the result of
1936 /// [`Metadata::is_dir`], and will be false for symlink metadata
1937 /// obtained from [`symlink_metadata`].
1938 ///
1939 /// When the goal is simply to read from (or write to) the source, the most
1940 /// reliable way to test the source can be read (or written to) is to open
1941 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1942 /// a Unix-like system for example. See [`File::open`] or
1943 /// [`OpenOptions::open`] for more information.
1944 ///
1945 /// # Examples
1946 ///
1947 /// ```no_run
1948 /// use std::fs;
1949 ///
1950 /// fn main() -> std::io::Result<()> {
1951 /// let metadata = fs::metadata("foo.txt")?;
1952 ///
1953 /// assert!(metadata.is_file());
1954 /// Ok(())
1955 /// }
1956 /// ```
1957 #[must_use]
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 pub fn is_file(&self) -> bool {
1960 self.file_type().is_file()
1961 }
1962
1963 /// Returns `true` if this metadata is for a symbolic link.
1964 ///
1965 /// # Examples
1966 ///
1967 #[cfg_attr(unix, doc = "```no_run")]
1968 #[cfg_attr(not(unix), doc = "```ignore")]
1969 /// use std::fs;
1970 /// use std::path::Path;
1971 /// use std::os::unix::fs::symlink;
1972 ///
1973 /// fn main() -> std::io::Result<()> {
1974 /// let link_path = Path::new("link");
1975 /// symlink("/origin_does_not_exist/", link_path)?;
1976 ///
1977 /// let metadata = fs::symlink_metadata(link_path)?;
1978 ///
1979 /// assert!(metadata.is_symlink());
1980 /// Ok(())
1981 /// }
1982 /// ```
1983 #[must_use]
1984 #[stable(feature = "is_symlink", since = "1.58.0")]
1985 pub fn is_symlink(&self) -> bool {
1986 self.file_type().is_symlink()
1987 }
1988
1989 /// Returns the size of the file, in bytes, this metadata is for.
1990 ///
1991 /// # Examples
1992 ///
1993 /// ```no_run
1994 /// use std::fs;
1995 ///
1996 /// fn main() -> std::io::Result<()> {
1997 /// let metadata = fs::metadata("foo.txt")?;
1998 ///
1999 /// assert_eq!(0, metadata.len());
2000 /// Ok(())
2001 /// }
2002 /// ```
2003 #[must_use]
2004 #[stable(feature = "rust1", since = "1.0.0")]
2005 pub fn len(&self) -> u64 {
2006 self.0.size()
2007 }
2008
2009 /// Returns the permissions of the file this metadata is for.
2010 ///
2011 /// # Examples
2012 ///
2013 /// ```no_run
2014 /// use std::fs;
2015 ///
2016 /// fn main() -> std::io::Result<()> {
2017 /// let metadata = fs::metadata("foo.txt")?;
2018 ///
2019 /// assert!(!metadata.permissions().readonly());
2020 /// Ok(())
2021 /// }
2022 /// ```
2023 #[must_use]
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 pub fn permissions(&self) -> Permissions {
2026 Permissions(self.0.perm())
2027 }
2028
2029 /// Returns the last modification time listed in this metadata.
2030 ///
2031 /// The returned value corresponds to the `mtime` field of `stat` on Unix
2032 /// platforms and the `ftLastWriteTime` field on Windows platforms.
2033 ///
2034 /// # Errors
2035 ///
2036 /// This field might not be available on all platforms, and will return an
2037 /// `Err` on platforms where it is not available.
2038 ///
2039 /// # Examples
2040 ///
2041 /// ```no_run
2042 /// use std::fs;
2043 ///
2044 /// fn main() -> std::io::Result<()> {
2045 /// let metadata = fs::metadata("foo.txt")?;
2046 ///
2047 /// if let Ok(time) = metadata.modified() {
2048 /// println!("{time:?}");
2049 /// } else {
2050 /// println!("Not supported on this platform");
2051 /// }
2052 /// Ok(())
2053 /// }
2054 /// ```
2055 #[doc(alias = "mtime", alias = "ftLastWriteTime")]
2056 #[stable(feature = "fs_time", since = "1.10.0")]
2057 pub fn modified(&self) -> io::Result<SystemTime> {
2058 self.0.modified().map(FromInner::from_inner)
2059 }
2060
2061 /// Returns the last access time of this metadata.
2062 ///
2063 /// The returned value corresponds to the `atime` field of `stat` on Unix
2064 /// platforms and the `ftLastAccessTime` field on Windows platforms.
2065 ///
2066 /// Note that not all platforms will keep this field update in a file's
2067 /// metadata, for example Windows has an option to disable updating this
2068 /// time when files are accessed and Linux similarly has `noatime`.
2069 ///
2070 /// # Errors
2071 ///
2072 /// This field might not be available on all platforms, and will return an
2073 /// `Err` on platforms where it is not available.
2074 ///
2075 /// # Examples
2076 ///
2077 /// ```no_run
2078 /// use std::fs;
2079 ///
2080 /// fn main() -> std::io::Result<()> {
2081 /// let metadata = fs::metadata("foo.txt")?;
2082 ///
2083 /// if let Ok(time) = metadata.accessed() {
2084 /// println!("{time:?}");
2085 /// } else {
2086 /// println!("Not supported on this platform");
2087 /// }
2088 /// Ok(())
2089 /// }
2090 /// ```
2091 #[doc(alias = "atime", alias = "ftLastAccessTime")]
2092 #[stable(feature = "fs_time", since = "1.10.0")]
2093 pub fn accessed(&self) -> io::Result<SystemTime> {
2094 self.0.accessed().map(FromInner::from_inner)
2095 }
2096
2097 /// Returns the creation time listed in this metadata.
2098 ///
2099 /// The returned value corresponds to the `btime` field of `statx` on
2100 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
2101 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
2102 ///
2103 /// # Errors
2104 ///
2105 /// This field might not be available on all platforms, and will return an
2106 /// `Err` on platforms or filesystems where it is not available.
2107 ///
2108 /// # Examples
2109 ///
2110 /// ```no_run
2111 /// use std::fs;
2112 ///
2113 /// fn main() -> std::io::Result<()> {
2114 /// let metadata = fs::metadata("foo.txt")?;
2115 ///
2116 /// if let Ok(time) = metadata.created() {
2117 /// println!("{time:?}");
2118 /// } else {
2119 /// println!("Not supported on this platform or filesystem");
2120 /// }
2121 /// Ok(())
2122 /// }
2123 /// ```
2124 #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
2125 #[stable(feature = "fs_time", since = "1.10.0")]
2126 pub fn created(&self) -> io::Result<SystemTime> {
2127 self.0.created().map(FromInner::from_inner)
2128 }
2129}
2130
2131#[stable(feature = "std_debug", since = "1.16.0")]
2132impl fmt::Debug for Metadata {
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 let mut debug = f.debug_struct("Metadata");
2135 debug.field("file_type", &self.file_type());
2136 debug.field("permissions", &self.permissions());
2137 debug.field("len", &self.len());
2138 if let Ok(modified) = self.modified() {
2139 debug.field("modified", &modified);
2140 }
2141 if let Ok(accessed) = self.accessed() {
2142 debug.field("accessed", &accessed);
2143 }
2144 if let Ok(created) = self.created() {
2145 debug.field("created", &created);
2146 }
2147 debug.finish_non_exhaustive()
2148 }
2149}
2150
2151impl AsInner<fs_imp::FileAttr> for Metadata {
2152 #[inline]
2153 fn as_inner(&self) -> &fs_imp::FileAttr {
2154 &self.0
2155 }
2156}
2157
2158impl FromInner<fs_imp::FileAttr> for Metadata {
2159 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2160 Metadata(attr)
2161 }
2162}
2163
2164impl FileTimes {
2165 /// Creates a new `FileTimes` with no times set.
2166 ///
2167 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2168 #[stable(feature = "file_set_times", since = "1.75.0")]
2169 pub fn new() -> Self {
2170 Self::default()
2171 }
2172
2173 /// Set the last access time of a file.
2174 #[stable(feature = "file_set_times", since = "1.75.0")]
2175 pub fn set_accessed(mut self, t: SystemTime) -> Self {
2176 self.0.set_accessed(t.into_inner());
2177 self
2178 }
2179
2180 /// Set the last modified time of a file.
2181 #[stable(feature = "file_set_times", since = "1.75.0")]
2182 pub fn set_modified(mut self, t: SystemTime) -> Self {
2183 self.0.set_modified(t.into_inner());
2184 self
2185 }
2186}
2187
2188impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2189 fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2190 &mut self.0
2191 }
2192}
2193
2194// For implementing OS extension traits in `std::os`
2195#[stable(feature = "file_set_times", since = "1.75.0")]
2196impl Sealed for FileTimes {}
2197
2198impl Permissions {
2199 /// Returns `true` if these permissions describe a readonly (unwritable) file.
2200 ///
2201 /// # Note
2202 ///
2203 /// This function does not take Access Control Lists (ACLs), Unix group
2204 /// membership and other nuances into account.
2205 /// Therefore the return value of this function cannot be relied upon
2206 /// to predict whether attempts to read or write the file will actually succeed.
2207 ///
2208 /// # Windows
2209 ///
2210 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2211 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2212 /// but the user may still have permission to change this flag. If
2213 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2214 /// to lack of write permission.
2215 /// The behavior of this attribute for directories depends on the Windows
2216 /// version.
2217 ///
2218 /// # Unix (including macOS)
2219 ///
2220 /// On Unix-based platforms this checks if *any* of the owner, group or others
2221 /// write permission bits are set. It does not consider anything else, including:
2222 ///
2223 /// * Whether the current user is in the file's assigned group.
2224 /// * Permissions granted by ACL.
2225 /// * That `root` user can write to files that do not have any write bits set.
2226 /// * Writable files on a filesystem that is mounted read-only.
2227 ///
2228 /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2229 /// also does not read ACLs.
2230 ///
2231 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2232 ///
2233 /// # Examples
2234 ///
2235 /// ```no_run
2236 /// use std::fs::File;
2237 ///
2238 /// fn main() -> std::io::Result<()> {
2239 /// let mut f = File::create("foo.txt")?;
2240 /// let metadata = f.metadata()?;
2241 ///
2242 /// assert_eq!(false, metadata.permissions().readonly());
2243 /// Ok(())
2244 /// }
2245 /// ```
2246 #[must_use = "call `set_readonly` to modify the readonly flag"]
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 pub fn readonly(&self) -> bool {
2249 self.0.readonly()
2250 }
2251
2252 /// Modifies the readonly flag for this set of permissions. If the
2253 /// `readonly` argument is `true`, using the resulting `Permission` will
2254 /// update file permissions to forbid writing. Conversely, if it's `false`,
2255 /// using the resulting `Permission` will update file permissions to allow
2256 /// writing.
2257 ///
2258 /// This operation does **not** modify the files attributes. This only
2259 /// changes the in-memory value of these attributes for this `Permissions`
2260 /// instance. To modify the files attributes use the [`set_permissions`]
2261 /// function which commits these attribute changes to the file.
2262 ///
2263 /// # Note
2264 ///
2265 /// `set_readonly(false)` makes the file *world-writable* on Unix.
2266 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2267 ///
2268 /// It also does not take Access Control Lists (ACLs) or Unix group
2269 /// membership into account.
2270 ///
2271 /// # Windows
2272 ///
2273 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2274 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2275 /// but the user may still have permission to change this flag. If
2276 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2277 /// the user does not have permission to write to the file.
2278 ///
2279 /// In Windows 7 and earlier this attribute prevents deleting empty
2280 /// directories. It does not prevent modifying the directory contents.
2281 /// On later versions of Windows this attribute is ignored for directories.
2282 ///
2283 /// # Unix (including macOS)
2284 ///
2285 /// On Unix-based platforms this sets or clears the write access bit for
2286 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2287 /// or `chmod a-w <file>` respectively. The latter will grant write access
2288 /// to all users! You can use the [`PermissionsExt`] trait on Unix
2289 /// to avoid this issue.
2290 ///
2291 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2292 ///
2293 /// # Examples
2294 ///
2295 /// ```no_run
2296 /// use std::fs::File;
2297 ///
2298 /// fn main() -> std::io::Result<()> {
2299 /// let f = File::create("foo.txt")?;
2300 /// let metadata = f.metadata()?;
2301 /// let mut permissions = metadata.permissions();
2302 ///
2303 /// permissions.set_readonly(true);
2304 ///
2305 /// // filesystem doesn't change, only the in memory state of the
2306 /// // readonly permission
2307 /// assert_eq!(false, metadata.permissions().readonly());
2308 ///
2309 /// // just this particular `permissions`.
2310 /// assert_eq!(true, permissions.readonly());
2311 /// Ok(())
2312 /// }
2313 /// ```
2314 #[stable(feature = "rust1", since = "1.0.0")]
2315 pub fn set_readonly(&mut self, readonly: bool) {
2316 self.0.set_readonly(readonly)
2317 }
2318}
2319
2320impl FileType {
2321 /// Tests whether this file type represents a directory. The
2322 /// result is mutually exclusive to the results of
2323 /// [`is_file`] and [`is_symlink`]; only zero or one of these
2324 /// tests may pass.
2325 ///
2326 /// [`is_file`]: FileType::is_file
2327 /// [`is_symlink`]: FileType::is_symlink
2328 ///
2329 /// # Examples
2330 ///
2331 /// ```no_run
2332 /// fn main() -> std::io::Result<()> {
2333 /// use std::fs;
2334 ///
2335 /// let metadata = fs::metadata("foo.txt")?;
2336 /// let file_type = metadata.file_type();
2337 ///
2338 /// assert_eq!(file_type.is_dir(), false);
2339 /// Ok(())
2340 /// }
2341 /// ```
2342 #[must_use]
2343 #[stable(feature = "file_type", since = "1.1.0")]
2344 pub fn is_dir(&self) -> bool {
2345 self.0.is_dir()
2346 }
2347
2348 /// Tests whether this file type represents a regular file.
2349 /// The result is mutually exclusive to the results of
2350 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2351 /// tests may pass.
2352 ///
2353 /// When the goal is simply to read from (or write to) the source, the most
2354 /// reliable way to test the source can be read (or written to) is to open
2355 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2356 /// a Unix-like system for example. See [`File::open`] or
2357 /// [`OpenOptions::open`] for more information.
2358 ///
2359 /// [`is_dir`]: FileType::is_dir
2360 /// [`is_symlink`]: FileType::is_symlink
2361 ///
2362 /// # Examples
2363 ///
2364 /// ```no_run
2365 /// fn main() -> std::io::Result<()> {
2366 /// use std::fs;
2367 ///
2368 /// let metadata = fs::metadata("foo.txt")?;
2369 /// let file_type = metadata.file_type();
2370 ///
2371 /// assert_eq!(file_type.is_file(), true);
2372 /// Ok(())
2373 /// }
2374 /// ```
2375 #[must_use]
2376 #[stable(feature = "file_type", since = "1.1.0")]
2377 pub fn is_file(&self) -> bool {
2378 self.0.is_file()
2379 }
2380
2381 /// Tests whether this file type represents a symbolic link.
2382 /// The result is mutually exclusive to the results of
2383 /// [`is_dir`] and [`is_file`]; only zero or one of these
2384 /// tests may pass.
2385 ///
2386 /// The underlying [`Metadata`] struct needs to be retrieved
2387 /// with the [`fs::symlink_metadata`] function and not the
2388 /// [`fs::metadata`] function. The [`fs::metadata`] function
2389 /// follows symbolic links, so [`is_symlink`] would always
2390 /// return `false` for the target file.
2391 ///
2392 /// [`fs::metadata`]: metadata
2393 /// [`fs::symlink_metadata`]: symlink_metadata
2394 /// [`is_dir`]: FileType::is_dir
2395 /// [`is_file`]: FileType::is_file
2396 /// [`is_symlink`]: FileType::is_symlink
2397 ///
2398 /// # Examples
2399 ///
2400 /// ```no_run
2401 /// use std::fs;
2402 ///
2403 /// fn main() -> std::io::Result<()> {
2404 /// let metadata = fs::symlink_metadata("foo.txt")?;
2405 /// let file_type = metadata.file_type();
2406 ///
2407 /// assert_eq!(file_type.is_symlink(), false);
2408 /// Ok(())
2409 /// }
2410 /// ```
2411 #[must_use]
2412 #[stable(feature = "file_type", since = "1.1.0")]
2413 pub fn is_symlink(&self) -> bool {
2414 self.0.is_symlink()
2415 }
2416}
2417
2418#[stable(feature = "std_debug", since = "1.16.0")]
2419impl fmt::Debug for FileType {
2420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2421 f.debug_struct("FileType")
2422 .field("is_file", &self.is_file())
2423 .field("is_dir", &self.is_dir())
2424 .field("is_symlink", &self.is_symlink())
2425 .finish_non_exhaustive()
2426 }
2427}
2428
2429impl AsInner<fs_imp::FileType> for FileType {
2430 #[inline]
2431 fn as_inner(&self) -> &fs_imp::FileType {
2432 &self.0
2433 }
2434}
2435
2436impl FromInner<fs_imp::FilePermissions> for Permissions {
2437 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2438 Permissions(f)
2439 }
2440}
2441
2442impl AsInner<fs_imp::FilePermissions> for Permissions {
2443 #[inline]
2444 fn as_inner(&self) -> &fs_imp::FilePermissions {
2445 &self.0
2446 }
2447}
2448
2449#[stable(feature = "rust1", since = "1.0.0")]
2450impl Iterator for ReadDir {
2451 type Item = io::Result<DirEntry>;
2452
2453 fn next(&mut self) -> Option<io::Result<DirEntry>> {
2454 self.0.next().map(|entry| entry.map(DirEntry))
2455 }
2456}
2457
2458impl DirEntry {
2459 /// Returns the full path to the file that this entry represents.
2460 ///
2461 /// The full path is created by joining the original path to `read_dir`
2462 /// with the filename of this entry.
2463 ///
2464 /// # Examples
2465 ///
2466 /// ```no_run
2467 /// use std::fs;
2468 ///
2469 /// fn main() -> std::io::Result<()> {
2470 /// for entry in fs::read_dir(".")? {
2471 /// let dir = entry?;
2472 /// println!("{:?}", dir.path());
2473 /// }
2474 /// Ok(())
2475 /// }
2476 /// ```
2477 ///
2478 /// This prints output like:
2479 ///
2480 /// ```text
2481 /// "./whatever.txt"
2482 /// "./foo.html"
2483 /// "./hello_world.rs"
2484 /// ```
2485 ///
2486 /// The exact text, of course, depends on what files you have in `.`.
2487 #[must_use]
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 pub fn path(&self) -> PathBuf {
2490 self.0.path()
2491 }
2492
2493 /// Returns the metadata for the file that this entry points at.
2494 ///
2495 /// This function will not traverse symlinks if this entry points at a
2496 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2497 ///
2498 /// [`fs::metadata`]: metadata
2499 /// [`fs::File::metadata`]: File::metadata
2500 ///
2501 /// # Platform-specific behavior
2502 ///
2503 /// On Windows this function is cheap to call (no extra system calls
2504 /// needed), but on Unix platforms this function is the equivalent of
2505 /// calling `symlink_metadata` on the path.
2506 ///
2507 /// # Examples
2508 ///
2509 /// ```
2510 /// use std::fs;
2511 ///
2512 /// if let Ok(entries) = fs::read_dir(".") {
2513 /// for entry in entries {
2514 /// if let Ok(entry) = entry {
2515 /// // Here, `entry` is a `DirEntry`.
2516 /// if let Ok(metadata) = entry.metadata() {
2517 /// // Now let's show our entry's permissions!
2518 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
2519 /// } else {
2520 /// println!("Couldn't get metadata for {:?}", entry.path());
2521 /// }
2522 /// }
2523 /// }
2524 /// }
2525 /// ```
2526 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2527 pub fn metadata(&self) -> io::Result<Metadata> {
2528 self.0.metadata().map(Metadata)
2529 }
2530
2531 /// Returns the file type for the file that this entry points at.
2532 ///
2533 /// This function will not traverse symlinks if this entry points at a
2534 /// symlink.
2535 ///
2536 /// # Platform-specific behavior
2537 ///
2538 /// On Windows and most Unix platforms this function is free (no extra
2539 /// system calls needed), but some Unix platforms may require the equivalent
2540 /// call to `symlink_metadata` to learn about the target file type.
2541 ///
2542 /// # Examples
2543 ///
2544 /// ```
2545 /// use std::fs;
2546 ///
2547 /// if let Ok(entries) = fs::read_dir(".") {
2548 /// for entry in entries {
2549 /// if let Ok(entry) = entry {
2550 /// // Here, `entry` is a `DirEntry`.
2551 /// if let Ok(file_type) = entry.file_type() {
2552 /// // Now let's show our entry's file type!
2553 /// println!("{:?}: {:?}", entry.path(), file_type);
2554 /// } else {
2555 /// println!("Couldn't get file type for {:?}", entry.path());
2556 /// }
2557 /// }
2558 /// }
2559 /// }
2560 /// ```
2561 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2562 pub fn file_type(&self) -> io::Result<FileType> {
2563 self.0.file_type().map(FileType)
2564 }
2565
2566 /// Returns the file name of this directory entry without any
2567 /// leading path component(s).
2568 ///
2569 /// As an example,
2570 /// the output of the function will result in "foo" for all the following paths:
2571 /// - "./foo"
2572 /// - "/the/foo"
2573 /// - "../../foo"
2574 ///
2575 /// # Examples
2576 ///
2577 /// ```
2578 /// use std::fs;
2579 ///
2580 /// if let Ok(entries) = fs::read_dir(".") {
2581 /// for entry in entries {
2582 /// if let Ok(entry) = entry {
2583 /// // Here, `entry` is a `DirEntry`.
2584 /// println!("{:?}", entry.file_name());
2585 /// }
2586 /// }
2587 /// }
2588 /// ```
2589 #[must_use]
2590 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2591 pub fn file_name(&self) -> OsString {
2592 self.0.file_name()
2593 }
2594}
2595
2596#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2597impl fmt::Debug for DirEntry {
2598 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2599 f.debug_tuple("DirEntry").field(&self.path()).finish()
2600 }
2601}
2602
2603impl AsInner<fs_imp::DirEntry> for DirEntry {
2604 #[inline]
2605 fn as_inner(&self) -> &fs_imp::DirEntry {
2606 &self.0
2607 }
2608}
2609
2610/// Removes a file from the filesystem.
2611///
2612/// Note that there is no
2613/// guarantee that the file is immediately deleted (e.g., depending on
2614/// platform, other open file descriptors may prevent immediate removal).
2615///
2616/// # Platform-specific behavior
2617///
2618/// This function currently corresponds to the `unlink` function on Unix.
2619/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2620/// Note that, this [may change in the future][changes].
2621///
2622/// [changes]: io#platform-specific-behavior
2623///
2624/// # Errors
2625///
2626/// This function will return an error in the following situations, but is not
2627/// limited to just these cases:
2628///
2629/// * `path` points to a directory.
2630/// * The file doesn't exist.
2631/// * The user lacks permissions to remove the file.
2632///
2633/// This function will only ever return an error of kind `NotFound` if the given
2634/// path does not exist. Note that the inverse is not true,
2635/// i.e. if a path does not exist, its removal may fail for a number of reasons,
2636/// such as insufficient permissions.
2637///
2638/// # Examples
2639///
2640/// ```no_run
2641/// use std::fs;
2642///
2643/// fn main() -> std::io::Result<()> {
2644/// fs::remove_file("a.txt")?;
2645/// Ok(())
2646/// }
2647/// ```
2648#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
2649#[stable(feature = "rust1", since = "1.0.0")]
2650pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
2651 fs_imp::remove_file(path.as_ref())
2652}
2653
2654/// Given a path, queries the file system to get information about a file,
2655/// directory, etc.
2656///
2657/// This function will traverse symbolic links to query information about the
2658/// destination file.
2659///
2660/// # Platform-specific behavior
2661///
2662/// This function currently corresponds to the `stat` function on Unix
2663/// and the `GetFileInformationByHandle` function on Windows.
2664/// Note that, this [may change in the future][changes].
2665///
2666/// [changes]: io#platform-specific-behavior
2667///
2668/// # Errors
2669///
2670/// This function will return an error in the following situations, but is not
2671/// limited to just these cases:
2672///
2673/// * The user lacks permissions to perform `metadata` call on `path`.
2674/// * `path` does not exist.
2675///
2676/// # Examples
2677///
2678/// ```rust,no_run
2679/// use std::fs;
2680///
2681/// fn main() -> std::io::Result<()> {
2682/// let attr = fs::metadata("/some/file/path.txt")?;
2683/// // inspect attr ...
2684/// Ok(())
2685/// }
2686/// ```
2687#[doc(alias = "stat")]
2688#[stable(feature = "rust1", since = "1.0.0")]
2689pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2690 fs_imp::metadata(path.as_ref()).map(Metadata)
2691}
2692
2693/// Queries the metadata about a file without following symlinks.
2694///
2695/// # Platform-specific behavior
2696///
2697/// This function currently corresponds to the `lstat` function on Unix
2698/// and the `GetFileInformationByHandle` function on Windows.
2699/// Note that, this [may change in the future][changes].
2700///
2701/// [changes]: io#platform-specific-behavior
2702///
2703/// # Errors
2704///
2705/// This function will return an error in the following situations, but is not
2706/// limited to just these cases:
2707///
2708/// * The user lacks permissions to perform `metadata` call on `path`.
2709/// * `path` does not exist.
2710///
2711/// # Examples
2712///
2713/// ```rust,no_run
2714/// use std::fs;
2715///
2716/// fn main() -> std::io::Result<()> {
2717/// let attr = fs::symlink_metadata("/some/file/path.txt")?;
2718/// // inspect attr ...
2719/// Ok(())
2720/// }
2721/// ```
2722#[doc(alias = "lstat")]
2723#[stable(feature = "symlink_metadata", since = "1.1.0")]
2724pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
2725 fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
2726}
2727
2728/// Renames a file or directory to a new name, replacing the original file if
2729/// `to` already exists.
2730///
2731/// This will not work if the new name is on a different mount point.
2732///
2733/// # Platform-specific behavior
2734///
2735/// This function currently corresponds to the `rename` function on Unix
2736/// and the `MoveFileExW` or `SetFileInformationByHandle` function on Windows.
2737///
2738/// Because of this, the behavior when both `from` and `to` exist differs. On
2739/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
2740/// `from` is not a directory, `to` must also be not a directory. The behavior
2741/// on Windows is the same on Windows 10 1607 and higher if `FileRenameInfoEx`
2742/// is supported by the filesystem; otherwise, `from` can be anything, but
2743/// `to` must *not* be a directory.
2744///
2745/// Note that, this [may change in the future][changes].
2746///
2747/// [changes]: io#platform-specific-behavior
2748///
2749/// # Errors
2750///
2751/// This function will return an error in the following situations, but is not
2752/// limited to just these cases:
2753///
2754/// * `from` does not exist.
2755/// * The user lacks permissions to view contents.
2756/// * `from` and `to` are on separate filesystems.
2757///
2758/// # Examples
2759///
2760/// ```no_run
2761/// use std::fs;
2762///
2763/// fn main() -> std::io::Result<()> {
2764/// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
2765/// Ok(())
2766/// }
2767/// ```
2768#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
2769#[stable(feature = "rust1", since = "1.0.0")]
2770pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
2771 fs_imp::rename(from.as_ref(), to.as_ref())
2772}
2773
2774/// Copies the contents of one file to another. This function will also
2775/// copy the permission bits of the original file to the destination file.
2776///
2777/// This function will **overwrite** the contents of `to`.
2778///
2779/// Note that if `from` and `to` both point to the same file, then the file
2780/// will likely get truncated by this operation.
2781///
2782/// On success, the total number of bytes copied is returned and it is equal to
2783/// the length of the `to` file as reported by `metadata`.
2784///
2785/// If you want to copy the contents of one file to another and you’re
2786/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
2787///
2788/// # Platform-specific behavior
2789///
2790/// This function currently corresponds to the `open` function in Unix
2791/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
2792/// `O_CLOEXEC` is set for returned file descriptors.
2793///
2794/// On Linux (including Android), this function uses copy_file_range(2),
2795/// sendfile(2), or splice(2) syscalls to move data directly between files
2796/// if possible.
2797///
2798/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
2799/// NTFS streams are copied but only the size of the main stream is returned by
2800/// this function.
2801///
2802/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
2803///
2804/// Note that platform-specific behavior [may change in the future][changes].
2805///
2806/// [changes]: io#platform-specific-behavior
2807///
2808/// # Errors
2809///
2810/// This function will return an error in the following situations, but is not
2811/// limited to just these cases:
2812///
2813/// * `from` is neither a regular file nor a symlink to a regular file.
2814/// * `from` does not exist.
2815/// * The current process does not have the permission rights to read
2816/// `from` or write `to`.
2817/// * The parent directory of `to` doesn't exist.
2818///
2819/// # Examples
2820///
2821/// ```no_run
2822/// use std::fs;
2823///
2824/// fn main() -> std::io::Result<()> {
2825/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
2826/// Ok(())
2827/// }
2828/// ```
2829#[doc(alias = "cp")]
2830#[doc(alias = "CopyFile", alias = "CopyFileEx")]
2831#[doc(alias = "fclonefileat", alias = "fcopyfile")]
2832#[stable(feature = "rust1", since = "1.0.0")]
2833pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
2834 fs_imp::copy(from.as_ref(), to.as_ref())
2835}
2836
2837/// Creates a new hard link on the filesystem.
2838///
2839/// The `link` path will be a link pointing to the `original` path. Note that
2840/// systems often require these two paths to both be located on the same
2841/// filesystem.
2842///
2843/// If `original` names a symbolic link, it is platform-specific whether the
2844/// symbolic link is followed. On platforms where it's possible to not follow
2845/// it, it is not followed, and the created hard link points to the symbolic
2846/// link itself.
2847///
2848/// # Platform-specific behavior
2849///
2850/// This function currently corresponds to the `CreateHardLink` function on Windows.
2851/// On most Unix systems, it corresponds to the `linkat` function with no flags.
2852/// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2853/// On MacOS, it uses the `linkat` function if it is available, but on very old
2854/// systems where `linkat` is not available, `link` is selected at runtime instead.
2855/// Note that, this [may change in the future][changes].
2856///
2857/// [changes]: io#platform-specific-behavior
2858///
2859/// # Errors
2860///
2861/// This function will return an error in the following situations, but is not
2862/// limited to just these cases:
2863///
2864/// * The `original` path is not a file or doesn't exist.
2865/// * The 'link' path already exists.
2866///
2867/// # Examples
2868///
2869/// ```no_run
2870/// use std::fs;
2871///
2872/// fn main() -> std::io::Result<()> {
2873/// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2874/// Ok(())
2875/// }
2876/// ```
2877#[doc(alias = "CreateHardLink", alias = "linkat")]
2878#[stable(feature = "rust1", since = "1.0.0")]
2879pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2880 fs_imp::hard_link(original.as_ref(), link.as_ref())
2881}
2882
2883/// Creates a new symbolic link on the filesystem.
2884///
2885/// The `link` path will be a symbolic link pointing to the `original` path.
2886/// On Windows, this will be a file symlink, not a directory symlink;
2887/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2888/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2889/// used instead to make the intent explicit.
2890///
2891/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2892/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2893/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2894///
2895/// # Examples
2896///
2897/// ```no_run
2898/// use std::fs;
2899///
2900/// fn main() -> std::io::Result<()> {
2901/// fs::soft_link("a.txt", "b.txt")?;
2902/// Ok(())
2903/// }
2904/// ```
2905#[stable(feature = "rust1", since = "1.0.0")]
2906#[deprecated(
2907 since = "1.1.0",
2908 note = "replaced with std::os::unix::fs::symlink and \
2909 std::os::windows::fs::{symlink_file, symlink_dir}"
2910)]
2911pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2912 fs_imp::symlink(original.as_ref(), link.as_ref())
2913}
2914
2915/// Reads a symbolic link, returning the file that the link points to.
2916///
2917/// # Platform-specific behavior
2918///
2919/// This function currently corresponds to the `readlink` function on Unix
2920/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2921/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2922/// Note that, this [may change in the future][changes].
2923///
2924/// [changes]: io#platform-specific-behavior
2925///
2926/// # Errors
2927///
2928/// This function will return an error in the following situations, but is not
2929/// limited to just these cases:
2930///
2931/// * `path` is not a symbolic link.
2932/// * `path` does not exist.
2933///
2934/// # Examples
2935///
2936/// ```no_run
2937/// use std::fs;
2938///
2939/// fn main() -> std::io::Result<()> {
2940/// let path = fs::read_link("a.txt")?;
2941/// Ok(())
2942/// }
2943/// ```
2944#[stable(feature = "rust1", since = "1.0.0")]
2945pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2946 fs_imp::read_link(path.as_ref())
2947}
2948
2949/// Returns the canonical, absolute form of a path with all intermediate
2950/// components normalized and symbolic links resolved.
2951///
2952/// # Platform-specific behavior
2953///
2954/// This function currently corresponds to the `realpath` function on Unix
2955/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2956/// Note that this [may change in the future][changes].
2957///
2958/// On Windows, this converts the path to use [extended length path][path]
2959/// syntax, which allows your program to use longer path names, but means you
2960/// can only join backslash-delimited paths to it, and it may be incompatible
2961/// with other applications (if passed to the application on the command-line,
2962/// or written to a file another application may read).
2963///
2964/// [changes]: io#platform-specific-behavior
2965/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2966///
2967/// # Errors
2968///
2969/// This function will return an error in the following situations, but is not
2970/// limited to just these cases:
2971///
2972/// * `path` does not exist.
2973/// * A non-final component in path is not a directory.
2974///
2975/// # Examples
2976///
2977/// ```no_run
2978/// use std::fs;
2979///
2980/// fn main() -> std::io::Result<()> {
2981/// let path = fs::canonicalize("../a/../foo.txt")?;
2982/// Ok(())
2983/// }
2984/// ```
2985#[doc(alias = "realpath")]
2986#[doc(alias = "GetFinalPathNameByHandle")]
2987#[stable(feature = "fs_canonicalize", since = "1.5.0")]
2988pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2989 fs_imp::canonicalize(path.as_ref())
2990}
2991
2992/// Creates a new, empty directory at the provided path.
2993///
2994/// # Platform-specific behavior
2995///
2996/// This function currently corresponds to the `mkdir` function on Unix
2997/// and the `CreateDirectoryW` function on Windows.
2998/// Note that, this [may change in the future][changes].
2999///
3000/// [changes]: io#platform-specific-behavior
3001///
3002/// **NOTE**: If a parent of the given path doesn't exist, this function will
3003/// return an error. To create a directory and all its missing parents at the
3004/// same time, use the [`create_dir_all`] function.
3005///
3006/// # Errors
3007///
3008/// This function will return an error in the following situations, but is not
3009/// limited to just these cases:
3010///
3011/// * User lacks permissions to create directory at `path`.
3012/// * A parent of the given path doesn't exist. (To create a directory and all
3013/// its missing parents at the same time, use the [`create_dir_all`]
3014/// function.)
3015/// * `path` already exists.
3016///
3017/// # Examples
3018///
3019/// ```no_run
3020/// use std::fs;
3021///
3022/// fn main() -> std::io::Result<()> {
3023/// fs::create_dir("/some/dir")?;
3024/// Ok(())
3025/// }
3026/// ```
3027#[doc(alias = "mkdir", alias = "CreateDirectory")]
3028#[stable(feature = "rust1", since = "1.0.0")]
3029#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
3030pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3031 DirBuilder::new().create(path.as_ref())
3032}
3033
3034/// Recursively create a directory and all of its parent components if they
3035/// are missing.
3036///
3037/// This function is not atomic. If it returns an error, any parent components it was able to create
3038/// will remain.
3039///
3040/// If the empty path is passed to this function, it always succeeds without
3041/// creating any directories.
3042///
3043/// # Platform-specific behavior
3044///
3045/// This function currently corresponds to multiple calls to the `mkdir`
3046/// function on Unix and the `CreateDirectoryW` function on Windows.
3047///
3048/// Note that, this [may change in the future][changes].
3049///
3050/// [changes]: io#platform-specific-behavior
3051///
3052/// # Errors
3053///
3054/// The function will return an error if any directory specified in path does not exist and
3055/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
3056///
3057/// Notable exception is made for situations where any of the directories
3058/// specified in the `path` could not be created as it was being created concurrently.
3059/// Such cases are considered to be successful. That is, calling `create_dir_all`
3060/// concurrently from multiple threads or processes is guaranteed not to fail
3061/// due to a race condition with itself.
3062///
3063/// [`fs::create_dir`]: create_dir
3064///
3065/// # Examples
3066///
3067/// ```no_run
3068/// use std::fs;
3069///
3070/// fn main() -> std::io::Result<()> {
3071/// fs::create_dir_all("/some/dir")?;
3072/// Ok(())
3073/// }
3074/// ```
3075#[stable(feature = "rust1", since = "1.0.0")]
3076pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3077 DirBuilder::new().recursive(true).create(path.as_ref())
3078}
3079
3080/// Removes an empty directory.
3081///
3082/// If you want to remove a directory that is not empty, as well as all
3083/// of its contents recursively, consider using [`remove_dir_all`]
3084/// instead.
3085///
3086/// # Platform-specific behavior
3087///
3088/// This function currently corresponds to the `rmdir` function on Unix
3089/// and the `RemoveDirectory` function on Windows.
3090/// Note that, this [may change in the future][changes].
3091///
3092/// [changes]: io#platform-specific-behavior
3093///
3094/// # Errors
3095///
3096/// This function will return an error in the following situations, but is not
3097/// limited to just these cases:
3098///
3099/// * `path` doesn't exist.
3100/// * `path` isn't a directory.
3101/// * The user lacks permissions to remove the directory at the provided `path`.
3102/// * The directory isn't empty.
3103///
3104/// This function will only ever return an error of kind `NotFound` if the given
3105/// path does not exist. Note that the inverse is not true,
3106/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3107/// such as insufficient permissions.
3108///
3109/// # Examples
3110///
3111/// ```no_run
3112/// use std::fs;
3113///
3114/// fn main() -> std::io::Result<()> {
3115/// fs::remove_dir("/some/dir")?;
3116/// Ok(())
3117/// }
3118/// ```
3119#[doc(alias = "rmdir", alias = "RemoveDirectory")]
3120#[stable(feature = "rust1", since = "1.0.0")]
3121pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3122 fs_imp::remove_dir(path.as_ref())
3123}
3124
3125/// Removes a directory at this path, after removing all its contents. Use
3126/// carefully!
3127///
3128/// This function does **not** follow symbolic links and it will simply remove the
3129/// symbolic link itself.
3130///
3131/// # Platform-specific behavior
3132///
3133/// These implementation details [may change in the future][changes].
3134///
3135/// - "Unix-like": By default, this function currently corresponds to
3136/// `openat`, `fdopendir`, `unlinkat` and `lstat`
3137/// on Unix-family platforms, except where noted otherwise.
3138/// - "Windows": This function currently corresponds to `CreateFileW`,
3139/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
3140///
3141/// ## Time-of-check to time-of-use (TOCTOU) race conditions
3142/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
3143///
3144/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
3145/// However, on the following platforms, this protection is not provided and the function should
3146/// not be used in security-sensitive contexts:
3147/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
3148/// TOCTOU races, Miri will not do so.
3149/// - **QNX**, **Redox OS**, **VxWorks**: This function does not protect against TOCTOU races, as
3150/// the underlying platform does not implement the required platform support to do so.
3151///
3152/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3153/// [changes]: io#platform-specific-behavior
3154///
3155/// # Errors
3156///
3157/// See [`fs::remove_file`] and [`fs::remove_dir`].
3158///
3159/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3160/// paths, *including* the root `path`. Consequently,
3161///
3162/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3163/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3164///
3165/// Consider ignoring the error if validating the removal is not required for your use case.
3166///
3167/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3168/// written into, which typically indicates some contents were removed but not all.
3169/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3170///
3171/// [`fs::remove_file`]: remove_file
3172/// [`fs::remove_dir`]: remove_dir
3173///
3174/// # Examples
3175///
3176/// ```no_run
3177/// use std::fs;
3178///
3179/// fn main() -> std::io::Result<()> {
3180/// fs::remove_dir_all("/some/dir")?;
3181/// Ok(())
3182/// }
3183/// ```
3184#[stable(feature = "rust1", since = "1.0.0")]
3185pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3186 fs_imp::remove_dir_all(path.as_ref())
3187}
3188
3189/// Returns an iterator over the entries within a directory.
3190///
3191/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3192/// New errors may be encountered after an iterator is initially constructed.
3193/// Entries for the current and parent directories (typically `.` and `..`) are
3194/// skipped.
3195///
3196/// The order in which `read_dir` returns entries can change between calls. If reproducible
3197/// ordering is required, the entries should be explicitly sorted.
3198///
3199/// # Platform-specific behavior
3200///
3201/// This function currently corresponds to the `opendir` function on Unix
3202/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3203/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3204/// Note that, this [may change in the future][changes].
3205///
3206/// [changes]: io#platform-specific-behavior
3207///
3208/// The order in which this iterator returns entries is platform and filesystem
3209/// dependent.
3210///
3211/// # Errors
3212///
3213/// This function will return an error in the following situations, but is not
3214/// limited to just these cases:
3215///
3216/// * The provided `path` doesn't exist.
3217/// * The process lacks permissions to view the contents.
3218/// * The `path` points at a non-directory file.
3219///
3220/// # Examples
3221///
3222/// ```
3223/// use std::io;
3224/// use std::fs::{self, DirEntry};
3225/// use std::path::Path;
3226///
3227/// // one possible implementation of walking a directory only visiting files
3228/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3229/// if dir.is_dir() {
3230/// for entry in fs::read_dir(dir)? {
3231/// let entry = entry?;
3232/// let path = entry.path();
3233/// if path.is_dir() {
3234/// visit_dirs(&path, cb)?;
3235/// } else {
3236/// cb(&entry);
3237/// }
3238/// }
3239/// }
3240/// Ok(())
3241/// }
3242/// ```
3243///
3244/// ```rust,no_run
3245/// use std::{fs, io};
3246///
3247/// fn main() -> io::Result<()> {
3248/// let mut entries = fs::read_dir(".")?
3249/// .map(|res| res.map(|e| e.path()))
3250/// .collect::<Result<Vec<_>, io::Error>>()?;
3251///
3252/// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3253/// // ordering is required the entries should be explicitly sorted.
3254///
3255/// entries.sort();
3256///
3257/// // The entries have now been sorted by their path.
3258///
3259/// Ok(())
3260/// }
3261/// ```
3262#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3263#[stable(feature = "rust1", since = "1.0.0")]
3264pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3265 fs_imp::read_dir(path.as_ref()).map(ReadDir)
3266}
3267
3268/// Changes the permissions found on a file or a directory.
3269///
3270/// # Platform-specific behavior
3271///
3272/// This function currently corresponds to the `chmod` function on Unix
3273/// and the `SetFileAttributes` function on Windows.
3274/// Note that, this [may change in the future][changes].
3275///
3276/// [changes]: io#platform-specific-behavior
3277///
3278/// ## Symlinks
3279/// On UNIX-like systems, this function will update the permission bits
3280/// of the file pointed to by the symlink.
3281///
3282/// Note that this behavior can lead to privilege escalation vulnerabilities,
3283/// where the ability to create a symlink in one directory allows you to
3284/// cause the permissions of another file or directory to be modified.
3285///
3286/// For this reason, using this function with symlinks should be avoided.
3287/// When possible, permissions should be set at creation time instead.
3288///
3289/// # Rationale
3290/// POSIX does not specify an `lchmod` function,
3291/// and symlinks can be followed regardless of what permission bits are set.
3292///
3293/// # Errors
3294///
3295/// This function will return an error in the following situations, but is not
3296/// limited to just these cases:
3297///
3298/// * `path` does not exist.
3299/// * The user lacks the permission to change attributes of the file.
3300///
3301/// # Examples
3302///
3303/// ```no_run
3304/// use std::fs;
3305///
3306/// fn main() -> std::io::Result<()> {
3307/// let mut perms = fs::metadata("foo.txt")?.permissions();
3308/// perms.set_readonly(true);
3309/// fs::set_permissions("foo.txt", perms)?;
3310/// Ok(())
3311/// }
3312/// ```
3313#[doc(alias = "chmod", alias = "SetFileAttributes")]
3314#[stable(feature = "set_permissions", since = "1.1.0")]
3315pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3316 fs_imp::set_permissions(path.as_ref(), perm.0)
3317}
3318
3319/// Set the permissions of a file, unless it is a symlink.
3320///
3321/// Note that the non-final path elements are allowed to be symlinks.
3322///
3323/// # Platform-specific behavior
3324///
3325/// Currently unimplemented on Windows.
3326///
3327/// On Unix platforms, this results in a [`FilesystemLoop`] error if the last element is a symlink.
3328///
3329/// This behavior may change in the future.
3330///
3331/// [`FilesystemLoop`]: crate::io::ErrorKind::FilesystemLoop
3332#[doc(alias = "chmod", alias = "SetFileAttributes")]
3333#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
3334pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3335 fs_imp::set_permissions_nofollow(path.as_ref(), perm)
3336}
3337
3338impl DirBuilder {
3339 /// Creates a new set of options with default mode/security settings for all
3340 /// platforms and also non-recursive.
3341 ///
3342 /// # Examples
3343 ///
3344 /// ```
3345 /// use std::fs::DirBuilder;
3346 ///
3347 /// let builder = DirBuilder::new();
3348 /// ```
3349 #[stable(feature = "dir_builder", since = "1.6.0")]
3350 #[must_use]
3351 pub fn new() -> DirBuilder {
3352 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3353 }
3354
3355 /// Indicates that directories should be created recursively, creating all
3356 /// parent directories. Parents that do not exist are created with the same
3357 /// security and permissions settings.
3358 ///
3359 /// This option defaults to `false`.
3360 ///
3361 /// # Examples
3362 ///
3363 /// ```
3364 /// use std::fs::DirBuilder;
3365 ///
3366 /// let mut builder = DirBuilder::new();
3367 /// builder.recursive(true);
3368 /// ```
3369 #[stable(feature = "dir_builder", since = "1.6.0")]
3370 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3371 self.recursive = recursive;
3372 self
3373 }
3374
3375 /// Creates the specified directory with the options configured in this
3376 /// builder.
3377 ///
3378 /// It is considered an error if the directory already exists unless
3379 /// recursive mode is enabled.
3380 ///
3381 /// # Examples
3382 ///
3383 /// ```no_run
3384 /// use std::fs::{self, DirBuilder};
3385 ///
3386 /// let path = "/tmp/foo/bar/baz";
3387 /// DirBuilder::new()
3388 /// .recursive(true)
3389 /// .create(path).unwrap();
3390 ///
3391 /// assert!(fs::metadata(path).unwrap().is_dir());
3392 /// ```
3393 #[stable(feature = "dir_builder", since = "1.6.0")]
3394 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3395 self._create(path.as_ref())
3396 }
3397
3398 fn _create(&self, path: &Path) -> io::Result<()> {
3399 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3400 }
3401
3402 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3403 // if path's parent is None, it is "/" path, which should
3404 // return Ok immediately
3405 if path == Path::new("") || path.parent() == None {
3406 return Ok(());
3407 }
3408
3409 let ancestors = path.ancestors();
3410 let mut uncreated_dirs = 0;
3411
3412 for ancestor in ancestors {
3413 // for relative paths like "foo/bar", the parent of
3414 // "foo" will be "" which there's no need to invoke
3415 // a mkdir syscall on
3416 if ancestor == Path::new("") || ancestor.parent() == None {
3417 break;
3418 }
3419
3420 match self.inner.mkdir(ancestor) {
3421 Ok(()) => break,
3422 Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
3423 // we check if the err is AlreadyExists for two reasons
3424 // - in case the path exists as a *file*
3425 // - and to avoid calls to .is_dir() in case of other errs
3426 // (i.e. PermissionDenied)
3427 Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
3428 Err(e) => return Err(e),
3429 }
3430 }
3431
3432 // collect only the uncreated directories w/o letting the vec resize
3433 let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
3434 uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
3435
3436 for uncreated_dir in uncreated_dirs_vec.iter().rev() {
3437 if let Err(e) = self.inner.mkdir(uncreated_dir) {
3438 if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
3439 return Err(e);
3440 }
3441 }
3442 }
3443
3444 Ok(())
3445 }
3446}
3447
3448impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3449 #[inline]
3450 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3451 &mut self.inner
3452 }
3453}
3454
3455/// Returns `Ok(true)` if the path points at an existing entity.
3456///
3457/// This function will traverse symbolic links to query information about the
3458/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3459///
3460/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3461/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3462/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3463/// permission is denied on one of the parent directories.
3464///
3465/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3466/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3467/// where those bugs are not an issue.
3468///
3469/// # Examples
3470///
3471/// ```no_run
3472/// use std::fs;
3473///
3474/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3475/// assert!(fs::exists("/root/secret_file.txt").is_err());
3476/// ```
3477///
3478/// [`Path::exists`]: crate::path::Path::exists
3479/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3480#[stable(feature = "fs_try_exists", since = "1.81.0")]
3481#[inline]
3482pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
3483 fs_imp::exists(path.as_ref())
3484}