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