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