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