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