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