1 // ignore-tidy-filelength
3 //! Filesystem manipulation operations.
5 //! This module contains basic methods to manipulate the contents of the local
6 //! filesystem. All methods in this module represent cross-platform filesystem
7 //! operations. Extra platform-specific functionality can be found in the
8 //! extension traits of `std::os::$platform`.
10 #![stable(feature = "rust1", since = "1.0.0")]
11 #![deny(unsafe_op_in_unsafe_fn)]
13 use crate::ffi::OsString;
15 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
16 use crate::path::{Path, PathBuf};
17 use crate::sys::fs as fs_imp;
18 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
19 use crate::time::SystemTime;
21 /// A reference to an open file on the filesystem.
23 /// An instance of a `File` can be read and/or written depending on what options
24 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
25 /// that the file contains internally.
27 /// Files are automatically closed when they go out of scope. Errors detected
28 /// on closing are ignored by the implementation of `Drop`. Use the method
29 /// [`sync_all`] if these errors must be manually handled.
33 /// Creates a new file and write bytes to it (you can also use [`write()`]):
36 /// use std::fs::File;
37 /// use std::io::prelude::*;
39 /// fn main() -> std::io::Result<()> {
40 /// let mut file = File::create("foo.txt")?;
41 /// file.write_all(b"Hello, world!")?;
46 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
49 /// use std::fs::File;
50 /// use std::io::prelude::*;
52 /// fn main() -> std::io::Result<()> {
53 /// let mut file = File::open("foo.txt")?;
54 /// let mut contents = String::new();
55 /// file.read_to_string(&mut contents)?;
56 /// assert_eq!(contents, "Hello, world!");
61 /// It can be more efficient to read the contents of a file with a buffered
62 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
65 /// use std::fs::File;
66 /// use std::io::BufReader;
67 /// use std::io::prelude::*;
69 /// fn main() -> std::io::Result<()> {
70 /// let file = File::open("foo.txt")?;
71 /// let mut buf_reader = BufReader::new(file);
72 /// let mut contents = String::new();
73 /// buf_reader.read_to_string(&mut contents)?;
74 /// assert_eq!(contents, "Hello, world!");
79 /// Note that, although read and write methods require a `&mut File`, because
80 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
81 /// still modify the file, either through methods that take `&File` or by
82 /// retrieving the underlying OS object and modifying the file that way.
83 /// Additionally, many operating systems allow concurrent modification of files
84 /// by different processes. Avoid assuming that holding a `&File` means that the
85 /// file will not change.
87 /// [`BufReader<R>`]: io::BufReader
88 /// [`sync_all`]: File::sync_all
89 #[stable(feature = "rust1", since = "1.0.0")]
94 /// Metadata information about a file.
96 /// This structure is returned from the [`metadata`] or
97 /// [`symlink_metadata`] function or method and represents known
98 /// metadata about a file such as its permissions, size, modification
100 #[stable(feature = "rust1", since = "1.0.0")]
102 pub struct Metadata(fs_imp::FileAttr);
104 /// Iterator over the entries in a directory.
106 /// This iterator is returned from the [`read_dir`] function of this module and
107 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
108 /// information like the entry's path and possibly other metadata can be
111 /// The order in which this iterator returns entries is platform and filesystem
116 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
117 /// IO error during iteration.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 pub struct ReadDir(fs_imp::ReadDir);
122 /// Entries returned by the [`ReadDir`] iterator.
124 /// An instance of `DirEntry` represents an entry inside of a directory on the
125 /// filesystem. Each entry can be inspected via methods to learn about the full
126 /// path or possibly other metadata through per-platform extension traits.
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct DirEntry(fs_imp::DirEntry);
130 /// Options and flags which can be used to configure how a file is opened.
132 /// This builder exposes the ability to configure how a [`File`] is opened and
133 /// what operations are permitted on the open file. The [`File::open`] and
134 /// [`File::create`] methods are aliases for commonly used options using this
137 /// Generally speaking, when using `OpenOptions`, you'll first call
138 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
139 /// call [`OpenOptions::open`], passing the path of the file you're trying to
140 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
141 /// can further operate on.
145 /// Opening a file to read:
148 /// use std::fs::OpenOptions;
150 /// let file = OpenOptions::new().read(true).open("foo.txt");
153 /// Opening a file for both reading and writing, as well as creating it if it
157 /// use std::fs::OpenOptions;
159 /// let file = OpenOptions::new()
163 /// .open("foo.txt");
165 #[derive(Clone, Debug)]
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub struct OpenOptions(fs_imp::OpenOptions);
169 /// Representation of the various permissions on a file.
171 /// This module only currently provides one bit of information,
172 /// [`Permissions::readonly`], which is exposed on all currently supported
173 /// platforms. Unix-specific functionality, such as mode bits, is available
174 /// through the [`PermissionsExt`] trait.
176 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
177 #[derive(Clone, PartialEq, Eq, Debug)]
178 #[stable(feature = "rust1", since = "1.0.0")]
179 pub struct Permissions(fs_imp::FilePermissions);
181 /// A structure representing a type of file with accessors for each file type.
182 /// It is returned by [`Metadata::file_type`] method.
183 #[stable(feature = "file_type", since = "1.1.0")]
184 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
185 pub struct FileType(fs_imp::FileType);
187 /// A builder used to create directories in various manners.
189 /// This builder also supports platform-specific options.
190 #[stable(feature = "dir_builder", since = "1.6.0")]
192 pub struct DirBuilder {
193 inner: fs_imp::DirBuilder,
197 /// Indicates how large a buffer to pre-allocate before reading the entire file.
198 fn initial_buffer_size(file: &File) -> usize {
199 // Allocate one extra byte so the buffer doesn't need to grow before the
200 // final `read` call at the end of the file. Don't worry about `usize`
201 // overflow because reading will fail regardless in that case.
202 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
205 /// Read the entire contents of a file into a bytes vector.
207 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
208 /// with fewer imports and without an intermediate variable. It pre-allocates a
209 /// buffer based on the file size when available, so it is generally faster than
210 /// reading into a vector created with [`Vec::new()`].
212 /// [`read_to_end`]: Read::read_to_end
216 /// This function will return an error if `path` does not already exist.
217 /// Other errors may also be returned according to [`OpenOptions::open`].
219 /// It will also return an error if it encounters while reading an error
220 /// of a kind other than [`io::ErrorKind::Interrupted`].
226 /// use std::net::SocketAddr;
228 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
229 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
233 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
234 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
235 fn inner(path: &Path) -> io::Result<Vec<u8>> {
236 let mut file = File::open(path)?;
237 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
238 file.read_to_end(&mut bytes)?;
244 /// Read the entire contents of a file into a string.
246 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
247 /// with fewer imports and without an intermediate variable. It pre-allocates a
248 /// buffer based on the file size when available, so it is generally faster than
249 /// reading into a string created with [`String::new()`].
251 /// [`read_to_string`]: Read::read_to_string
255 /// This function will return an error if `path` does not already exist.
256 /// Other errors may also be returned according to [`OpenOptions::open`].
258 /// It will also return an error if it encounters while reading an error
259 /// of a kind other than [`io::ErrorKind::Interrupted`],
260 /// or if the contents of the file are not valid UTF-8.
266 /// use std::net::SocketAddr;
268 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
269 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
273 #[stable(feature = "fs_read_write", since = "1.26.0")]
274 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
275 fn inner(path: &Path) -> io::Result<String> {
276 let mut file = File::open(path)?;
277 let mut string = String::with_capacity(initial_buffer_size(&file));
278 file.read_to_string(&mut string)?;
284 /// Write a slice as the entire contents of a file.
286 /// This function will create a file if it does not exist,
287 /// and will entirely replace its contents if it does.
289 /// This is a convenience function for using [`File::create`] and [`write_all`]
290 /// with fewer imports.
292 /// [`write_all`]: Write::write_all
299 /// fn main() -> std::io::Result<()> {
300 /// fs::write("foo.txt", b"Lorem ipsum")?;
301 /// fs::write("bar.txt", "dolor sit")?;
305 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
306 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
307 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
308 File::create(path)?.write_all(contents)
310 inner(path.as_ref(), contents.as_ref())
314 /// Attempts to open a file in read-only mode.
316 /// See the [`OpenOptions::open`] method for more details.
320 /// This function will return an error if `path` does not already exist.
321 /// Other errors may also be returned according to [`OpenOptions::open`].
326 /// use std::fs::File;
328 /// fn main() -> std::io::Result<()> {
329 /// let mut f = File::open("foo.txt")?;
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
335 OpenOptions::new().read(true).open(path.as_ref())
338 /// Opens a file in write-only mode.
340 /// This function will create a file if it does not exist,
341 /// and will truncate it if it does.
343 /// See the [`OpenOptions::open`] function for more details.
348 /// use std::fs::File;
350 /// fn main() -> std::io::Result<()> {
351 /// let mut f = File::create("foo.txt")?;
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
357 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
360 /// Returns a new OpenOptions object.
362 /// This function returns a new OpenOptions object that you can use to
363 /// open or create a file with specific options if `open()` or `create()`
364 /// are not appropriate.
366 /// It is equivalent to `OpenOptions::new()` but allows you to write more
367 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
368 /// you can write `File::with_options().read(true).open("foo.txt")`. This
369 /// also avoids the need to import `OpenOptions`.
371 /// See the [`OpenOptions::new`] function for more details.
376 /// #![feature(with_options)]
377 /// use std::fs::File;
379 /// fn main() -> std::io::Result<()> {
380 /// let mut f = File::with_options().read(true).open("foo.txt")?;
384 #[unstable(feature = "with_options", issue = "65439")]
385 pub fn with_options() -> OpenOptions {
389 /// Attempts to sync all OS-internal metadata to disk.
391 /// This function will attempt to ensure that all in-memory data reaches the
392 /// filesystem before returning.
394 /// This can be used to handle errors that would otherwise only be caught
395 /// when the `File` is closed. Dropping a file will ignore errors in
396 /// synchronizing this in-memory data.
401 /// use std::fs::File;
402 /// use std::io::prelude::*;
404 /// fn main() -> std::io::Result<()> {
405 /// let mut f = File::create("foo.txt")?;
406 /// f.write_all(b"Hello, world!")?;
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn sync_all(&self) -> io::Result<()> {
417 /// This function is similar to [`sync_all`], except that it may not
418 /// synchronize file metadata to the filesystem.
420 /// This is intended for use cases that must synchronize content, but don't
421 /// need the metadata on disk. The goal of this method is to reduce disk
424 /// Note that some platforms may simply implement this in terms of
427 /// [`sync_all`]: File::sync_all
432 /// use std::fs::File;
433 /// use std::io::prelude::*;
435 /// fn main() -> std::io::Result<()> {
436 /// let mut f = File::create("foo.txt")?;
437 /// f.write_all(b"Hello, world!")?;
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn sync_data(&self) -> io::Result<()> {
445 self.inner.datasync()
448 /// Truncates or extends the underlying file, updating the size of
449 /// this file to become `size`.
451 /// If the `size` is less than the current file's size, then the file will
452 /// be shrunk. If it is greater than the current file's size, then the file
453 /// will be extended to `size` and have all of the intermediate data filled
456 /// The file's cursor isn't changed. In particular, if the cursor was at the
457 /// end and the file is shrunk using this operation, the cursor will now be
462 /// This function will return an error if the file is not opened for writing.
463 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
464 /// length would cause an overflow due to the implementation specifics.
469 /// use std::fs::File;
471 /// fn main() -> std::io::Result<()> {
472 /// let mut f = File::create("foo.txt")?;
478 /// Note that this method alters the content of the underlying file, even
479 /// though it takes `&self` rather than `&mut self`.
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn set_len(&self, size: u64) -> io::Result<()> {
482 self.inner.truncate(size)
485 /// Queries metadata about the underlying file.
490 /// use std::fs::File;
492 /// fn main() -> std::io::Result<()> {
493 /// let mut f = File::open("foo.txt")?;
494 /// let metadata = f.metadata()?;
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn metadata(&self) -> io::Result<Metadata> {
500 self.inner.file_attr().map(Metadata)
503 /// Creates a new `File` instance that shares the same underlying file handle
504 /// as the existing `File` instance. Reads, writes, and seeks will affect
505 /// both `File` instances simultaneously.
509 /// Creates two handles for a file named `foo.txt`:
512 /// use std::fs::File;
514 /// fn main() -> std::io::Result<()> {
515 /// let mut file = File::open("foo.txt")?;
516 /// let file_copy = file.try_clone()?;
521 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
522 /// two handles, seek one of them, and read the remaining bytes from the
526 /// use std::fs::File;
527 /// use std::io::SeekFrom;
528 /// use std::io::prelude::*;
530 /// fn main() -> std::io::Result<()> {
531 /// let mut file = File::open("foo.txt")?;
532 /// let mut file_copy = file.try_clone()?;
534 /// file.seek(SeekFrom::Start(3))?;
536 /// let mut contents = vec![];
537 /// file_copy.read_to_end(&mut contents)?;
538 /// assert_eq!(contents, b"def\n");
542 #[stable(feature = "file_try_clone", since = "1.9.0")]
543 pub fn try_clone(&self) -> io::Result<File> {
544 Ok(File { inner: self.inner.duplicate()? })
547 /// Changes the permissions on the underlying file.
549 /// # Platform-specific behavior
551 /// This function currently corresponds to the `fchmod` function on Unix and
552 /// the `SetFileInformationByHandle` function on Windows. Note that, this
553 /// [may change in the future][changes].
555 /// [changes]: ../io/index.html#platform-specific-behavior
559 /// This function will return an error if the user lacks permission change
560 /// attributes on the underlying file. It may also return an error in other
561 /// os-specific unspecified cases.
566 /// fn main() -> std::io::Result<()> {
567 /// use std::fs::File;
569 /// let file = File::open("foo.txt")?;
570 /// let mut perms = file.metadata()?.permissions();
571 /// perms.set_readonly(true);
572 /// file.set_permissions(perms)?;
577 /// Note that this method alters the permissions of the underlying file,
578 /// even though it takes `&self` rather than `&mut self`.
579 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
580 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
581 self.inner.set_permissions(perm.0)
585 impl AsInner<fs_imp::File> for File {
586 fn as_inner(&self) -> &fs_imp::File {
590 impl FromInner<fs_imp::File> for File {
591 fn from_inner(f: fs_imp::File) -> File {
595 impl IntoInner<fs_imp::File> for File {
596 fn into_inner(self) -> fs_imp::File {
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl fmt::Debug for File {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 #[stable(feature = "rust1", since = "1.0.0")]
610 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
614 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
615 self.inner.read_vectored(bufs)
619 fn is_read_vectored(&self) -> bool {
620 self.inner.is_read_vectored()
624 unsafe fn initializer(&self) -> Initializer {
625 // SAFETY: Read is guaranteed to work on uninitialized memory
626 unsafe { Initializer::nop() }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl Write for File {
631 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
632 self.inner.write(buf)
635 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
636 self.inner.write_vectored(bufs)
640 fn is_write_vectored(&self) -> bool {
641 self.inner.is_write_vectored()
644 fn flush(&mut self) -> io::Result<()> {
648 #[stable(feature = "rust1", since = "1.0.0")]
650 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Read for &File {
656 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
660 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
661 self.inner.read_vectored(bufs)
665 fn is_read_vectored(&self) -> bool {
666 self.inner.is_read_vectored()
670 unsafe fn initializer(&self) -> Initializer {
671 // SAFETY: Read is guaranteed to work on uninitialized memory
672 unsafe { Initializer::nop() }
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl Write for &File {
677 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
678 self.inner.write(buf)
681 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
682 self.inner.write_vectored(bufs)
686 fn is_write_vectored(&self) -> bool {
687 self.inner.is_write_vectored()
690 fn flush(&mut self) -> io::Result<()> {
694 #[stable(feature = "rust1", since = "1.0.0")]
695 impl Seek for &File {
696 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
702 /// Creates a blank new set of options ready for configuration.
704 /// All options are initially set to `false`.
709 /// use std::fs::OpenOptions;
711 /// let mut options = OpenOptions::new();
712 /// let file = options.read(true).open("foo.txt");
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn new() -> Self {
716 OpenOptions(fs_imp::OpenOptions::new())
719 /// Sets the option for read access.
721 /// This option, when true, will indicate that the file should be
722 /// `read`-able if opened.
727 /// use std::fs::OpenOptions;
729 /// let file = OpenOptions::new().read(true).open("foo.txt");
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn read(&mut self, read: bool) -> &mut Self {
737 /// Sets the option for write access.
739 /// This option, when true, will indicate that the file should be
740 /// `write`-able if opened.
742 /// If the file already exists, any write calls on it will overwrite its
743 /// contents, without truncating it.
748 /// use std::fs::OpenOptions;
750 /// let file = OpenOptions::new().write(true).open("foo.txt");
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn write(&mut self, write: bool) -> &mut Self {
758 /// Sets the option for the append mode.
760 /// This option, when true, means that writes will append to a file instead
761 /// of overwriting previous contents.
762 /// Note that setting `.write(true).append(true)` has the same effect as
763 /// setting only `.append(true)`.
765 /// For most filesystems, the operating system guarantees that all writes are
766 /// atomic: no writes get mangled because another process writes at the same
769 /// One maybe obvious note when using append-mode: make sure that all data
770 /// that belongs together is written to the file in one operation. This
771 /// can be done by concatenating strings before passing them to [`write()`],
772 /// or using a buffered writer (with a buffer of adequate size),
773 /// and calling [`flush()`] when the message is complete.
775 /// If a file is opened with both read and append access, beware that after
776 /// opening, and after every write, the position for reading may be set at the
777 /// end of the file. So, before writing, save the current position (using
778 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
782 /// This function doesn't create the file if it doesn't exist. Use the
783 /// [`OpenOptions::create`] method to do so.
785 /// [`write()`]: Write::write
786 /// [`flush()`]: Write::flush
787 /// [`seek`]: Seek::seek
788 /// [`Current`]: SeekFrom::Current
793 /// use std::fs::OpenOptions;
795 /// let file = OpenOptions::new().append(true).open("foo.txt");
797 #[stable(feature = "rust1", since = "1.0.0")]
798 pub fn append(&mut self, append: bool) -> &mut Self {
799 self.0.append(append);
803 /// Sets the option for truncating a previous file.
805 /// If a file is successfully opened with this option set it will truncate
806 /// the file to 0 length if it already exists.
808 /// The file must be opened with write access for truncate to work.
813 /// use std::fs::OpenOptions;
815 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
819 self.0.truncate(truncate);
823 /// Sets the option to create a new file, or open it if it already exists.
825 /// In order for the file to be created, [`OpenOptions::write`] or
826 /// [`OpenOptions::append`] access must be used.
831 /// use std::fs::OpenOptions;
833 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn create(&mut self, create: bool) -> &mut Self {
837 self.0.create(create);
841 /// Sets the option to create a new file, failing if it already exists.
843 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
844 /// way, if the call succeeds, the file returned is guaranteed to be new.
846 /// This option is useful because it is atomic. Otherwise between checking
847 /// whether a file exists and creating a new one, the file may have been
848 /// created by another process (a TOCTOU race condition / attack).
850 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
853 /// The file must be opened with write or append access in order to create
856 /// [`.create()`]: OpenOptions::create
857 /// [`.truncate()`]: OpenOptions::truncate
862 /// use std::fs::OpenOptions;
864 /// let file = OpenOptions::new().write(true)
865 /// .create_new(true)
866 /// .open("foo.txt");
868 #[stable(feature = "expand_open_options2", since = "1.9.0")]
869 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
870 self.0.create_new(create_new);
874 /// Opens a file at `path` with the options specified by `self`.
878 /// This function will return an error under a number of different
879 /// circumstances. Some of these error conditions are listed here, together
880 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
881 /// part of the compatibility contract of the function, especially the
882 /// [`Other`] kind might change to more specific kinds in the future.
884 /// * [`NotFound`]: The specified file does not exist and neither `create`
885 /// or `create_new` is set.
886 /// * [`NotFound`]: One of the directory components of the file path does
888 /// * [`PermissionDenied`]: The user lacks permission to get the specified
889 /// access rights for the file.
890 /// * [`PermissionDenied`]: The user lacks permission to open one of the
891 /// directory components of the specified path.
892 /// * [`AlreadyExists`]: `create_new` was specified and the file already
894 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
895 /// without write access, no access mode set, etc.).
896 /// * [`Other`]: One of the directory components of the specified file path
897 /// was not, in fact, a directory.
898 /// * [`Other`]: Filesystem-level errors: full disk, write permission
899 /// requested on a read-only file system, exceeded disk quota, too many
900 /// open files, too long filename, too many symbolic links in the
901 /// specified path (Unix-like systems only), etc.
906 /// use std::fs::OpenOptions;
908 /// let file = OpenOptions::new().read(true).open("foo.txt");
911 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
912 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
913 /// [`NotFound`]: io::ErrorKind::NotFound
914 /// [`Other`]: io::ErrorKind::Other
915 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
918 self._open(path.as_ref())
921 fn _open(&self, path: &Path) -> io::Result<File> {
922 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
926 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
927 fn as_inner(&self) -> &fs_imp::OpenOptions {
932 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
933 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
939 /// Returns the file type for this metadata.
944 /// fn main() -> std::io::Result<()> {
947 /// let metadata = fs::metadata("foo.txt")?;
949 /// println!("{:?}", metadata.file_type());
953 #[stable(feature = "file_type", since = "1.1.0")]
954 pub fn file_type(&self) -> FileType {
955 FileType(self.0.file_type())
958 /// Returns `true` if this metadata is for a directory. The
959 /// result is mutually exclusive to the result of
960 /// [`Metadata::is_file`], and will be false for symlink metadata
961 /// obtained from [`symlink_metadata`].
966 /// fn main() -> std::io::Result<()> {
969 /// let metadata = fs::metadata("foo.txt")?;
971 /// assert!(!metadata.is_dir());
975 #[stable(feature = "rust1", since = "1.0.0")]
976 pub fn is_dir(&self) -> bool {
977 self.file_type().is_dir()
980 /// Returns `true` if this metadata is for a regular file. The
981 /// result is mutually exclusive to the result of
982 /// [`Metadata::is_dir`], and will be false for symlink metadata
983 /// obtained from [`symlink_metadata`].
985 /// When the goal is simply to read from (or write to) the source, the most
986 /// reliable way to test the source can be read (or written to) is to open
987 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
988 /// a Unix-like system for example. See [`File::open`] or
989 /// [`OpenOptions::open`] for more information.
996 /// fn main() -> std::io::Result<()> {
997 /// let metadata = fs::metadata("foo.txt")?;
999 /// assert!(metadata.is_file());
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn is_file(&self) -> bool {
1005 self.file_type().is_file()
1008 /// Returns the size of the file, in bytes, this metadata is for.
1015 /// fn main() -> std::io::Result<()> {
1016 /// let metadata = fs::metadata("foo.txt")?;
1018 /// assert_eq!(0, metadata.len());
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub fn len(&self) -> u64 {
1027 /// Returns the permissions of the file this metadata is for.
1034 /// fn main() -> std::io::Result<()> {
1035 /// let metadata = fs::metadata("foo.txt")?;
1037 /// assert!(!metadata.permissions().readonly());
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 pub fn permissions(&self) -> Permissions {
1043 Permissions(self.0.perm())
1046 /// Returns the last modification time listed in this metadata.
1048 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1049 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1053 /// This field may not be available on all platforms, and will return an
1054 /// `Err` on platforms where it is not available.
1061 /// fn main() -> std::io::Result<()> {
1062 /// let metadata = fs::metadata("foo.txt")?;
1064 /// if let Ok(time) = metadata.modified() {
1065 /// println!("{:?}", time);
1067 /// println!("Not supported on this platform");
1072 #[stable(feature = "fs_time", since = "1.10.0")]
1073 pub fn modified(&self) -> io::Result<SystemTime> {
1074 self.0.modified().map(FromInner::from_inner)
1077 /// Returns the last access time of this metadata.
1079 /// The returned value corresponds to the `atime` field of `stat` on Unix
1080 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1082 /// Note that not all platforms will keep this field update in a file's
1083 /// metadata, for example Windows has an option to disable updating this
1084 /// time when files are accessed and Linux similarly has `noatime`.
1088 /// This field may not be available on all platforms, and will return an
1089 /// `Err` on platforms where it is not available.
1096 /// fn main() -> std::io::Result<()> {
1097 /// let metadata = fs::metadata("foo.txt")?;
1099 /// if let Ok(time) = metadata.accessed() {
1100 /// println!("{:?}", time);
1102 /// println!("Not supported on this platform");
1107 #[stable(feature = "fs_time", since = "1.10.0")]
1108 pub fn accessed(&self) -> io::Result<SystemTime> {
1109 self.0.accessed().map(FromInner::from_inner)
1112 /// Returns the creation time listed in this metadata.
1114 /// The returned value corresponds to the `btime` field of `statx` on
1115 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1116 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1120 /// This field may not be available on all platforms, and will return an
1121 /// `Err` on platforms or filesystems where it is not available.
1128 /// fn main() -> std::io::Result<()> {
1129 /// let metadata = fs::metadata("foo.txt")?;
1131 /// if let Ok(time) = metadata.created() {
1132 /// println!("{:?}", time);
1134 /// println!("Not supported on this platform or filesystem");
1139 #[stable(feature = "fs_time", since = "1.10.0")]
1140 pub fn created(&self) -> io::Result<SystemTime> {
1141 self.0.created().map(FromInner::from_inner)
1145 #[stable(feature = "std_debug", since = "1.16.0")]
1146 impl fmt::Debug for Metadata {
1147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1148 f.debug_struct("Metadata")
1149 .field("file_type", &self.file_type())
1150 .field("is_dir", &self.is_dir())
1151 .field("is_file", &self.is_file())
1152 .field("permissions", &self.permissions())
1153 .field("modified", &self.modified())
1154 .field("accessed", &self.accessed())
1155 .field("created", &self.created())
1160 impl AsInner<fs_imp::FileAttr> for Metadata {
1161 fn as_inner(&self) -> &fs_imp::FileAttr {
1166 impl FromInner<fs_imp::FileAttr> for Metadata {
1167 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1173 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1178 /// use std::fs::File;
1180 /// fn main() -> std::io::Result<()> {
1181 /// let mut f = File::create("foo.txt")?;
1182 /// let metadata = f.metadata()?;
1184 /// assert_eq!(false, metadata.permissions().readonly());
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn readonly(&self) -> bool {
1193 /// Modifies the readonly flag for this set of permissions. If the
1194 /// `readonly` argument is `true`, using the resulting `Permission` will
1195 /// update file permissions to forbid writing. Conversely, if it's `false`,
1196 /// using the resulting `Permission` will update file permissions to allow
1199 /// This operation does **not** modify the filesystem. To modify the
1200 /// filesystem use the [`set_permissions`] function.
1205 /// use std::fs::File;
1207 /// fn main() -> std::io::Result<()> {
1208 /// let f = File::create("foo.txt")?;
1209 /// let metadata = f.metadata()?;
1210 /// let mut permissions = metadata.permissions();
1212 /// permissions.set_readonly(true);
1214 /// // filesystem doesn't change
1215 /// assert_eq!(false, metadata.permissions().readonly());
1217 /// // just this particular `permissions`.
1218 /// assert_eq!(true, permissions.readonly());
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn set_readonly(&mut self, readonly: bool) {
1224 self.0.set_readonly(readonly)
1229 /// Tests whether this file type represents a directory. The
1230 /// result is mutually exclusive to the results of
1231 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1234 /// [`is_file`]: FileType::is_file
1235 /// [`is_symlink`]: FileType::is_symlink
1240 /// fn main() -> std::io::Result<()> {
1243 /// let metadata = fs::metadata("foo.txt")?;
1244 /// let file_type = metadata.file_type();
1246 /// assert_eq!(file_type.is_dir(), false);
1250 #[stable(feature = "file_type", since = "1.1.0")]
1251 pub fn is_dir(&self) -> bool {
1255 /// Tests whether this file type represents a regular file.
1256 /// The result is mutually exclusive to the results of
1257 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1260 /// When the goal is simply to read from (or write to) the source, the most
1261 /// reliable way to test the source can be read (or written to) is to open
1262 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1263 /// a Unix-like system for example. See [`File::open`] or
1264 /// [`OpenOptions::open`] for more information.
1266 /// [`is_dir`]: FileType::is_dir
1267 /// [`is_symlink`]: FileType::is_symlink
1272 /// fn main() -> std::io::Result<()> {
1275 /// let metadata = fs::metadata("foo.txt")?;
1276 /// let file_type = metadata.file_type();
1278 /// assert_eq!(file_type.is_file(), true);
1282 #[stable(feature = "file_type", since = "1.1.0")]
1283 pub fn is_file(&self) -> bool {
1287 /// Tests whether this file type represents a symbolic link.
1288 /// The result is mutually exclusive to the results of
1289 /// [`is_dir`] and [`is_file`]; only zero or one of these
1292 /// The underlying [`Metadata`] struct needs to be retrieved
1293 /// with the [`fs::symlink_metadata`] function and not the
1294 /// [`fs::metadata`] function. The [`fs::metadata`] function
1295 /// follows symbolic links, so [`is_symlink`] would always
1296 /// return `false` for the target file.
1298 /// [`fs::metadata`]: metadata
1299 /// [`fs::symlink_metadata`]: symlink_metadata
1300 /// [`is_dir`]: FileType::is_dir
1301 /// [`is_file`]: FileType::is_file
1302 /// [`is_symlink`]: FileType::is_symlink
1309 /// fn main() -> std::io::Result<()> {
1310 /// let metadata = fs::symlink_metadata("foo.txt")?;
1311 /// let file_type = metadata.file_type();
1313 /// assert_eq!(file_type.is_symlink(), false);
1317 #[stable(feature = "file_type", since = "1.1.0")]
1318 pub fn is_symlink(&self) -> bool {
1323 impl AsInner<fs_imp::FileType> for FileType {
1324 fn as_inner(&self) -> &fs_imp::FileType {
1329 impl FromInner<fs_imp::FilePermissions> for Permissions {
1330 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1335 impl AsInner<fs_imp::FilePermissions> for Permissions {
1336 fn as_inner(&self) -> &fs_imp::FilePermissions {
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl Iterator for ReadDir {
1343 type Item = io::Result<DirEntry>;
1345 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1346 self.0.next().map(|entry| entry.map(DirEntry))
1351 /// Returns the full path to the file that this entry represents.
1353 /// The full path is created by joining the original path to `read_dir`
1354 /// with the filename of this entry.
1361 /// fn main() -> std::io::Result<()> {
1362 /// for entry in fs::read_dir(".")? {
1363 /// let dir = entry?;
1364 /// println!("{:?}", dir.path());
1370 /// This prints output like:
1373 /// "./whatever.txt"
1375 /// "./hello_world.rs"
1378 /// The exact text, of course, depends on what files you have in `.`.
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 pub fn path(&self) -> PathBuf {
1384 /// Returns the metadata for the file that this entry points at.
1386 /// This function will not traverse symlinks if this entry points at a
1387 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1389 /// [`fs::metadata`]: metadata
1390 /// [`fs::File::metadata`]: File::metadata
1392 /// # Platform-specific behavior
1394 /// On Windows this function is cheap to call (no extra system calls
1395 /// needed), but on Unix platforms this function is the equivalent of
1396 /// calling `symlink_metadata` on the path.
1403 /// if let Ok(entries) = fs::read_dir(".") {
1404 /// for entry in entries {
1405 /// if let Ok(entry) = entry {
1406 /// // Here, `entry` is a `DirEntry`.
1407 /// if let Ok(metadata) = entry.metadata() {
1408 /// // Now let's show our entry's permissions!
1409 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1411 /// println!("Couldn't get metadata for {:?}", entry.path());
1417 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1418 pub fn metadata(&self) -> io::Result<Metadata> {
1419 self.0.metadata().map(Metadata)
1422 /// Returns the file type for the file that this entry points at.
1424 /// This function will not traverse symlinks if this entry points at a
1427 /// # Platform-specific behavior
1429 /// On Windows and most Unix platforms this function is free (no extra
1430 /// system calls needed), but some Unix platforms may require the equivalent
1431 /// call to `symlink_metadata` to learn about the target file type.
1438 /// if let Ok(entries) = fs::read_dir(".") {
1439 /// for entry in entries {
1440 /// if let Ok(entry) = entry {
1441 /// // Here, `entry` is a `DirEntry`.
1442 /// if let Ok(file_type) = entry.file_type() {
1443 /// // Now let's show our entry's file type!
1444 /// println!("{:?}: {:?}", entry.path(), file_type);
1446 /// println!("Couldn't get file type for {:?}", entry.path());
1452 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1453 pub fn file_type(&self) -> io::Result<FileType> {
1454 self.0.file_type().map(FileType)
1457 /// Returns the bare file name of this directory entry without any other
1458 /// leading path component.
1465 /// if let Ok(entries) = fs::read_dir(".") {
1466 /// for entry in entries {
1467 /// if let Ok(entry) = entry {
1468 /// // Here, `entry` is a `DirEntry`.
1469 /// println!("{:?}", entry.file_name());
1474 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1475 pub fn file_name(&self) -> OsString {
1480 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1481 impl fmt::Debug for DirEntry {
1482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1483 f.debug_tuple("DirEntry").field(&self.path()).finish()
1487 impl AsInner<fs_imp::DirEntry> for DirEntry {
1488 fn as_inner(&self) -> &fs_imp::DirEntry {
1493 /// Removes a file from the filesystem.
1495 /// Note that there is no
1496 /// guarantee that the file is immediately deleted (e.g., depending on
1497 /// platform, other open file descriptors may prevent immediate removal).
1499 /// # Platform-specific behavior
1501 /// This function currently corresponds to the `unlink` function on Unix
1502 /// and the `DeleteFile` function on Windows.
1503 /// Note that, this [may change in the future][changes].
1505 /// [changes]: ../io/index.html#platform-specific-behavior
1509 /// This function will return an error in the following situations, but is not
1510 /// limited to just these cases:
1512 /// * `path` points to a directory.
1513 /// * The file doesn't exist.
1514 /// * The user lacks permissions to remove the file.
1521 /// fn main() -> std::io::Result<()> {
1522 /// fs::remove_file("a.txt")?;
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1528 fs_imp::unlink(path.as_ref())
1531 /// Given a path, query the file system to get information about a file,
1534 /// This function will traverse symbolic links to query information about the
1535 /// destination file.
1537 /// # Platform-specific behavior
1539 /// This function currently corresponds to the `stat` function on Unix
1540 /// and the `GetFileAttributesEx` function on Windows.
1541 /// Note that, this [may change in the future][changes].
1543 /// [changes]: ../io/index.html#platform-specific-behavior
1547 /// This function will return an error in the following situations, but is not
1548 /// limited to just these cases:
1550 /// * The user lacks permissions to perform `metadata` call on `path`.
1551 /// * `path` does not exist.
1558 /// fn main() -> std::io::Result<()> {
1559 /// let attr = fs::metadata("/some/file/path.txt")?;
1560 /// // inspect attr ...
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1566 fs_imp::stat(path.as_ref()).map(Metadata)
1569 /// Query the metadata about a file without following symlinks.
1571 /// # Platform-specific behavior
1573 /// This function currently corresponds to the `lstat` function on Unix
1574 /// and the `GetFileAttributesEx` function on Windows.
1575 /// Note that, this [may change in the future][changes].
1577 /// [changes]: ../io/index.html#platform-specific-behavior
1581 /// This function will return an error in the following situations, but is not
1582 /// limited to just these cases:
1584 /// * The user lacks permissions to perform `metadata` call on `path`.
1585 /// * `path` does not exist.
1592 /// fn main() -> std::io::Result<()> {
1593 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1594 /// // inspect attr ...
1598 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1599 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1600 fs_imp::lstat(path.as_ref()).map(Metadata)
1603 /// Rename a file or directory to a new name, replacing the original file if
1604 /// `to` already exists.
1606 /// This will not work if the new name is on a different mount point.
1608 /// # Platform-specific behavior
1610 /// This function currently corresponds to the `rename` function on Unix
1611 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1613 /// Because of this, the behavior when both `from` and `to` exist differs. On
1614 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1615 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1616 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1618 /// Note that, this [may change in the future][changes].
1620 /// [changes]: ../io/index.html#platform-specific-behavior
1624 /// This function will return an error in the following situations, but is not
1625 /// limited to just these cases:
1627 /// * `from` does not exist.
1628 /// * The user lacks permissions to view contents.
1629 /// * `from` and `to` are on separate filesystems.
1636 /// fn main() -> std::io::Result<()> {
1637 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1643 fs_imp::rename(from.as_ref(), to.as_ref())
1646 /// Copies the contents of one file to another. This function will also
1647 /// copy the permission bits of the original file to the destination file.
1649 /// This function will **overwrite** the contents of `to`.
1651 /// Note that if `from` and `to` both point to the same file, then the file
1652 /// will likely get truncated by this operation.
1654 /// On success, the total number of bytes copied is returned and it is equal to
1655 /// the length of the `to` file as reported by `metadata`.
1657 /// If you’re wanting to copy the contents of one file to another and you’re
1658 /// working with [`File`]s, see the [`io::copy`] function.
1660 /// # Platform-specific behavior
1662 /// This function currently corresponds to the `open` function in Unix
1663 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1664 /// `O_CLOEXEC` is set for returned file descriptors.
1665 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1666 /// NTFS streams are copied but only the size of the main stream is returned by
1667 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1669 /// Note that, this [may change in the future][changes].
1671 /// [changes]: ../io/index.html#platform-specific-behavior
1675 /// This function will return an error in the following situations, but is not
1676 /// limited to just these cases:
1678 /// * The `from` path is not a file.
1679 /// * The `from` file does not exist.
1680 /// * The current process does not have the permission rights to access
1681 /// `from` or write `to`.
1688 /// fn main() -> std::io::Result<()> {
1689 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1695 fs_imp::copy(from.as_ref(), to.as_ref())
1698 /// Creates a new hard link on the filesystem.
1700 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1701 /// often require these two paths to both be located on the same filesystem.
1703 /// # Platform-specific behavior
1705 /// This function currently corresponds to the `link` function on Unix
1706 /// and the `CreateHardLink` function on Windows.
1707 /// Note that, this [may change in the future][changes].
1709 /// [changes]: ../io/index.html#platform-specific-behavior
1713 /// This function will return an error in the following situations, but is not
1714 /// limited to just these cases:
1716 /// * The `src` path is not a file or doesn't exist.
1723 /// fn main() -> std::io::Result<()> {
1724 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1730 fs_imp::link(src.as_ref(), dst.as_ref())
1733 /// Creates a new symbolic link on the filesystem.
1735 /// The `dst` path will be a symbolic link pointing to the `src` path.
1736 /// On Windows, this will be a file symlink, not a directory symlink;
1737 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1738 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1739 /// used instead to make the intent explicit.
1741 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1742 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1743 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1750 /// fn main() -> std::io::Result<()> {
1751 /// fs::soft_link("a.txt", "b.txt")?;
1755 #[stable(feature = "rust1", since = "1.0.0")]
1758 reason = "replaced with std::os::unix::fs::symlink and \
1759 std::os::windows::fs::{symlink_file, symlink_dir}"
1761 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1762 fs_imp::symlink(src.as_ref(), dst.as_ref())
1765 /// Reads a symbolic link, returning the file that the link points to.
1767 /// # Platform-specific behavior
1769 /// This function currently corresponds to the `readlink` function on Unix
1770 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1771 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1772 /// Note that, this [may change in the future][changes].
1774 /// [changes]: ../io/index.html#platform-specific-behavior
1778 /// This function will return an error in the following situations, but is not
1779 /// limited to just these cases:
1781 /// * `path` is not a symbolic link.
1782 /// * `path` does not exist.
1789 /// fn main() -> std::io::Result<()> {
1790 /// let path = fs::read_link("a.txt")?;
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1796 fs_imp::readlink(path.as_ref())
1799 /// Returns the canonical, absolute form of a path with all intermediate
1800 /// components normalized and symbolic links resolved.
1802 /// # Platform-specific behavior
1804 /// This function currently corresponds to the `realpath` function on Unix
1805 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1806 /// Note that, this [may change in the future][changes].
1808 /// On Windows, this converts the path to use [extended length path][path]
1809 /// syntax, which allows your program to use longer path names, but means you
1810 /// can only join backslash-delimited paths to it, and it may be incompatible
1811 /// with other applications (if passed to the application on the command-line,
1812 /// or written to a file another application may read).
1814 /// [changes]: ../io/index.html#platform-specific-behavior
1815 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1819 /// This function will return an error in the following situations, but is not
1820 /// limited to just these cases:
1822 /// * `path` does not exist.
1823 /// * A non-final component in path is not a directory.
1830 /// fn main() -> std::io::Result<()> {
1831 /// let path = fs::canonicalize("../a/../foo.txt")?;
1835 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1836 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1837 fs_imp::canonicalize(path.as_ref())
1840 /// Creates a new, empty directory at the provided path
1842 /// # Platform-specific behavior
1844 /// This function currently corresponds to the `mkdir` function on Unix
1845 /// and the `CreateDirectory` function on Windows.
1846 /// Note that, this [may change in the future][changes].
1848 /// [changes]: ../io/index.html#platform-specific-behavior
1850 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1851 /// return an error. To create a directory and all its missing parents at the
1852 /// same time, use the [`create_dir_all`] function.
1856 /// This function will return an error in the following situations, but is not
1857 /// limited to just these cases:
1859 /// * User lacks permissions to create directory at `path`.
1860 /// * A parent of the given path doesn't exist. (To create a directory and all
1861 /// its missing parents at the same time, use the [`create_dir_all`]
1863 /// * `path` already exists.
1870 /// fn main() -> std::io::Result<()> {
1871 /// fs::create_dir("/some/dir")?;
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1877 DirBuilder::new().create(path.as_ref())
1880 /// Recursively create a directory and all of its parent components if they
1883 /// # Platform-specific behavior
1885 /// This function currently corresponds to the `mkdir` function on Unix
1886 /// and the `CreateDirectory` function on Windows.
1887 /// Note that, this [may change in the future][changes].
1889 /// [changes]: ../io/index.html#platform-specific-behavior
1893 /// This function will return an error in the following situations, but is not
1894 /// limited to just these cases:
1896 /// * If any directory in the path specified by `path`
1897 /// does not already exist and it could not be created otherwise. The specific
1898 /// error conditions for when a directory is being created (after it is
1899 /// determined to not exist) are outlined by [`fs::create_dir`].
1901 /// Notable exception is made for situations where any of the directories
1902 /// specified in the `path` could not be created as it was being created concurrently.
1903 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1904 /// concurrently from multiple threads or processes is guaranteed not to fail
1905 /// due to a race condition with itself.
1907 /// [`fs::create_dir`]: create_dir
1914 /// fn main() -> std::io::Result<()> {
1915 /// fs::create_dir_all("/some/dir")?;
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1921 DirBuilder::new().recursive(true).create(path.as_ref())
1924 /// Removes an existing, empty directory.
1926 /// # Platform-specific behavior
1928 /// This function currently corresponds to the `rmdir` function on Unix
1929 /// and the `RemoveDirectory` function on Windows.
1930 /// Note that, this [may change in the future][changes].
1932 /// [changes]: ../io/index.html#platform-specific-behavior
1936 /// This function will return an error in the following situations, but is not
1937 /// limited to just these cases:
1939 /// * The user lacks permissions to remove the directory at the provided `path`.
1940 /// * The directory isn't empty.
1947 /// fn main() -> std::io::Result<()> {
1948 /// fs::remove_dir("/some/dir")?;
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1954 fs_imp::rmdir(path.as_ref())
1957 /// Removes a directory at this path, after removing all its contents. Use
1960 /// This function does **not** follow symbolic links and it will simply remove the
1961 /// symbolic link itself.
1963 /// # Platform-specific behavior
1965 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1966 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1968 /// Note that, this [may change in the future][changes].
1970 /// [changes]: ../io/index.html#platform-specific-behavior
1974 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1976 /// [`fs::remove_file`]: remove_file
1977 /// [`fs::remove_dir`]: remove_dir
1984 /// fn main() -> std::io::Result<()> {
1985 /// fs::remove_dir_all("/some/dir")?;
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1991 fs_imp::remove_dir_all(path.as_ref())
1994 /// Returns an iterator over the entries within a directory.
1996 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1997 /// New errors may be encountered after an iterator is initially constructed.
1999 /// # Platform-specific behavior
2001 /// This function currently corresponds to the `opendir` function on Unix
2002 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2003 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2004 /// Note that, this [may change in the future][changes].
2006 /// [changes]: ../io/index.html#platform-specific-behavior
2008 /// The order in which this iterator returns entries is platform and filesystem
2013 /// This function will return an error in the following situations, but is not
2014 /// limited to just these cases:
2016 /// * The provided `path` doesn't exist.
2017 /// * The process lacks permissions to view the contents.
2018 /// * The `path` points at a non-directory file.
2024 /// use std::fs::{self, DirEntry};
2025 /// use std::path::Path;
2027 /// // one possible implementation of walking a directory only visiting files
2028 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2029 /// if dir.is_dir() {
2030 /// for entry in fs::read_dir(dir)? {
2031 /// let entry = entry?;
2032 /// let path = entry.path();
2033 /// if path.is_dir() {
2034 /// visit_dirs(&path, cb)?;
2045 /// use std::{fs, io};
2047 /// fn main() -> io::Result<()> {
2048 /// let mut entries = fs::read_dir(".")?
2049 /// .map(|res| res.map(|e| e.path()))
2050 /// .collect::<Result<Vec<_>, io::Error>>()?;
2052 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2053 /// // ordering is required the entries should be explicitly sorted.
2057 /// // The entries have now been sorted by their path.
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2064 fs_imp::readdir(path.as_ref()).map(ReadDir)
2067 /// Changes the permissions found on a file or a directory.
2069 /// # Platform-specific behavior
2071 /// This function currently corresponds to the `chmod` function on Unix
2072 /// and the `SetFileAttributes` function on Windows.
2073 /// Note that, this [may change in the future][changes].
2075 /// [changes]: ../io/index.html#platform-specific-behavior
2079 /// This function will return an error in the following situations, but is not
2080 /// limited to just these cases:
2082 /// * `path` does not exist.
2083 /// * The user lacks the permission to change attributes of the file.
2090 /// fn main() -> std::io::Result<()> {
2091 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2092 /// perms.set_readonly(true);
2093 /// fs::set_permissions("foo.txt", perms)?;
2097 #[stable(feature = "set_permissions", since = "1.1.0")]
2098 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2099 fs_imp::set_perm(path.as_ref(), perm.0)
2103 /// Creates a new set of options with default mode/security settings for all
2104 /// platforms and also non-recursive.
2109 /// use std::fs::DirBuilder;
2111 /// let builder = DirBuilder::new();
2113 #[stable(feature = "dir_builder", since = "1.6.0")]
2114 pub fn new() -> DirBuilder {
2115 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2118 /// Indicates that directories should be created recursively, creating all
2119 /// parent directories. Parents that do not exist are created with the same
2120 /// security and permissions settings.
2122 /// This option defaults to `false`.
2127 /// use std::fs::DirBuilder;
2129 /// let mut builder = DirBuilder::new();
2130 /// builder.recursive(true);
2132 #[stable(feature = "dir_builder", since = "1.6.0")]
2133 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2134 self.recursive = recursive;
2138 /// Creates the specified directory with the options configured in this
2141 /// It is considered an error if the directory already exists unless
2142 /// recursive mode is enabled.
2147 /// use std::fs::{self, DirBuilder};
2149 /// let path = "/tmp/foo/bar/baz";
2150 /// DirBuilder::new()
2151 /// .recursive(true)
2152 /// .create(path).unwrap();
2154 /// assert!(fs::metadata(path).unwrap().is_dir());
2156 #[stable(feature = "dir_builder", since = "1.6.0")]
2157 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2158 self._create(path.as_ref())
2161 fn _create(&self, path: &Path) -> io::Result<()> {
2162 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2165 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2166 if path == Path::new("") {
2170 match self.inner.mkdir(path) {
2171 Ok(()) => return Ok(()),
2172 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2173 Err(_) if path.is_dir() => return Ok(()),
2174 Err(e) => return Err(e),
2176 match path.parent() {
2177 Some(p) => self.create_dir_all(p)?,
2179 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2182 match self.inner.mkdir(path) {
2184 Err(_) if path.is_dir() => Ok(()),
2190 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2191 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2196 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2198 use crate::io::prelude::*;
2200 use crate::fs::{self, File, OpenOptions};
2201 use crate::io::{ErrorKind, SeekFrom};
2202 use crate::path::Path;
2204 use crate::sys_common::io::test::{tmpdir, TempDir};
2207 use rand::{rngs::StdRng, RngCore, SeedableRng};
2210 use crate::os::unix::fs::symlink as symlink_dir;
2212 use crate::os::unix::fs::symlink as symlink_file;
2214 use crate::os::unix::fs::symlink as symlink_junction;
2216 use crate::os::windows::fs::{symlink_dir, symlink_file};
2218 use crate::sys::fs::symlink_junction;
2220 macro_rules! check {
2224 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2230 macro_rules! error {
2231 ($e:expr, $s:expr) => {
2233 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2234 Err(ref err) => assert!(
2235 err.raw_os_error() == Some($s),
2236 format!("`{}` did not have a code of `{}`", err, $s)
2243 macro_rules! error {
2244 ($e:expr, $s:expr) => {
2245 error_contains!($e, $s)
2249 macro_rules! error_contains {
2250 ($e:expr, $s:expr) => {
2252 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2253 Err(ref err) => assert!(
2254 err.to_string().contains($s),
2255 format!("`{}` did not contain `{}`", err, $s)
2261 // Several test fail on windows if the user does not have permission to
2262 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2263 // disabling these test on Windows, use this function to test whether we
2264 // have permission, and return otherwise. This way, we still don't run these
2265 // tests most of the time, but at least we do if the user has the right
2267 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2271 let link = tmpdir.join("some_hopefully_unique_link_name");
2273 match symlink_file(r"nonexisting_target", link) {
2275 // ERROR_PRIVILEGE_NOT_HELD = 1314
2276 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2282 fn file_test_io_smoke_test() {
2283 let message = "it's alright. have a good time";
2284 let tmpdir = tmpdir();
2285 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2287 let mut write_stream = check!(File::create(filename));
2288 check!(write_stream.write(message.as_bytes()));
2291 let mut read_stream = check!(File::open(filename));
2292 let mut read_buf = [0; 1028];
2293 let read_str = match check!(read_stream.read(&mut read_buf)) {
2294 0 => panic!("shouldn't happen"),
2295 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2297 assert_eq!(read_str, message);
2299 check!(fs::remove_file(filename));
2303 fn invalid_path_raises() {
2304 let tmpdir = tmpdir();
2305 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2306 let result = File::open(filename);
2308 #[cfg(all(unix, not(target_os = "vxworks")))]
2309 error!(result, "No such file or directory");
2310 #[cfg(target_os = "vxworks")]
2311 error!(result, "no such file or directory");
2313 error!(result, 2); // ERROR_FILE_NOT_FOUND
2317 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2318 let tmpdir = tmpdir();
2319 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2321 let result = fs::remove_file(filename);
2323 #[cfg(all(unix, not(target_os = "vxworks")))]
2324 error!(result, "No such file or directory");
2325 #[cfg(target_os = "vxworks")]
2326 error!(result, "no such file or directory");
2328 error!(result, 2); // ERROR_FILE_NOT_FOUND
2332 fn file_test_io_non_positional_read() {
2333 let message: &str = "ten-four";
2334 let mut read_mem = [0; 8];
2335 let tmpdir = tmpdir();
2336 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2338 let mut rw_stream = check!(File::create(filename));
2339 check!(rw_stream.write(message.as_bytes()));
2342 let mut read_stream = check!(File::open(filename));
2344 let read_buf = &mut read_mem[0..4];
2345 check!(read_stream.read(read_buf));
2348 let read_buf = &mut read_mem[4..8];
2349 check!(read_stream.read(read_buf));
2352 check!(fs::remove_file(filename));
2353 let read_str = str::from_utf8(&read_mem).unwrap();
2354 assert_eq!(read_str, message);
2358 fn file_test_io_seek_and_tell_smoke_test() {
2359 let message = "ten-four";
2360 let mut read_mem = [0; 4];
2361 let set_cursor = 4 as u64;
2362 let tell_pos_pre_read;
2363 let tell_pos_post_read;
2364 let tmpdir = tmpdir();
2365 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2367 let mut rw_stream = check!(File::create(filename));
2368 check!(rw_stream.write(message.as_bytes()));
2371 let mut read_stream = check!(File::open(filename));
2372 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2373 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2374 check!(read_stream.read(&mut read_mem));
2375 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2377 check!(fs::remove_file(filename));
2378 let read_str = str::from_utf8(&read_mem).unwrap();
2379 assert_eq!(read_str, &message[4..8]);
2380 assert_eq!(tell_pos_pre_read, set_cursor);
2381 assert_eq!(tell_pos_post_read, message.len() as u64);
2385 fn file_test_io_seek_and_write() {
2386 let initial_msg = "food-is-yummy";
2387 let overwrite_msg = "-the-bar!!";
2388 let final_msg = "foo-the-bar!!";
2390 let mut read_mem = [0; 13];
2391 let tmpdir = tmpdir();
2392 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2394 let mut rw_stream = check!(File::create(filename));
2395 check!(rw_stream.write(initial_msg.as_bytes()));
2396 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2397 check!(rw_stream.write(overwrite_msg.as_bytes()));
2400 let mut read_stream = check!(File::open(filename));
2401 check!(read_stream.read(&mut read_mem));
2403 check!(fs::remove_file(filename));
2404 let read_str = str::from_utf8(&read_mem).unwrap();
2405 assert!(read_str == final_msg);
2409 fn file_test_io_seek_shakedown() {
2411 let initial_msg = "qwer-asdf-zxcv";
2412 let chunk_one: &str = "qwer";
2413 let chunk_two: &str = "asdf";
2414 let chunk_three: &str = "zxcv";
2415 let mut read_mem = [0; 4];
2416 let tmpdir = tmpdir();
2417 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2419 let mut rw_stream = check!(File::create(filename));
2420 check!(rw_stream.write(initial_msg.as_bytes()));
2423 let mut read_stream = check!(File::open(filename));
2425 check!(read_stream.seek(SeekFrom::End(-4)));
2426 check!(read_stream.read(&mut read_mem));
2427 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2429 check!(read_stream.seek(SeekFrom::Current(-9)));
2430 check!(read_stream.read(&mut read_mem));
2431 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2433 check!(read_stream.seek(SeekFrom::Start(0)));
2434 check!(read_stream.read(&mut read_mem));
2435 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2437 check!(fs::remove_file(filename));
2441 fn file_test_io_eof() {
2442 let tmpdir = tmpdir();
2443 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2444 let mut buf = [0; 256];
2446 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2447 let mut rw = check!(oo.open(&filename));
2448 assert_eq!(check!(rw.read(&mut buf)), 0);
2449 assert_eq!(check!(rw.read(&mut buf)), 0);
2451 check!(fs::remove_file(&filename));
2456 fn file_test_io_read_write_at() {
2457 use crate::os::unix::fs::FileExt;
2459 let tmpdir = tmpdir();
2460 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2461 let mut buf = [0; 256];
2462 let write1 = "asdf";
2463 let write2 = "qwer-";
2464 let write3 = "-zxcv";
2465 let content = "qwer-asdf-zxcv";
2467 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2468 let mut rw = check!(oo.open(&filename));
2469 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2470 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2471 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2472 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2473 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2474 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2475 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2476 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2477 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2478 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2479 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2480 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2481 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2482 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2483 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2484 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2485 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2486 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2489 let mut read = check!(File::open(&filename));
2490 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2491 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2492 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2493 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2494 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2495 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2496 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2497 assert_eq!(check!(read.read(&mut buf)), write3.len());
2498 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2499 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2500 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2501 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2502 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2503 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2504 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2505 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2507 check!(fs::remove_file(&filename));
2512 fn set_get_unix_permissions() {
2513 use crate::os::unix::fs::PermissionsExt;
2515 let tmpdir = tmpdir();
2516 let filename = &tmpdir.join("set_get_unix_permissions");
2517 check!(fs::create_dir(filename));
2520 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2521 let metadata0 = check!(fs::metadata(filename));
2522 assert_eq!(mask & metadata0.permissions().mode(), 0);
2524 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2525 let metadata1 = check!(fs::metadata(filename));
2526 #[cfg(all(unix, not(target_os = "vxworks")))]
2527 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2528 #[cfg(target_os = "vxworks")]
2529 assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2534 fn file_test_io_seek_read_write() {
2535 use crate::os::windows::fs::FileExt;
2537 let tmpdir = tmpdir();
2538 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2539 let mut buf = [0; 256];
2540 let write1 = "asdf";
2541 let write2 = "qwer-";
2542 let write3 = "-zxcv";
2543 let content = "qwer-asdf-zxcv";
2545 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2546 let mut rw = check!(oo.open(&filename));
2547 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2548 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2549 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2550 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2551 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2552 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2553 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2554 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2555 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2556 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2557 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2558 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2559 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2560 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2561 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2562 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2565 let mut read = check!(File::open(&filename));
2566 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2567 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2568 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2569 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2570 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2571 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2572 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2573 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2574 assert_eq!(check!(read.read(&mut buf)), write3.len());
2575 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2576 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2577 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2578 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2579 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2580 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2581 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2583 check!(fs::remove_file(&filename));
2587 fn file_test_stat_is_correct_on_is_file() {
2588 let tmpdir = tmpdir();
2589 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2591 let mut opts = OpenOptions::new();
2592 let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2594 fs.write(msg.as_bytes()).unwrap();
2596 let fstat_res = check!(fs.metadata());
2597 assert!(fstat_res.is_file());
2599 let stat_res_fn = check!(fs::metadata(filename));
2600 assert!(stat_res_fn.is_file());
2601 let stat_res_meth = check!(filename.metadata());
2602 assert!(stat_res_meth.is_file());
2603 check!(fs::remove_file(filename));
2607 fn file_test_stat_is_correct_on_is_dir() {
2608 let tmpdir = tmpdir();
2609 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2610 check!(fs::create_dir(filename));
2611 let stat_res_fn = check!(fs::metadata(filename));
2612 assert!(stat_res_fn.is_dir());
2613 let stat_res_meth = check!(filename.metadata());
2614 assert!(stat_res_meth.is_dir());
2615 check!(fs::remove_dir(filename));
2619 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2620 let tmpdir = tmpdir();
2621 let dir = &tmpdir.join("fileinfo_false_on_dir");
2622 check!(fs::create_dir(dir));
2623 assert!(!dir.is_file());
2624 check!(fs::remove_dir(dir));
2628 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2629 let tmpdir = tmpdir();
2630 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2631 check!(check!(File::create(file)).write(b"foo"));
2632 assert!(file.exists());
2633 check!(fs::remove_file(file));
2634 assert!(!file.exists());
2638 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2639 let tmpdir = tmpdir();
2640 let dir = &tmpdir.join("before_and_after_dir");
2641 assert!(!dir.exists());
2642 check!(fs::create_dir(dir));
2643 assert!(dir.exists());
2644 assert!(dir.is_dir());
2645 check!(fs::remove_dir(dir));
2646 assert!(!dir.exists());
2650 fn file_test_directoryinfo_readdir() {
2651 let tmpdir = tmpdir();
2652 let dir = &tmpdir.join("di_readdir");
2653 check!(fs::create_dir(dir));
2656 let f = dir.join(&format!("{}.txt", n));
2657 let mut w = check!(File::create(&f));
2658 let msg_str = format!("{}{}", prefix, n.to_string());
2659 let msg = msg_str.as_bytes();
2660 check!(w.write(msg));
2662 let files = check!(fs::read_dir(dir));
2663 let mut mem = [0; 4];
2665 let f = f.unwrap().path();
2667 let n = f.file_stem().unwrap();
2668 check!(check!(File::open(&f)).read(&mut mem));
2669 let read_str = str::from_utf8(&mem).unwrap();
2670 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2671 assert_eq!(expected, read_str);
2673 check!(fs::remove_file(&f));
2675 check!(fs::remove_dir(dir));
2679 fn file_create_new_already_exists_error() {
2680 let tmpdir = tmpdir();
2681 let file = &tmpdir.join("file_create_new_error_exists");
2682 check!(fs::File::create(file));
2683 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2684 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2688 fn mkdir_path_already_exists_error() {
2689 let tmpdir = tmpdir();
2690 let dir = &tmpdir.join("mkdir_error_twice");
2691 check!(fs::create_dir(dir));
2692 let e = fs::create_dir(dir).unwrap_err();
2693 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2697 fn recursive_mkdir() {
2698 let tmpdir = tmpdir();
2699 let dir = tmpdir.join("d1/d2");
2700 check!(fs::create_dir_all(&dir));
2701 assert!(dir.is_dir())
2705 fn recursive_mkdir_failure() {
2706 let tmpdir = tmpdir();
2707 let dir = tmpdir.join("d1");
2708 let file = dir.join("f1");
2710 check!(fs::create_dir_all(&dir));
2711 check!(File::create(&file));
2713 let result = fs::create_dir_all(&file);
2715 assert!(result.is_err());
2719 fn concurrent_recursive_mkdir() {
2722 let mut dir = dir.join("a");
2724 dir = dir.join("a");
2726 let mut join = vec![];
2728 let dir = dir.clone();
2729 join.push(thread::spawn(move || {
2730 check!(fs::create_dir_all(&dir));
2734 // No `Display` on result of `join()`
2735 join.drain(..).map(|join| join.join().unwrap()).count();
2740 fn recursive_mkdir_slash() {
2741 check!(fs::create_dir_all(Path::new("/")));
2745 fn recursive_mkdir_dot() {
2746 check!(fs::create_dir_all(Path::new(".")));
2750 fn recursive_mkdir_empty() {
2751 check!(fs::create_dir_all(Path::new("")));
2755 fn recursive_rmdir() {
2756 let tmpdir = tmpdir();
2757 let d1 = tmpdir.join("d1");
2758 let dt = d1.join("t");
2759 let dtt = dt.join("t");
2760 let d2 = tmpdir.join("d2");
2761 let canary = d2.join("do_not_delete");
2762 check!(fs::create_dir_all(&dtt));
2763 check!(fs::create_dir_all(&d2));
2764 check!(check!(File::create(&canary)).write(b"foo"));
2765 check!(symlink_junction(&d2, &dt.join("d2")));
2766 let _ = symlink_file(&canary, &d1.join("canary"));
2767 check!(fs::remove_dir_all(&d1));
2769 assert!(!d1.is_dir());
2770 assert!(canary.exists());
2774 fn recursive_rmdir_of_symlink() {
2775 // test we do not recursively delete a symlink but only dirs.
2776 let tmpdir = tmpdir();
2777 let link = tmpdir.join("d1");
2778 let dir = tmpdir.join("d2");
2779 let canary = dir.join("do_not_delete");
2780 check!(fs::create_dir_all(&dir));
2781 check!(check!(File::create(&canary)).write(b"foo"));
2782 check!(symlink_junction(&dir, &link));
2783 check!(fs::remove_dir_all(&link));
2785 assert!(!link.is_dir());
2786 assert!(canary.exists());
2790 // only Windows makes a distinction between file and directory symlinks.
2792 fn recursive_rmdir_of_file_symlink() {
2793 let tmpdir = tmpdir();
2794 if !got_symlink_permission(&tmpdir) {
2798 let f1 = tmpdir.join("f1");
2799 let f2 = tmpdir.join("f2");
2800 check!(check!(File::create(&f1)).write(b"foo"));
2801 check!(symlink_file(&f1, &f2));
2802 match fs::remove_dir_all(&f2) {
2803 Ok(..) => panic!("wanted a failure"),
2809 fn unicode_path_is_dir() {
2810 assert!(Path::new(".").is_dir());
2811 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2813 let tmpdir = tmpdir();
2815 let mut dirpath = tmpdir.path().to_path_buf();
2816 dirpath.push("test-가一ー你好");
2817 check!(fs::create_dir(&dirpath));
2818 assert!(dirpath.is_dir());
2820 let mut filepath = dirpath;
2821 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2822 check!(File::create(&filepath)); // ignore return; touch only
2823 assert!(!filepath.is_dir());
2824 assert!(filepath.exists());
2828 fn unicode_path_exists() {
2829 assert!(Path::new(".").exists());
2830 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2832 let tmpdir = tmpdir();
2833 let unicode = tmpdir.path();
2834 let unicode = unicode.join("test-각丁ー再见");
2835 check!(fs::create_dir(&unicode));
2836 assert!(unicode.exists());
2837 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2841 fn copy_file_does_not_exist() {
2842 let from = Path::new("test/nonexistent-bogus-path");
2843 let to = Path::new("test/other-bogus-path");
2845 match fs::copy(&from, &to) {
2848 assert!(!from.exists());
2849 assert!(!to.exists());
2855 fn copy_src_does_not_exist() {
2856 let tmpdir = tmpdir();
2857 let from = Path::new("test/nonexistent-bogus-path");
2858 let to = tmpdir.join("out.txt");
2859 check!(check!(File::create(&to)).write(b"hello"));
2860 assert!(fs::copy(&from, &to).is_err());
2861 assert!(!from.exists());
2862 let mut v = Vec::new();
2863 check!(check!(File::open(&to)).read_to_end(&mut v));
2864 assert_eq!(v, b"hello");
2869 let tmpdir = tmpdir();
2870 let input = tmpdir.join("in.txt");
2871 let out = tmpdir.join("out.txt");
2873 check!(check!(File::create(&input)).write(b"hello"));
2874 check!(fs::copy(&input, &out));
2875 let mut v = Vec::new();
2876 check!(check!(File::open(&out)).read_to_end(&mut v));
2877 assert_eq!(v, b"hello");
2879 assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2883 fn copy_file_dst_dir() {
2884 let tmpdir = tmpdir();
2885 let out = tmpdir.join("out");
2887 check!(File::create(&out));
2888 match fs::copy(&*out, tmpdir.path()) {
2895 fn copy_file_dst_exists() {
2896 let tmpdir = tmpdir();
2897 let input = tmpdir.join("in");
2898 let output = tmpdir.join("out");
2900 check!(check!(File::create(&input)).write("foo".as_bytes()));
2901 check!(check!(File::create(&output)).write("bar".as_bytes()));
2902 check!(fs::copy(&input, &output));
2904 let mut v = Vec::new();
2905 check!(check!(File::open(&output)).read_to_end(&mut v));
2906 assert_eq!(v, b"foo".to_vec());
2910 fn copy_file_src_dir() {
2911 let tmpdir = tmpdir();
2912 let out = tmpdir.join("out");
2914 match fs::copy(tmpdir.path(), &out) {
2918 assert!(!out.exists());
2922 fn copy_file_preserves_perm_bits() {
2923 let tmpdir = tmpdir();
2924 let input = tmpdir.join("in.txt");
2925 let out = tmpdir.join("out.txt");
2927 let attr = check!(check!(File::create(&input)).metadata());
2928 let mut p = attr.permissions();
2929 p.set_readonly(true);
2930 check!(fs::set_permissions(&input, p));
2931 check!(fs::copy(&input, &out));
2932 assert!(check!(out.metadata()).permissions().readonly());
2933 check!(fs::set_permissions(&input, attr.permissions()));
2934 check!(fs::set_permissions(&out, attr.permissions()));
2939 fn copy_file_preserves_streams() {
2941 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2942 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2943 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2944 let mut v = Vec::new();
2945 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2946 assert_eq!(v, b"carrot".to_vec());
2950 fn copy_file_returns_metadata_len() {
2952 let in_path = tmp.join("in.txt");
2953 let out_path = tmp.join("out.txt");
2954 check!(check!(File::create(&in_path)).write(b"lettuce"));
2956 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2957 let copied_len = check!(fs::copy(&in_path, &out_path));
2958 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2962 fn copy_file_follows_dst_symlink() {
2964 if !got_symlink_permission(&tmp) {
2968 let in_path = tmp.join("in.txt");
2969 let out_path = tmp.join("out.txt");
2970 let out_path_symlink = tmp.join("out_symlink.txt");
2972 check!(fs::write(&in_path, "foo"));
2973 check!(fs::write(&out_path, "bar"));
2974 check!(symlink_file(&out_path, &out_path_symlink));
2976 check!(fs::copy(&in_path, &out_path_symlink));
2978 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
2979 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
2980 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
2984 fn symlinks_work() {
2985 let tmpdir = tmpdir();
2986 if !got_symlink_permission(&tmpdir) {
2990 let input = tmpdir.join("in.txt");
2991 let out = tmpdir.join("out.txt");
2993 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2994 check!(symlink_file(&input, &out));
2995 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2996 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
2997 let mut v = Vec::new();
2998 check!(check!(File::open(&out)).read_to_end(&mut v));
2999 assert_eq!(v, b"foobar".to_vec());
3003 fn symlink_noexist() {
3004 // Symlinks can point to things that don't exist
3005 let tmpdir = tmpdir();
3006 if !got_symlink_permission(&tmpdir) {
3010 // Use a relative path for testing. Symlinks get normalized by Windows,
3011 // so we may not get the same path back for absolute paths
3012 check!(symlink_file(&"foo", &tmpdir.join("bar")));
3013 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3019 // directory symlink
3021 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3026 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3029 // junction with special permissions
3031 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3035 let tmpdir = tmpdir();
3036 let link = tmpdir.join("link");
3037 if !got_symlink_permission(&tmpdir) {
3040 check!(symlink_file(&"foo", &link));
3041 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3045 fn readlink_not_symlink() {
3046 let tmpdir = tmpdir();
3047 match fs::read_link(tmpdir.path()) {
3048 Ok(..) => panic!("wanted a failure"),
3055 let tmpdir = tmpdir();
3056 let input = tmpdir.join("in.txt");
3057 let out = tmpdir.join("out.txt");
3059 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3060 check!(fs::hard_link(&input, &out));
3061 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3062 assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3063 let mut v = Vec::new();
3064 check!(check!(File::open(&out)).read_to_end(&mut v));
3065 assert_eq!(v, b"foobar".to_vec());
3067 // can't link to yourself
3068 match fs::hard_link(&input, &input) {
3069 Ok(..) => panic!("wanted a failure"),
3072 // can't link to something that doesn't exist
3073 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3074 Ok(..) => panic!("wanted a failure"),
3081 let tmpdir = tmpdir();
3082 let file = tmpdir.join("in.txt");
3084 check!(File::create(&file));
3085 let attr = check!(fs::metadata(&file));
3086 assert!(!attr.permissions().readonly());
3087 let mut p = attr.permissions();
3088 p.set_readonly(true);
3089 check!(fs::set_permissions(&file, p.clone()));
3090 let attr = check!(fs::metadata(&file));
3091 assert!(attr.permissions().readonly());
3093 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3094 Ok(..) => panic!("wanted an error"),
3098 p.set_readonly(false);
3099 check!(fs::set_permissions(&file, p));
3104 let tmpdir = tmpdir();
3105 let path = tmpdir.join("in.txt");
3107 let file = check!(File::create(&path));
3108 let attr = check!(fs::metadata(&path));
3109 assert!(!attr.permissions().readonly());
3110 let mut p = attr.permissions();
3111 p.set_readonly(true);
3112 check!(file.set_permissions(p.clone()));
3113 let attr = check!(fs::metadata(&path));
3114 assert!(attr.permissions().readonly());
3116 p.set_readonly(false);
3117 check!(file.set_permissions(p));
3121 fn sync_doesnt_kill_anything() {
3122 let tmpdir = tmpdir();
3123 let path = tmpdir.join("in.txt");
3125 let mut file = check!(File::create(&path));
3126 check!(file.sync_all());
3127 check!(file.sync_data());
3128 check!(file.write(b"foo"));
3129 check!(file.sync_all());
3130 check!(file.sync_data());
3134 fn truncate_works() {
3135 let tmpdir = tmpdir();
3136 let path = tmpdir.join("in.txt");
3138 let mut file = check!(File::create(&path));
3139 check!(file.write(b"foo"));
3140 check!(file.sync_all());
3142 // Do some simple things with truncation
3143 assert_eq!(check!(file.metadata()).len(), 3);
3144 check!(file.set_len(10));
3145 assert_eq!(check!(file.metadata()).len(), 10);
3146 check!(file.write(b"bar"));
3147 check!(file.sync_all());
3148 assert_eq!(check!(file.metadata()).len(), 10);
3150 let mut v = Vec::new();
3151 check!(check!(File::open(&path)).read_to_end(&mut v));
3152 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3154 // Truncate to a smaller length, don't seek, and then write something.
3155 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3156 // past the end of the file).
3157 check!(file.set_len(2));
3158 assert_eq!(check!(file.metadata()).len(), 2);
3159 check!(file.write(b"wut"));
3160 check!(file.sync_all());
3161 assert_eq!(check!(file.metadata()).len(), 9);
3162 let mut v = Vec::new();
3163 check!(check!(File::open(&path)).read_to_end(&mut v));
3164 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3169 use crate::fs::OpenOptions as OO;
3170 fn c<T: Clone>(t: &T) -> T {
3174 let tmpdir = tmpdir();
3176 let mut r = OO::new();
3178 let mut w = OO::new();
3180 let mut rw = OO::new();
3181 rw.read(true).write(true);
3182 let mut a = OO::new();
3184 let mut ra = OO::new();
3185 ra.read(true).append(true);
3188 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3189 #[cfg(all(unix, not(target_os = "vxworks")))]
3190 let invalid_options = "Invalid argument";
3191 #[cfg(target_os = "vxworks")]
3192 let invalid_options = "invalid argument";
3194 // Test various combinations of creation modes and access modes.
3197 // creation mode | read | write | read-write | append | read-append |
3198 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3199 // not set (open existing) | X | X | X | X | X |
3200 // create | | X | X | X | X |
3201 // truncate | | X | X | | |
3202 // create and truncate | | X | X | | |
3203 // create_new | | X | X | X | X |
3205 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3208 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3209 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3210 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3211 check!(c(&w).create(true).open(&tmpdir.join("a")));
3212 check!(c(&w).open(&tmpdir.join("a")));
3215 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3216 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3217 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3218 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3219 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3222 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3223 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3224 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3225 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3226 check!(c(&rw).open(&tmpdir.join("c")));
3229 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3230 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3231 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3232 check!(c(&a).create(true).open(&tmpdir.join("d")));
3233 check!(c(&a).open(&tmpdir.join("d")));
3236 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3237 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3238 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3239 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3240 check!(c(&ra).open(&tmpdir.join("e")));
3242 // Test opening a file without setting an access mode
3243 let mut blank = OO::new();
3244 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3247 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3249 // Test write fails for read-only
3250 check!(r.open(&tmpdir.join("h")));
3252 let mut f = check!(r.open(&tmpdir.join("h")));
3253 assert!(f.write("wut".as_bytes()).is_err());
3256 // Test write overwrites
3258 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3259 check!(f.write("baz".as_bytes()));
3262 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3263 let mut b = vec![0; 6];
3264 check!(f.read(&mut b));
3265 assert_eq!(b, "bazbar".as_bytes());
3268 // Test truncate works
3270 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3271 check!(f.write("foo".as_bytes()));
3273 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3275 // Test append works
3276 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3278 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3279 check!(f.write("bar".as_bytes()));
3281 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3283 // Test .append(true) equals .write(true).append(true)
3285 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3286 check!(f.write("baz".as_bytes()));
3288 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3292 fn _assert_send_sync() {
3293 fn _assert_send_sync<T: Send + Sync>() {}
3294 _assert_send_sync::<OpenOptions>();
3299 let mut bytes = [0; 1024];
3300 StdRng::from_entropy().fill_bytes(&mut bytes);
3302 let tmpdir = tmpdir();
3304 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3305 let mut v = Vec::new();
3306 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3307 assert!(v == &bytes[..]);
3311 fn write_then_read() {
3312 let mut bytes = [0; 1024];
3313 StdRng::from_entropy().fill_bytes(&mut bytes);
3315 let tmpdir = tmpdir();
3317 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3318 let v = check!(fs::read(&tmpdir.join("test")));
3319 assert!(v == &bytes[..]);
3321 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3323 fs::read_to_string(&tmpdir.join("not-utf8")),
3324 "stream did not contain valid UTF-8"
3328 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3329 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3330 assert_eq!(string, s);
3334 fn file_try_clone() {
3335 let tmpdir = tmpdir();
3337 let mut f1 = check!(
3338 OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3340 let mut f2 = check!(f1.try_clone());
3342 check!(f1.write_all(b"hello world"));
3343 check!(f1.seek(SeekFrom::Start(2)));
3345 let mut buf = vec![];
3346 check!(f2.read_to_end(&mut buf));
3347 assert_eq!(buf, b"llo world");
3350 check!(f1.write_all(b"!"));
3354 #[cfg(not(windows))]
3355 fn unlink_readonly() {
3356 let tmpdir = tmpdir();
3357 let path = tmpdir.join("file");
3358 check!(File::create(&path));
3359 let mut perm = check!(fs::metadata(&path)).permissions();
3360 perm.set_readonly(true);
3361 check!(fs::set_permissions(&path, perm));
3362 check!(fs::remove_file(&path));
3366 fn mkdir_trailing_slash() {
3367 let tmpdir = tmpdir();
3368 let path = tmpdir.join("file");
3369 check!(fs::create_dir_all(&path.join("a/")));
3373 fn canonicalize_works_simple() {
3374 let tmpdir = tmpdir();
3375 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3376 let file = tmpdir.join("test");
3377 File::create(&file).unwrap();
3378 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3382 fn realpath_works() {
3383 let tmpdir = tmpdir();
3384 if !got_symlink_permission(&tmpdir) {
3388 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3389 let file = tmpdir.join("test");
3390 let dir = tmpdir.join("test2");
3391 let link = dir.join("link");
3392 let linkdir = tmpdir.join("test3");
3394 File::create(&file).unwrap();
3395 fs::create_dir(&dir).unwrap();
3396 symlink_file(&file, &link).unwrap();
3397 symlink_dir(&dir, &linkdir).unwrap();
3399 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3401 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3402 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3403 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3404 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3405 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3409 fn realpath_works_tricky() {
3410 let tmpdir = tmpdir();
3411 if !got_symlink_permission(&tmpdir) {
3415 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3416 let a = tmpdir.join("a");
3417 let b = a.join("b");
3418 let c = b.join("c");
3419 let d = a.join("d");
3420 let e = d.join("e");
3421 let f = a.join("f");
3423 fs::create_dir_all(&b).unwrap();
3424 fs::create_dir_all(&d).unwrap();
3425 File::create(&f).unwrap();
3426 if cfg!(not(windows)) {
3427 symlink_file("../d/e", &c).unwrap();
3428 symlink_file("../f", &e).unwrap();
3431 symlink_file(r"..\d\e", &c).unwrap();
3432 symlink_file(r"..\f", &e).unwrap();
3435 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3436 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3440 fn dir_entry_methods() {
3441 let tmpdir = tmpdir();
3443 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3444 File::create(&tmpdir.join("b")).unwrap();
3446 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3447 let fname = file.file_name();
3448 match fname.to_str() {
3450 assert!(file.file_type().unwrap().is_dir());
3451 assert!(file.metadata().unwrap().is_dir());
3454 assert!(file.file_type().unwrap().is_file());
3455 assert!(file.metadata().unwrap().is_file());
3457 f => panic!("unknown file name: {:?}", f),
3463 fn dir_entry_debug() {
3464 let tmpdir = tmpdir();
3465 File::create(&tmpdir.join("b")).unwrap();
3466 let mut read_dir = tmpdir.path().read_dir().unwrap();
3467 let dir_entry = read_dir.next().unwrap().unwrap();
3468 let actual = format!("{:?}", dir_entry);
3469 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3470 assert_eq!(actual, expected);
3474 fn read_dir_not_found() {
3475 let res = fs::read_dir("/path/that/does/not/exist");
3476 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3480 fn create_dir_all_with_junctions() {
3481 let tmpdir = tmpdir();
3482 let target = tmpdir.join("target");
3484 let junction = tmpdir.join("junction");
3485 let b = junction.join("a/b");
3487 let link = tmpdir.join("link");
3488 let d = link.join("c/d");
3490 fs::create_dir(&target).unwrap();
3492 check!(symlink_junction(&target, &junction));
3493 check!(fs::create_dir_all(&b));
3494 // the junction itself is not a directory, but `is_dir()` on a Path
3496 assert!(junction.is_dir());
3497 assert!(b.exists());
3499 if !got_symlink_permission(&tmpdir) {
3502 check!(symlink_dir(&target, &link));
3503 check!(fs::create_dir_all(&d));
3504 assert!(link.is_dir());
3505 assert!(d.exists());
3509 fn metadata_access_times() {
3510 let tmpdir = tmpdir();
3512 let b = tmpdir.join("b");
3513 File::create(&b).unwrap();
3515 let a = check!(fs::metadata(&tmpdir.path()));
3516 let b = check!(fs::metadata(&b));
3518 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3519 assert_eq!(check!(a.modified()), check!(a.modified()));
3520 assert_eq!(check!(b.accessed()), check!(b.modified()));
3522 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3523 check!(a.created());
3524 check!(b.created());
3527 if cfg!(target_os = "linux") {
3528 // Not always available
3529 match (a.created(), b.created()) {
3530 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3532 if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3534 "creation time must be always supported or not supported: {:?} {:?}",