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