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