1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Filesystem manipulation operations.
13 //! This module contains basic methods to manipulate the contents of the local
14 //! filesystem. All methods in this module represent cross-platform filesystem
15 //! operations. Extra platform-specific functionality can be found in the
16 //! extension traits of `std::os::$platform`.
18 #![stable(feature = "rust1", since = "1.0.0")]
22 use io::{self, SeekFrom, Seek, Read, Initializer, Write};
23 use path::{Path, PathBuf};
24 use sys::fs as fs_imp;
25 use sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
28 /// A reference to an open file on the filesystem.
30 /// An instance of a `File` can be read and/or written depending on what options
31 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
32 /// that the file contains internally.
34 /// Files are automatically closed when they go out of scope.
38 /// Create a new file and write bytes to it:
41 /// use std::fs::File;
42 /// use std::io::prelude::*;
44 /// # fn foo() -> std::io::Result<()> {
45 /// let mut file = File::create("foo.txt")?;
46 /// file.write_all(b"Hello, world!")?;
51 /// Read the contents of a file into a [`String`]:
54 /// use std::fs::File;
55 /// use std::io::prelude::*;
57 /// # fn foo() -> std::io::Result<()> {
58 /// let mut file = File::open("foo.txt")?;
59 /// let mut contents = String::new();
60 /// file.read_to_string(&mut contents)?;
61 /// assert_eq!(contents, "Hello, world!");
66 /// It can be more efficient to read the contents of a file with a buffered
67 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
70 /// use std::fs::File;
71 /// use std::io::BufReader;
72 /// use std::io::prelude::*;
74 /// # fn foo() -> std::io::Result<()> {
75 /// let file = File::open("foo.txt")?;
76 /// let mut buf_reader = BufReader::new(file);
77 /// let mut contents = String::new();
78 /// buf_reader.read_to_string(&mut contents)?;
79 /// assert_eq!(contents, "Hello, world!");
84 /// [`Seek`]: ../io/trait.Seek.html
85 /// [`String`]: ../string/struct.String.html
86 /// [`Read`]: ../io/trait.Read.html
87 /// [`BufReader<R>`]: ../io/struct.BufReader.html
88 #[stable(feature = "rust1", since = "1.0.0")]
93 /// Metadata information about a file.
95 /// This structure is returned from the [`metadata`] or
96 /// [`symlink_metadata`] function or method and represents known
97 /// metadata about a file such as its permissions, size, modification
100 /// [`metadata`]: fn.metadata.html
101 /// [`symlink_metadata`]: fn.symlink_metadata.html
102 #[stable(feature = "rust1", since = "1.0.0")]
104 pub struct Metadata(fs_imp::FileAttr);
106 /// Iterator over the entries in a directory.
108 /// This iterator is returned from the [`read_dir`] function of this module and
109 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
110 /// information like the entry's path and possibly other metadata can be
115 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
116 /// IO error during iteration.
118 /// [`read_dir`]: fn.read_dir.html
119 /// [`DirEntry`]: struct.DirEntry.html
120 /// [`io::Result`]: ../io/type.Result.html
121 /// [`Err`]: ../result/enum.Result.html#variant.Err
122 #[stable(feature = "rust1", since = "1.0.0")]
124 pub struct ReadDir(fs_imp::ReadDir);
126 /// Entries returned by the [`ReadDir`] iterator.
128 /// [`ReadDir`]: struct.ReadDir.html
130 /// An instance of `DirEntry` represents an entry inside of a directory on the
131 /// filesystem. Each entry can be inspected via methods to learn about the full
132 /// path or possibly other metadata through per-platform extension traits.
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub struct DirEntry(fs_imp::DirEntry);
136 /// Options and flags which can be used to configure how a file is opened.
138 /// This builder exposes the ability to configure how a [`File`] is opened and
139 /// what operations are permitted on the open file. The [`File::open`] and
140 /// [`File::create`] methods are aliases for commonly used options using this
143 /// [`File`]: struct.File.html
144 /// [`File::open`]: struct.File.html#method.open
145 /// [`File::create`]: struct.File.html#method.create
147 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
148 /// then chain calls to methods to set each option, then call [`open`],
149 /// passing the path of the file you're trying to open. This will give you a
150 /// [`io::Result`][result] with a [`File`][file] inside that you can further
153 /// [`new`]: struct.OpenOptions.html#method.new
154 /// [`open`]: struct.OpenOptions.html#method.open
155 /// [result]: ../io/type.Result.html
156 /// [file]: struct.File.html
160 /// Opening a file to read:
163 /// use std::fs::OpenOptions;
165 /// let file = OpenOptions::new().read(true).open("foo.txt");
168 /// Opening a file for both reading and writing, as well as creating it if it
172 /// use std::fs::OpenOptions;
174 /// let file = OpenOptions::new()
178 /// .open("foo.txt");
180 #[derive(Clone, Debug)]
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub struct OpenOptions(fs_imp::OpenOptions);
184 /// Representation of the various permissions on a file.
186 /// This module only currently provides one bit of information, [`readonly`],
187 /// which is exposed on all currently supported platforms. Unix-specific
188 /// functionality, such as mode bits, is available through the
189 /// `os::unix::PermissionsExt` trait.
191 /// [`readonly`]: struct.Permissions.html#method.readonly
192 #[derive(Clone, PartialEq, Eq, Debug)]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub struct Permissions(fs_imp::FilePermissions);
196 /// A structure representing a type of file with accessors for each file type.
197 /// It is returned by [`Metadata::file_type`] method.
199 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
200 #[stable(feature = "file_type", since = "1.1.0")]
201 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
202 pub struct FileType(fs_imp::FileType);
204 /// A builder used to create directories in various manners.
206 /// This builder also supports platform-specific options.
207 #[stable(feature = "dir_builder", since = "1.6.0")]
209 pub struct DirBuilder {
210 inner: fs_imp::DirBuilder,
214 /// How large a buffer to pre-allocate before reading the entire file.
215 fn initial_buffer_size(file: &File) -> usize {
216 // Allocate one extra byte so the buffer doesn't need to grow before the
217 // final `read` call at the end of the file. Don't worry about `usize`
218 // overflow because reading will fail regardless in that case.
219 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
222 /// Read the entire contents of a file into a bytes vector.
224 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
225 /// with fewer imports and without an intermediate variable.
227 /// [`File::open`]: struct.File.html#method.open
228 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
232 /// This function will return an error if `path` does not already exist.
233 /// Other errors may also be returned according to [`OpenOptions::open`].
235 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
237 /// It will also return an error if it encounters while reading an error
238 /// of a kind other than [`ErrorKind::Interrupted`].
240 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
245 /// #![feature(fs_read_write)]
248 /// use std::net::SocketAddr;
250 /// # fn foo() -> Result<(), Box<std::error::Error + 'static>> {
251 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
255 #[unstable(feature = "fs_read_write", issue = "46588")]
256 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
257 let mut file = File::open(path)?;
258 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
259 file.read_to_end(&mut bytes)?;
263 /// Read the entire contents of a file into a string.
265 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
266 /// with fewer imports and without an intermediate variable.
268 /// [`File::open`]: struct.File.html#method.open
269 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
273 /// This function will return an error if `path` does not already exist.
274 /// Other errors may also be returned according to [`OpenOptions::open`].
276 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
278 /// It will also return an error if it encounters while reading an error
279 /// of a kind other than [`ErrorKind::Interrupted`],
280 /// or if the contents of the file are not valid UTF-8.
282 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
287 /// #![feature(fs_read_write)]
290 /// use std::net::SocketAddr;
292 /// # fn foo() -> Result<(), Box<std::error::Error + 'static>> {
293 /// let foo: SocketAddr = fs::read_string("address.txt")?.parse()?;
297 #[unstable(feature = "fs_read_write", issue = "46588")]
298 pub fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
299 let mut file = File::open(path)?;
300 let mut string = String::with_capacity(initial_buffer_size(&file));
301 file.read_to_string(&mut string)?;
305 /// Write a slice as the entire contents of a file.
307 /// This function will create a file if it does not exist,
308 /// and will entirely replace its contents if it does.
310 /// This is a convenience function for using [`File::create`] and [`write_all`]
311 /// with fewer imports.
313 /// [`File::create`]: struct.File.html#method.create
314 /// [`write_all`]: ../io/trait.Write.html#method.write_all
319 /// #![feature(fs_read_write)]
323 /// # fn foo() -> std::io::Result<()> {
324 /// fs::write("foo.txt", b"Lorem ipsum")?;
328 #[unstable(feature = "fs_read_write", issue = "46588")]
329 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
330 File::create(path)?.write_all(contents.as_ref())
334 /// Attempts to open a file in read-only mode.
336 /// See the [`OpenOptions::open`] method for more details.
340 /// This function will return an error if `path` does not already exist.
341 /// Other errors may also be returned according to [`OpenOptions::open`].
343 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
348 /// use std::fs::File;
350 /// # fn foo() -> std::io::Result<()> {
351 /// let mut f = File::open("foo.txt")?;
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
357 OpenOptions::new().read(true).open(path.as_ref())
360 /// Opens a file in write-only mode.
362 /// This function will create a file if it does not exist,
363 /// and will truncate it if it does.
365 /// See the [`OpenOptions::open`] function for more details.
367 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
372 /// use std::fs::File;
374 /// # fn foo() -> std::io::Result<()> {
375 /// let mut f = File::create("foo.txt")?;
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
381 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
384 /// Attempts to sync all OS-internal metadata to disk.
386 /// This function will attempt to ensure that all in-core data reaches the
387 /// filesystem before returning.
392 /// use std::fs::File;
393 /// use std::io::prelude::*;
395 /// # fn foo() -> std::io::Result<()> {
396 /// let mut f = File::create("foo.txt")?;
397 /// f.write_all(b"Hello, world!")?;
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn sync_all(&self) -> io::Result<()> {
408 /// This function is similar to [`sync_all`], except that it may not
409 /// synchronize file metadata to the filesystem.
411 /// This is intended for use cases that must synchronize content, but don't
412 /// need the metadata on disk. The goal of this method is to reduce disk
415 /// Note that some platforms may simply implement this in terms of
418 /// [`sync_all`]: struct.File.html#method.sync_all
423 /// use std::fs::File;
424 /// use std::io::prelude::*;
426 /// # fn foo() -> std::io::Result<()> {
427 /// let mut f = File::create("foo.txt")?;
428 /// f.write_all(b"Hello, world!")?;
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn sync_data(&self) -> io::Result<()> {
436 self.inner.datasync()
439 /// Truncates or extends the underlying file, updating the size of
440 /// this file to become `size`.
442 /// If the `size` is less than the current file's size, then the file will
443 /// be shrunk. If it is greater than the current file's size, then the file
444 /// will be extended to `size` and have all of the intermediate data filled
449 /// This function will return an error if the file is not opened for writing.
454 /// use std::fs::File;
456 /// # fn foo() -> std::io::Result<()> {
457 /// let mut f = File::create("foo.txt")?;
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn set_len(&self, size: u64) -> io::Result<()> {
464 self.inner.truncate(size)
467 /// Queries metadata about the underlying file.
472 /// use std::fs::File;
474 /// # fn foo() -> std::io::Result<()> {
475 /// let mut f = File::open("foo.txt")?;
476 /// let metadata = f.metadata()?;
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn metadata(&self) -> io::Result<Metadata> {
482 self.inner.file_attr().map(Metadata)
485 /// Creates a new independently owned handle to the underlying file.
487 /// The returned `File` is a reference to the same state that this object
488 /// references. Both handles will read and write with the same cursor
494 /// use std::fs::File;
496 /// # fn foo() -> std::io::Result<()> {
497 /// let mut f = File::open("foo.txt")?;
498 /// let file_copy = f.try_clone()?;
502 #[stable(feature = "file_try_clone", since = "1.9.0")]
503 pub fn try_clone(&self) -> io::Result<File> {
505 inner: self.inner.duplicate()?
509 /// Changes the permissions on the underlying file.
511 /// # Platform-specific behavior
513 /// This function currently corresponds to the `fchmod` function on Unix and
514 /// the `SetFileInformationByHandle` function on Windows. Note that, this
515 /// [may change in the future][changes].
517 /// [changes]: ../io/index.html#platform-specific-behavior
521 /// This function will return an error if the user lacks permission change
522 /// attributes on the underlying file. It may also return an error in other
523 /// os-specific unspecified cases.
528 /// # fn foo() -> std::io::Result<()> {
529 /// use std::fs::File;
531 /// let file = File::open("foo.txt")?;
532 /// let mut perms = file.metadata()?.permissions();
533 /// perms.set_readonly(true);
534 /// file.set_permissions(perms)?;
538 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
539 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
540 self.inner.set_permissions(perm.0)
544 impl AsInner<fs_imp::File> for File {
545 fn as_inner(&self) -> &fs_imp::File { &self.inner }
547 impl FromInner<fs_imp::File> for File {
548 fn from_inner(f: fs_imp::File) -> File {
552 impl IntoInner<fs_imp::File> for File {
553 fn into_inner(self) -> fs_imp::File {
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl fmt::Debug for File {
560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
565 #[stable(feature = "rust1", since = "1.0.0")]
567 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
572 unsafe fn initializer(&self) -> Initializer {
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl Write for File {
578 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
579 self.inner.write(buf)
581 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
583 #[stable(feature = "rust1", since = "1.0.0")]
585 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<'a> Read for &'a File {
591 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
596 unsafe fn initializer(&self) -> Initializer {
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl<'a> Write for &'a File {
602 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
603 self.inner.write(buf)
605 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl<'a> Seek for &'a File {
609 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
615 /// Creates a blank new set of options ready for configuration.
617 /// All options are initially set to `false`.
622 /// use std::fs::OpenOptions;
624 /// let mut options = OpenOptions::new();
625 /// let file = options.read(true).open("foo.txt");
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn new() -> OpenOptions {
629 OpenOptions(fs_imp::OpenOptions::new())
632 /// Sets the option for read access.
634 /// This option, when true, will indicate that the file should be
635 /// `read`-able if opened.
640 /// use std::fs::OpenOptions;
642 /// let file = OpenOptions::new().read(true).open("foo.txt");
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
646 self.0.read(read); self
649 /// Sets the option for write access.
651 /// This option, when true, will indicate that the file should be
652 /// `write`-able if opened.
654 /// If the file already exists, any write calls on it will overwrite its
655 /// contents, without truncating it.
660 /// use std::fs::OpenOptions;
662 /// let file = OpenOptions::new().write(true).open("foo.txt");
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
666 self.0.write(write); self
669 /// Sets the option for the append mode.
671 /// This option, when true, means that writes will append to a file instead
672 /// of overwriting previous contents.
673 /// Note that setting `.write(true).append(true)` has the same effect as
674 /// setting only `.append(true)`.
676 /// For most filesystems, the operating system guarantees that all writes are
677 /// atomic: no writes get mangled because another process writes at the same
680 /// One maybe obvious note when using append-mode: make sure that all data
681 /// that belongs together is written to the file in one operation. This
682 /// can be done by concatenating strings before passing them to [`write()`],
683 /// or using a buffered writer (with a buffer of adequate size),
684 /// and calling [`flush()`] when the message is complete.
686 /// If a file is opened with both read and append access, beware that after
687 /// opening, and after every write, the position for reading may be set at the
688 /// end of the file. So, before writing, save the current position (using
689 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`, and restore it before the next read.
693 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
696 /// [`write()`]: ../../std/fs/struct.File.html#method.write
697 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
698 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
699 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
700 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
701 /// [`create`]: #method.create
706 /// use std::fs::OpenOptions;
708 /// let file = OpenOptions::new().append(true).open("foo.txt");
710 #[stable(feature = "rust1", since = "1.0.0")]
711 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
712 self.0.append(append); self
715 /// Sets the option for truncating a previous file.
717 /// If a file is successfully opened with this option set it will truncate
718 /// the file to 0 length if it already exists.
720 /// The file must be opened with write access for truncate to work.
725 /// use std::fs::OpenOptions;
727 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
731 self.0.truncate(truncate); self
734 /// Sets the option for creating a new file.
736 /// This option indicates whether a new file will be created if the file
737 /// does not yet already exist.
739 /// In order for the file to be created, [`write`] or [`append`] access must
742 /// [`write`]: #method.write
743 /// [`append`]: #method.append
748 /// use std::fs::OpenOptions;
750 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
754 self.0.create(create); self
757 /// Sets the option to always create a new file.
759 /// This option indicates whether a new file will be created.
760 /// No file is allowed to exist at the target location, also no (dangling)
763 /// This option is useful because it is atomic. Otherwise between checking
764 /// whether a file exists and creating a new one, the file may have been
765 /// created by another process (a TOCTOU race condition / attack).
767 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
770 /// The file must be opened with write or append access in order to create
773 /// [`.create()`]: #method.create
774 /// [`.truncate()`]: #method.truncate
779 /// use std::fs::OpenOptions;
781 /// let file = OpenOptions::new().write(true)
782 /// .create_new(true)
783 /// .open("foo.txt");
785 #[stable(feature = "expand_open_options2", since = "1.9.0")]
786 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
787 self.0.create_new(create_new); self
790 /// Opens a file at `path` with the options specified by `self`.
794 /// This function will return an error under a number of different
795 /// circumstances. Some of these error conditions are listed here, together
796 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
797 /// the compatibility contract of the function, especially the `Other` kind
798 /// might change to more specific kinds in the future.
800 /// * [`NotFound`]: The specified file does not exist and neither `create`
801 /// or `create_new` is set.
802 /// * [`NotFound`]: One of the directory components of the file path does
804 /// * [`PermissionDenied`]: The user lacks permission to get the specified
805 /// access rights for the file.
806 /// * [`PermissionDenied`]: The user lacks permission to open one of the
807 /// directory components of the specified path.
808 /// * [`AlreadyExists`]: `create_new` was specified and the file already
810 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
811 /// without write access, no access mode set, etc.).
812 /// * [`Other`]: One of the directory components of the specified file path
813 /// was not, in fact, a directory.
814 /// * [`Other`]: Filesystem-level errors: full disk, write permission
815 /// requested on a read-only file system, exceeded disk quota, too many
816 /// open files, too long filename, too many symbolic links in the
817 /// specified path (Unix-like systems only), etc.
822 /// use std::fs::OpenOptions;
824 /// let file = OpenOptions::new().open("foo.txt");
827 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
828 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
829 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
830 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
831 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
832 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
835 self._open(path.as_ref())
838 fn _open(&self, path: &Path) -> io::Result<File> {
839 let inner = fs_imp::File::open(path, &self.0)?;
840 Ok(File { inner: inner })
844 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
845 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
849 /// Returns the file type for this metadata.
854 /// # fn foo() -> std::io::Result<()> {
857 /// let metadata = fs::metadata("foo.txt")?;
859 /// println!("{:?}", metadata.file_type());
863 #[stable(feature = "file_type", since = "1.1.0")]
864 pub fn file_type(&self) -> FileType {
865 FileType(self.0.file_type())
868 /// Returns whether this metadata is for a directory.
873 /// # fn foo() -> std::io::Result<()> {
876 /// let metadata = fs::metadata("foo.txt")?;
878 /// assert!(!metadata.is_dir());
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
885 /// Returns whether this metadata is for a regular file.
890 /// # fn foo() -> std::io::Result<()> {
893 /// let metadata = fs::metadata("foo.txt")?;
895 /// assert!(metadata.is_file());
899 #[stable(feature = "rust1", since = "1.0.0")]
900 pub fn is_file(&self) -> bool { self.file_type().is_file() }
902 /// Returns the size of the file, in bytes, this metadata is for.
907 /// # fn foo() -> std::io::Result<()> {
910 /// let metadata = fs::metadata("foo.txt")?;
912 /// assert_eq!(0, metadata.len());
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn len(&self) -> u64 { self.0.size() }
919 /// Returns the permissions of the file this metadata is for.
924 /// # fn foo() -> std::io::Result<()> {
927 /// let metadata = fs::metadata("foo.txt")?;
929 /// assert!(!metadata.permissions().readonly());
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn permissions(&self) -> Permissions {
935 Permissions(self.0.perm())
938 /// Returns the last modification time listed in this metadata.
940 /// The returned value corresponds to the `mtime` field of `stat` on Unix
941 /// platforms and the `ftLastWriteTime` field on Windows platforms.
945 /// This field may not be available on all platforms, and will return an
946 /// `Err` on platforms where it is not available.
951 /// # fn foo() -> std::io::Result<()> {
954 /// let metadata = fs::metadata("foo.txt")?;
956 /// if let Ok(time) = metadata.modified() {
957 /// println!("{:?}", time);
959 /// println!("Not supported on this platform");
964 #[stable(feature = "fs_time", since = "1.10.0")]
965 pub fn modified(&self) -> io::Result<SystemTime> {
966 self.0.modified().map(FromInner::from_inner)
969 /// Returns the last access time of this metadata.
971 /// The returned value corresponds to the `atime` field of `stat` on Unix
972 /// platforms and the `ftLastAccessTime` field on Windows platforms.
974 /// Note that not all platforms will keep this field update in a file's
975 /// metadata, for example Windows has an option to disable updating this
976 /// time when files are accessed and Linux similarly has `noatime`.
980 /// This field may not be available on all platforms, and will return an
981 /// `Err` on platforms where it is not available.
986 /// # fn foo() -> std::io::Result<()> {
989 /// let metadata = fs::metadata("foo.txt")?;
991 /// if let Ok(time) = metadata.accessed() {
992 /// println!("{:?}", time);
994 /// println!("Not supported on this platform");
999 #[stable(feature = "fs_time", since = "1.10.0")]
1000 pub fn accessed(&self) -> io::Result<SystemTime> {
1001 self.0.accessed().map(FromInner::from_inner)
1004 /// Returns the creation time listed in the this metadata.
1006 /// The returned value corresponds to the `birthtime` field of `stat` on
1007 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1011 /// This field may not be available on all platforms, and will return an
1012 /// `Err` on platforms where it is not available.
1017 /// # fn foo() -> std::io::Result<()> {
1020 /// let metadata = fs::metadata("foo.txt")?;
1022 /// if let Ok(time) = metadata.created() {
1023 /// println!("{:?}", time);
1025 /// println!("Not supported on this platform");
1030 #[stable(feature = "fs_time", since = "1.10.0")]
1031 pub fn created(&self) -> io::Result<SystemTime> {
1032 self.0.created().map(FromInner::from_inner)
1036 #[stable(feature = "std_debug", since = "1.16.0")]
1037 impl fmt::Debug for Metadata {
1038 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1039 f.debug_struct("Metadata")
1040 .field("file_type", &self.file_type())
1041 .field("is_dir", &self.is_dir())
1042 .field("is_file", &self.is_file())
1043 .field("permissions", &self.permissions())
1044 .field("modified", &self.modified())
1045 .field("accessed", &self.accessed())
1046 .field("created", &self.created())
1051 impl AsInner<fs_imp::FileAttr> for Metadata {
1052 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1056 /// Returns whether these permissions describe a readonly (unwritable) file.
1061 /// use std::fs::File;
1063 /// # fn foo() -> std::io::Result<()> {
1064 /// let mut f = File::create("foo.txt")?;
1065 /// let metadata = f.metadata()?;
1067 /// assert_eq!(false, metadata.permissions().readonly());
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 pub fn readonly(&self) -> bool { self.0.readonly() }
1074 /// Modifies the readonly flag for this set of permissions. If the
1075 /// `readonly` argument is `true`, using the resulting `Permission` will
1076 /// update file permissions to forbid writing. Conversely, if it's `false`,
1077 /// using the resulting `Permission` will update file permissions to allow
1080 /// This operation does **not** modify the filesystem. To modify the
1081 /// filesystem use the `fs::set_permissions` function.
1086 /// use std::fs::File;
1088 /// # fn foo() -> std::io::Result<()> {
1089 /// let f = File::create("foo.txt")?;
1090 /// let metadata = f.metadata()?;
1091 /// let mut permissions = metadata.permissions();
1093 /// permissions.set_readonly(true);
1095 /// // filesystem doesn't change
1096 /// assert_eq!(false, metadata.permissions().readonly());
1098 /// // just this particular `permissions`.
1099 /// assert_eq!(true, permissions.readonly());
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 pub fn set_readonly(&mut self, readonly: bool) {
1105 self.0.set_readonly(readonly)
1110 /// Test whether this file type represents a directory.
1115 /// # fn foo() -> std::io::Result<()> {
1118 /// let metadata = fs::metadata("foo.txt")?;
1119 /// let file_type = metadata.file_type();
1121 /// assert_eq!(file_type.is_dir(), false);
1125 #[stable(feature = "file_type", since = "1.1.0")]
1126 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1128 /// Test whether this file type represents a regular file.
1133 /// # fn foo() -> std::io::Result<()> {
1136 /// let metadata = fs::metadata("foo.txt")?;
1137 /// let file_type = metadata.file_type();
1139 /// assert_eq!(file_type.is_file(), true);
1143 #[stable(feature = "file_type", since = "1.1.0")]
1144 pub fn is_file(&self) -> bool { self.0.is_file() }
1146 /// Test whether this file type represents a symbolic link.
1148 /// The underlying [`Metadata`] struct needs to be retrieved
1149 /// with the [`fs::symlink_metadata`] function and not the
1150 /// [`fs::metadata`] function. The [`fs::metadata`] function
1151 /// follows symbolic links, so [`is_symlink`] would always
1152 /// return false for the target file.
1154 /// [`Metadata`]: struct.Metadata.html
1155 /// [`fs::metadata`]: fn.metadata.html
1156 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1157 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1162 /// # fn foo() -> std::io::Result<()> {
1165 /// let metadata = fs::symlink_metadata("foo.txt")?;
1166 /// let file_type = metadata.file_type();
1168 /// assert_eq!(file_type.is_symlink(), false);
1172 #[stable(feature = "file_type", since = "1.1.0")]
1173 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1176 impl AsInner<fs_imp::FileType> for FileType {
1177 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1180 impl FromInner<fs_imp::FilePermissions> for Permissions {
1181 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1186 impl AsInner<fs_imp::FilePermissions> for Permissions {
1187 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl Iterator for ReadDir {
1192 type Item = io::Result<DirEntry>;
1194 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1195 self.0.next().map(|entry| entry.map(DirEntry))
1200 /// Returns the full path to the file that this entry represents.
1202 /// The full path is created by joining the original path to `read_dir`
1203 /// with the filename of this entry.
1209 /// # fn foo() -> std::io::Result<()> {
1210 /// for entry in fs::read_dir(".")? {
1211 /// let dir = entry?;
1212 /// println!("{:?}", dir.path());
1218 /// This prints output like:
1221 /// "./whatever.txt"
1223 /// "./hello_world.rs"
1226 /// The exact text, of course, depends on what files you have in `.`.
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 pub fn path(&self) -> PathBuf { self.0.path() }
1230 /// Return the metadata for the file that this entry points at.
1232 /// This function will not traverse symlinks if this entry points at a
1235 /// # Platform-specific behavior
1237 /// On Windows this function is cheap to call (no extra system calls
1238 /// needed), but on Unix platforms this function is the equivalent of
1239 /// calling `symlink_metadata` on the path.
1246 /// if let Ok(entries) = fs::read_dir(".") {
1247 /// for entry in entries {
1248 /// if let Ok(entry) = entry {
1249 /// // Here, `entry` is a `DirEntry`.
1250 /// if let Ok(metadata) = entry.metadata() {
1251 /// // Now let's show our entry's permissions!
1252 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1254 /// println!("Couldn't get metadata for {:?}", entry.path());
1260 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1261 pub fn metadata(&self) -> io::Result<Metadata> {
1262 self.0.metadata().map(Metadata)
1265 /// Return the file type for the file that this entry points at.
1267 /// This function will not traverse symlinks if this entry points at a
1270 /// # Platform-specific behavior
1272 /// On Windows and most Unix platforms this function is free (no extra
1273 /// system calls needed), but some Unix platforms may require the equivalent
1274 /// call to `symlink_metadata` to learn about the target file type.
1281 /// if let Ok(entries) = fs::read_dir(".") {
1282 /// for entry in entries {
1283 /// if let Ok(entry) = entry {
1284 /// // Here, `entry` is a `DirEntry`.
1285 /// if let Ok(file_type) = entry.file_type() {
1286 /// // Now let's show our entry's file type!
1287 /// println!("{:?}: {:?}", entry.path(), file_type);
1289 /// println!("Couldn't get file type for {:?}", entry.path());
1295 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1296 pub fn file_type(&self) -> io::Result<FileType> {
1297 self.0.file_type().map(FileType)
1300 /// Returns the bare file name of this directory entry without any other
1301 /// leading path component.
1308 /// if let Ok(entries) = fs::read_dir(".") {
1309 /// for entry in entries {
1310 /// if let Ok(entry) = entry {
1311 /// // Here, `entry` is a `DirEntry`.
1312 /// println!("{:?}", entry.file_name());
1317 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1318 pub fn file_name(&self) -> OsString {
1323 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1324 impl fmt::Debug for DirEntry {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326 f.debug_tuple("DirEntry")
1327 .field(&self.path())
1332 impl AsInner<fs_imp::DirEntry> for DirEntry {
1333 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1336 /// Removes a file from the filesystem.
1338 /// Note that there is no
1339 /// guarantee that the file is immediately deleted (e.g. depending on
1340 /// platform, other open file descriptors may prevent immediate removal).
1342 /// # Platform-specific behavior
1344 /// This function currently corresponds to the `unlink` function on Unix
1345 /// and the `DeleteFile` function on Windows.
1346 /// Note that, this [may change in the future][changes].
1348 /// [changes]: ../io/index.html#platform-specific-behavior
1352 /// This function will return an error in the following situations, but is not
1353 /// limited to just these cases:
1355 /// * `path` points to a directory.
1356 /// * The user lacks permissions to remove the file.
1363 /// # fn foo() -> std::io::Result<()> {
1364 /// fs::remove_file("a.txt")?;
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1370 fs_imp::unlink(path.as_ref())
1373 /// Given a path, query the file system to get information about a file,
1376 /// This function will traverse symbolic links to query information about the
1377 /// destination file.
1379 /// # Platform-specific behavior
1381 /// This function currently corresponds to the `stat` function on Unix
1382 /// and the `GetFileAttributesEx` function on Windows.
1383 /// Note that, this [may change in the future][changes].
1385 /// [changes]: ../io/index.html#platform-specific-behavior
1389 /// This function will return an error in the following situations, but is not
1390 /// limited to just these cases:
1392 /// * The user lacks permissions to perform `metadata` call on `path`.
1393 /// * `path` does not exist.
1398 /// # fn foo() -> std::io::Result<()> {
1401 /// let attr = fs::metadata("/some/file/path.txt")?;
1402 /// // inspect attr ...
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1408 fs_imp::stat(path.as_ref()).map(Metadata)
1411 /// Query the metadata about a file without following symlinks.
1413 /// # Platform-specific behavior
1415 /// This function currently corresponds to the `lstat` function on Unix
1416 /// and the `GetFileAttributesEx` function on Windows.
1417 /// Note that, this [may change in the future][changes].
1419 /// [changes]: ../io/index.html#platform-specific-behavior
1423 /// This function will return an error in the following situations, but is not
1424 /// limited to just these cases:
1426 /// * The user lacks permissions to perform `metadata` call on `path`.
1427 /// * `path` does not exist.
1432 /// # fn foo() -> std::io::Result<()> {
1435 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1436 /// // inspect attr ...
1440 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1441 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1442 fs_imp::lstat(path.as_ref()).map(Metadata)
1445 /// Rename a file or directory to a new name, replacing the original file if
1446 /// `to` already exists.
1448 /// This will not work if the new name is on a different mount point.
1450 /// # Platform-specific behavior
1452 /// This function currently corresponds to the `rename` function on Unix
1453 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1455 /// Because of this, the behavior when both `from` and `to` exist differs. On
1456 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1457 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1458 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1460 /// Note that, this [may change in the future][changes].
1462 /// [changes]: ../io/index.html#platform-specific-behavior
1466 /// This function will return an error in the following situations, but is not
1467 /// limited to just these cases:
1469 /// * `from` does not exist.
1470 /// * The user lacks permissions to view contents.
1471 /// * `from` and `to` are on separate filesystems.
1478 /// # fn foo() -> std::io::Result<()> {
1479 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1485 fs_imp::rename(from.as_ref(), to.as_ref())
1488 /// Copies the contents of one file to another. This function will also
1489 /// copy the permission bits of the original file to the destination file.
1491 /// This function will **overwrite** the contents of `to`.
1493 /// Note that if `from` and `to` both point to the same file, then the file
1494 /// will likely get truncated by this operation.
1496 /// On success, the total number of bytes copied is returned and it is equal to
1497 /// the length of the `to` file as reported by `metadata`.
1499 /// # Platform-specific behavior
1501 /// This function currently corresponds to the `open` function in Unix
1502 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1503 /// `O_CLOEXEC` is set for returned file descriptors.
1504 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1505 /// NTFS streams are copied but only the size of the main stream is returned by
1507 /// Note that, this [may change in the future][changes].
1509 /// [changes]: ../io/index.html#platform-specific-behavior
1513 /// This function will return an error in the following situations, but is not
1514 /// limited to just these cases:
1516 /// * The `from` path is not a file.
1517 /// * The `from` file does not exist.
1518 /// * The current process does not have the permission rights to access
1519 /// `from` or write `to`.
1526 /// # fn foo() -> std::io::Result<()> {
1527 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1532 fs_imp::copy(from.as_ref(), to.as_ref())
1535 /// Creates a new hard link on the filesystem.
1537 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1538 /// often require these two paths to both be located on the same filesystem.
1540 /// # Platform-specific behavior
1542 /// This function currently corresponds to the `link` function on Unix
1543 /// and the `CreateHardLink` function on Windows.
1544 /// Note that, this [may change in the future][changes].
1546 /// [changes]: ../io/index.html#platform-specific-behavior
1550 /// This function will return an error in the following situations, but is not
1551 /// limited to just these cases:
1553 /// * The `src` path is not a file or doesn't exist.
1560 /// # fn foo() -> std::io::Result<()> {
1561 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1567 fs_imp::link(src.as_ref(), dst.as_ref())
1570 /// Creates a new symbolic link on the filesystem.
1572 /// The `dst` path will be a symbolic link pointing to the `src` path.
1573 /// On Windows, this will be a file symlink, not a directory symlink;
1574 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1575 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1576 /// used instead to make the intent explicit.
1583 /// # fn foo() -> std::io::Result<()> {
1584 /// fs::soft_link("a.txt", "b.txt")?;
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 #[rustc_deprecated(since = "1.1.0",
1590 reason = "replaced with std::os::unix::fs::symlink and \
1591 std::os::windows::fs::{symlink_file, symlink_dir}")]
1592 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1593 fs_imp::symlink(src.as_ref(), dst.as_ref())
1596 /// Reads a symbolic link, returning the file that the link points to.
1598 /// # Platform-specific behavior
1600 /// This function currently corresponds to the `readlink` function on Unix
1601 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1602 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1603 /// Note that, this [may change in the future][changes].
1605 /// [changes]: ../io/index.html#platform-specific-behavior
1609 /// This function will return an error in the following situations, but is not
1610 /// limited to just these cases:
1612 /// * `path` is not a symbolic link.
1613 /// * `path` does not exist.
1620 /// # fn foo() -> std::io::Result<()> {
1621 /// let path = fs::read_link("a.txt")?;
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1627 fs_imp::readlink(path.as_ref())
1630 /// Returns the canonical form of a path with all intermediate components
1631 /// normalized and symbolic links resolved.
1633 /// # Platform-specific behavior
1635 /// This function currently corresponds to the `realpath` function on Unix
1636 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1637 /// Note that, this [may change in the future][changes].
1639 /// [changes]: ../io/index.html#platform-specific-behavior
1643 /// This function will return an error in the following situations, but is not
1644 /// limited to just these cases:
1646 /// * `path` does not exist.
1647 /// * A component in path is not a directory.
1654 /// # fn foo() -> std::io::Result<()> {
1655 /// let path = fs::canonicalize("../a/../foo.txt")?;
1659 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1660 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1661 fs_imp::canonicalize(path.as_ref())
1664 /// Creates a new, empty directory at the provided path
1666 /// # Platform-specific behavior
1668 /// This function currently corresponds to the `mkdir` function on Unix
1669 /// and the `CreateDirectory` function on Windows.
1670 /// Note that, this [may change in the future][changes].
1672 /// [changes]: ../io/index.html#platform-specific-behavior
1676 /// This function will return an error in the following situations, but is not
1677 /// limited to just these cases:
1679 /// * User lacks permissions to create directory at `path`.
1680 /// * `path` already exists.
1687 /// # fn foo() -> std::io::Result<()> {
1688 /// fs::create_dir("/some/dir")?;
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1694 DirBuilder::new().create(path.as_ref())
1697 /// Recursively create a directory and all of its parent components if they
1700 /// # Platform-specific behavior
1702 /// This function currently corresponds to the `mkdir` function on Unix
1703 /// and the `CreateDirectory` function on Windows.
1704 /// Note that, this [may change in the future][changes].
1706 /// [changes]: ../io/index.html#platform-specific-behavior
1710 /// This function will return an error in the following situations, but is not
1711 /// limited to just these cases:
1713 /// * If any directory in the path specified by `path`
1714 /// does not already exist and it could not be created otherwise. The specific
1715 /// error conditions for when a directory is being created (after it is
1716 /// determined to not exist) are outlined by `fs::create_dir`.
1718 /// Notable exception is made for situations where any of the directories
1719 /// specified in the `path` could not be created as it was being created concurrently.
1720 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1721 /// concurrently from multiple threads or processes is guaranteed not to fail
1722 /// due to a race condition with itself.
1729 /// # fn foo() -> std::io::Result<()> {
1730 /// fs::create_dir_all("/some/dir")?;
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1736 DirBuilder::new().recursive(true).create(path.as_ref())
1739 /// Removes an existing, empty directory.
1741 /// # Platform-specific behavior
1743 /// This function currently corresponds to the `rmdir` function on Unix
1744 /// and the `RemoveDirectory` function on Windows.
1745 /// Note that, this [may change in the future][changes].
1747 /// [changes]: ../io/index.html#platform-specific-behavior
1751 /// This function will return an error in the following situations, but is not
1752 /// limited to just these cases:
1754 /// * The user lacks permissions to remove the directory at the provided `path`.
1755 /// * The directory isn't empty.
1762 /// # fn foo() -> std::io::Result<()> {
1763 /// fs::remove_dir("/some/dir")?;
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1769 fs_imp::rmdir(path.as_ref())
1772 /// Removes a directory at this path, after removing all its contents. Use
1775 /// This function does **not** follow symbolic links and it will simply remove the
1776 /// symbolic link itself.
1778 /// # Platform-specific behavior
1780 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1781 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1783 /// Note that, this [may change in the future][changes].
1785 /// [changes]: ../io/index.html#platform-specific-behavior
1789 /// See `file::remove_file` and `fs::remove_dir`.
1796 /// # fn foo() -> std::io::Result<()> {
1797 /// fs::remove_dir_all("/some/dir")?;
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1803 fs_imp::remove_dir_all(path.as_ref())
1806 /// Returns an iterator over the entries within a directory.
1808 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1809 /// New errors may be encountered after an iterator is initially constructed.
1811 /// [`io::Result`]: ../io/type.Result.html
1812 /// [`DirEntry`]: struct.DirEntry.html
1814 /// # Platform-specific behavior
1816 /// This function currently corresponds to the `opendir` function on Unix
1817 /// and the `FindFirstFile` function on Windows.
1818 /// Note that, this [may change in the future][changes].
1820 /// [changes]: ../io/index.html#platform-specific-behavior
1824 /// This function will return an error in the following situations, but is not
1825 /// limited to just these cases:
1827 /// * The provided `path` doesn't exist.
1828 /// * The process lacks permissions to view the contents.
1829 /// * The `path` points at a non-directory file.
1835 /// use std::fs::{self, DirEntry};
1836 /// use std::path::Path;
1838 /// // one possible implementation of walking a directory only visiting files
1839 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1840 /// if dir.is_dir() {
1841 /// for entry in fs::read_dir(dir)? {
1842 /// let entry = entry?;
1843 /// let path = entry.path();
1844 /// if path.is_dir() {
1845 /// visit_dirs(&path, cb)?;
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1856 fs_imp::readdir(path.as_ref()).map(ReadDir)
1859 /// Changes the permissions found on a file or a directory.
1861 /// # Platform-specific behavior
1863 /// This function currently corresponds to the `chmod` function on Unix
1864 /// and the `SetFileAttributes` function on Windows.
1865 /// Note that, this [may change in the future][changes].
1867 /// [changes]: ../io/index.html#platform-specific-behavior
1871 /// This function will return an error in the following situations, but is not
1872 /// limited to just these cases:
1874 /// * `path` does not exist.
1875 /// * The user lacks the permission to change attributes of the file.
1880 /// # fn foo() -> std::io::Result<()> {
1883 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1884 /// perms.set_readonly(true);
1885 /// fs::set_permissions("foo.txt", perms)?;
1889 #[stable(feature = "set_permissions", since = "1.1.0")]
1890 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1892 fs_imp::set_perm(path.as_ref(), perm.0)
1896 /// Creates a new set of options with default mode/security settings for all
1897 /// platforms and also non-recursive.
1902 /// use std::fs::DirBuilder;
1904 /// let builder = DirBuilder::new();
1906 #[stable(feature = "dir_builder", since = "1.6.0")]
1907 pub fn new() -> DirBuilder {
1909 inner: fs_imp::DirBuilder::new(),
1914 /// Indicates that directories should be created recursively, creating all
1915 /// parent directories. Parents that do not exist are created with the same
1916 /// security and permissions settings.
1918 /// This option defaults to `false`.
1923 /// use std::fs::DirBuilder;
1925 /// let mut builder = DirBuilder::new();
1926 /// builder.recursive(true);
1928 #[stable(feature = "dir_builder", since = "1.6.0")]
1929 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1930 self.recursive = recursive;
1934 /// Create the specified directory with the options configured in this
1937 /// It is considered an error if the directory already exists unless
1938 /// recursive mode is enabled.
1943 /// use std::fs::{self, DirBuilder};
1945 /// let path = "/tmp/foo/bar/baz";
1946 /// DirBuilder::new()
1947 /// .recursive(true)
1948 /// .create(path).unwrap();
1950 /// assert!(fs::metadata(path).unwrap().is_dir());
1952 #[stable(feature = "dir_builder", since = "1.6.0")]
1953 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1954 self._create(path.as_ref())
1957 fn _create(&self, path: &Path) -> io::Result<()> {
1959 self.create_dir_all(path)
1961 self.inner.mkdir(path)
1965 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1966 if path == Path::new("") {
1970 match self.inner.mkdir(path) {
1971 Ok(()) => return Ok(()),
1972 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
1973 Err(_) if path.is_dir() => return Ok(()),
1974 Err(e) => return Err(e),
1976 match path.parent() {
1977 Some(p) => try!(self.create_dir_all(p)),
1978 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
1980 match self.inner.mkdir(path) {
1982 Err(_) if path.is_dir() => Ok(()),
1988 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1989 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1994 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
1998 use fs::{self, File, OpenOptions};
1999 use io::{ErrorKind, SeekFrom};
2001 use rand::{StdRng, Rng};
2003 use sys_common::io::test::{TempDir, tmpdir};
2007 use os::windows::fs::{symlink_dir, symlink_file};
2009 use sys::fs::symlink_junction;
2011 use os::unix::fs::symlink as symlink_dir;
2013 use os::unix::fs::symlink as symlink_file;
2015 use os::unix::fs::symlink as symlink_junction;
2017 macro_rules! check { ($e:expr) => (
2020 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2025 macro_rules! error { ($e:expr, $s:expr) => (
2027 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2028 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2029 format!("`{}` did not have a code of `{}`", err, $s))
2034 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2036 macro_rules! error_contains { ($e:expr, $s:expr) => (
2038 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2039 Err(ref err) => assert!(err.to_string().contains($s),
2040 format!("`{}` did not contain `{}`", err, $s))
2044 // Several test fail on windows if the user does not have permission to
2045 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2046 // disabling these test on Windows, use this function to test whether we
2047 // have permission, and return otherwise. This way, we still don't run these
2048 // tests most of the time, but at least we do if the user has the right
2050 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2051 if cfg!(unix) { return true }
2052 let link = tmpdir.join("some_hopefully_unique_link_name");
2054 match symlink_file(r"nonexisting_target", link) {
2056 // ERROR_PRIVILEGE_NOT_HELD = 1314
2057 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2063 fn file_test_io_smoke_test() {
2064 let message = "it's alright. have a good time";
2065 let tmpdir = tmpdir();
2066 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2068 let mut write_stream = check!(File::create(filename));
2069 check!(write_stream.write(message.as_bytes()));
2072 let mut read_stream = check!(File::open(filename));
2073 let mut read_buf = [0; 1028];
2074 let read_str = match check!(read_stream.read(&mut read_buf)) {
2075 0 => panic!("shouldn't happen"),
2076 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2078 assert_eq!(read_str, message);
2080 check!(fs::remove_file(filename));
2084 fn invalid_path_raises() {
2085 let tmpdir = tmpdir();
2086 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2087 let result = File::open(filename);
2090 error!(result, "No such file or directory");
2092 error!(result, 2); // ERROR_FILE_NOT_FOUND
2096 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2097 let tmpdir = tmpdir();
2098 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2100 let result = fs::remove_file(filename);
2103 error!(result, "No such file or directory");
2105 error!(result, 2); // ERROR_FILE_NOT_FOUND
2109 fn file_test_io_non_positional_read() {
2110 let message: &str = "ten-four";
2111 let mut read_mem = [0; 8];
2112 let tmpdir = tmpdir();
2113 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2115 let mut rw_stream = check!(File::create(filename));
2116 check!(rw_stream.write(message.as_bytes()));
2119 let mut read_stream = check!(File::open(filename));
2121 let read_buf = &mut read_mem[0..4];
2122 check!(read_stream.read(read_buf));
2125 let read_buf = &mut read_mem[4..8];
2126 check!(read_stream.read(read_buf));
2129 check!(fs::remove_file(filename));
2130 let read_str = str::from_utf8(&read_mem).unwrap();
2131 assert_eq!(read_str, message);
2135 fn file_test_io_seek_and_tell_smoke_test() {
2136 let message = "ten-four";
2137 let mut read_mem = [0; 4];
2138 let set_cursor = 4 as u64;
2139 let tell_pos_pre_read;
2140 let tell_pos_post_read;
2141 let tmpdir = tmpdir();
2142 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2144 let mut rw_stream = check!(File::create(filename));
2145 check!(rw_stream.write(message.as_bytes()));
2148 let mut read_stream = check!(File::open(filename));
2149 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2150 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2151 check!(read_stream.read(&mut read_mem));
2152 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2154 check!(fs::remove_file(filename));
2155 let read_str = str::from_utf8(&read_mem).unwrap();
2156 assert_eq!(read_str, &message[4..8]);
2157 assert_eq!(tell_pos_pre_read, set_cursor);
2158 assert_eq!(tell_pos_post_read, message.len() as u64);
2162 fn file_test_io_seek_and_write() {
2163 let initial_msg = "food-is-yummy";
2164 let overwrite_msg = "-the-bar!!";
2165 let final_msg = "foo-the-bar!!";
2167 let mut read_mem = [0; 13];
2168 let tmpdir = tmpdir();
2169 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2171 let mut rw_stream = check!(File::create(filename));
2172 check!(rw_stream.write(initial_msg.as_bytes()));
2173 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2174 check!(rw_stream.write(overwrite_msg.as_bytes()));
2177 let mut read_stream = check!(File::open(filename));
2178 check!(read_stream.read(&mut read_mem));
2180 check!(fs::remove_file(filename));
2181 let read_str = str::from_utf8(&read_mem).unwrap();
2182 assert!(read_str == final_msg);
2186 fn file_test_io_seek_shakedown() {
2188 let initial_msg = "qwer-asdf-zxcv";
2189 let chunk_one: &str = "qwer";
2190 let chunk_two: &str = "asdf";
2191 let chunk_three: &str = "zxcv";
2192 let mut read_mem = [0; 4];
2193 let tmpdir = tmpdir();
2194 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2196 let mut rw_stream = check!(File::create(filename));
2197 check!(rw_stream.write(initial_msg.as_bytes()));
2200 let mut read_stream = check!(File::open(filename));
2202 check!(read_stream.seek(SeekFrom::End(-4)));
2203 check!(read_stream.read(&mut read_mem));
2204 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2206 check!(read_stream.seek(SeekFrom::Current(-9)));
2207 check!(read_stream.read(&mut read_mem));
2208 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2210 check!(read_stream.seek(SeekFrom::Start(0)));
2211 check!(read_stream.read(&mut read_mem));
2212 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2214 check!(fs::remove_file(filename));
2218 fn file_test_io_eof() {
2219 let tmpdir = tmpdir();
2220 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2221 let mut buf = [0; 256];
2223 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2224 let mut rw = check!(oo.open(&filename));
2225 assert_eq!(check!(rw.read(&mut buf)), 0);
2226 assert_eq!(check!(rw.read(&mut buf)), 0);
2228 check!(fs::remove_file(&filename));
2233 fn file_test_io_read_write_at() {
2234 use os::unix::fs::FileExt;
2236 let tmpdir = tmpdir();
2237 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2238 let mut buf = [0; 256];
2239 let write1 = "asdf";
2240 let write2 = "qwer-";
2241 let write3 = "-zxcv";
2242 let content = "qwer-asdf-zxcv";
2244 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2245 let mut rw = check!(oo.open(&filename));
2246 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2247 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2248 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2249 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2250 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2251 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2252 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2253 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2254 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2255 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2256 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2257 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2258 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2259 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2260 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2261 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2262 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2263 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2266 let mut read = check!(File::open(&filename));
2267 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2268 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2269 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2270 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2271 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2272 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2273 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2274 assert_eq!(check!(read.read(&mut buf)), write3.len());
2275 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2276 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2277 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2278 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2279 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2280 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2281 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2282 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2284 check!(fs::remove_file(&filename));
2289 fn set_get_unix_permissions() {
2290 use os::unix::fs::PermissionsExt;
2292 let tmpdir = tmpdir();
2293 let filename = &tmpdir.join("set_get_unix_permissions");
2294 check!(fs::create_dir(filename));
2297 check!(fs::set_permissions(filename,
2298 fs::Permissions::from_mode(0)));
2299 let metadata0 = check!(fs::metadata(filename));
2300 assert_eq!(mask & metadata0.permissions().mode(), 0);
2302 check!(fs::set_permissions(filename,
2303 fs::Permissions::from_mode(0o1777)));
2304 let metadata1 = check!(fs::metadata(filename));
2305 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2310 fn file_test_io_seek_read_write() {
2311 use os::windows::fs::FileExt;
2313 let tmpdir = tmpdir();
2314 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2315 let mut buf = [0; 256];
2316 let write1 = "asdf";
2317 let write2 = "qwer-";
2318 let write3 = "-zxcv";
2319 let content = "qwer-asdf-zxcv";
2321 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2322 let mut rw = check!(oo.open(&filename));
2323 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2324 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2325 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2326 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2327 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2328 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2329 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2330 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2331 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2332 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2333 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2334 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2335 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2336 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2337 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2338 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2341 let mut read = check!(File::open(&filename));
2342 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2343 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2344 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2345 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2346 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2347 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2348 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2349 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2350 assert_eq!(check!(read.read(&mut buf)), write3.len());
2351 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2352 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2353 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2354 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2355 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2356 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2357 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2359 check!(fs::remove_file(&filename));
2363 fn file_test_stat_is_correct_on_is_file() {
2364 let tmpdir = tmpdir();
2365 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2367 let mut opts = OpenOptions::new();
2368 let mut fs = check!(opts.read(true).write(true)
2369 .create(true).open(filename));
2371 fs.write(msg.as_bytes()).unwrap();
2373 let fstat_res = check!(fs.metadata());
2374 assert!(fstat_res.is_file());
2376 let stat_res_fn = check!(fs::metadata(filename));
2377 assert!(stat_res_fn.is_file());
2378 let stat_res_meth = check!(filename.metadata());
2379 assert!(stat_res_meth.is_file());
2380 check!(fs::remove_file(filename));
2384 fn file_test_stat_is_correct_on_is_dir() {
2385 let tmpdir = tmpdir();
2386 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2387 check!(fs::create_dir(filename));
2388 let stat_res_fn = check!(fs::metadata(filename));
2389 assert!(stat_res_fn.is_dir());
2390 let stat_res_meth = check!(filename.metadata());
2391 assert!(stat_res_meth.is_dir());
2392 check!(fs::remove_dir(filename));
2396 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2397 let tmpdir = tmpdir();
2398 let dir = &tmpdir.join("fileinfo_false_on_dir");
2399 check!(fs::create_dir(dir));
2400 assert!(!dir.is_file());
2401 check!(fs::remove_dir(dir));
2405 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2406 let tmpdir = tmpdir();
2407 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2408 check!(check!(File::create(file)).write(b"foo"));
2409 assert!(file.exists());
2410 check!(fs::remove_file(file));
2411 assert!(!file.exists());
2415 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2416 let tmpdir = tmpdir();
2417 let dir = &tmpdir.join("before_and_after_dir");
2418 assert!(!dir.exists());
2419 check!(fs::create_dir(dir));
2420 assert!(dir.exists());
2421 assert!(dir.is_dir());
2422 check!(fs::remove_dir(dir));
2423 assert!(!dir.exists());
2427 fn file_test_directoryinfo_readdir() {
2428 let tmpdir = tmpdir();
2429 let dir = &tmpdir.join("di_readdir");
2430 check!(fs::create_dir(dir));
2433 let f = dir.join(&format!("{}.txt", n));
2434 let mut w = check!(File::create(&f));
2435 let msg_str = format!("{}{}", prefix, n.to_string());
2436 let msg = msg_str.as_bytes();
2437 check!(w.write(msg));
2439 let files = check!(fs::read_dir(dir));
2440 let mut mem = [0; 4];
2442 let f = f.unwrap().path();
2444 let n = f.file_stem().unwrap();
2445 check!(check!(File::open(&f)).read(&mut mem));
2446 let read_str = str::from_utf8(&mem).unwrap();
2447 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2448 assert_eq!(expected, read_str);
2450 check!(fs::remove_file(&f));
2452 check!(fs::remove_dir(dir));
2456 fn file_create_new_already_exists_error() {
2457 let tmpdir = tmpdir();
2458 let file = &tmpdir.join("file_create_new_error_exists");
2459 check!(fs::File::create(file));
2460 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2461 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2465 fn mkdir_path_already_exists_error() {
2466 let tmpdir = tmpdir();
2467 let dir = &tmpdir.join("mkdir_error_twice");
2468 check!(fs::create_dir(dir));
2469 let e = fs::create_dir(dir).unwrap_err();
2470 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2474 fn recursive_mkdir() {
2475 let tmpdir = tmpdir();
2476 let dir = tmpdir.join("d1/d2");
2477 check!(fs::create_dir_all(&dir));
2478 assert!(dir.is_dir())
2482 fn recursive_mkdir_failure() {
2483 let tmpdir = tmpdir();
2484 let dir = tmpdir.join("d1");
2485 let file = dir.join("f1");
2487 check!(fs::create_dir_all(&dir));
2488 check!(File::create(&file));
2490 let result = fs::create_dir_all(&file);
2492 assert!(result.is_err());
2496 fn concurrent_recursive_mkdir() {
2499 let mut dir = dir.join("a");
2501 dir = dir.join("a");
2503 let mut join = vec!();
2505 let dir = dir.clone();
2506 join.push(thread::spawn(move || {
2507 check!(fs::create_dir_all(&dir));
2511 // No `Display` on result of `join()`
2512 join.drain(..).map(|join| join.join().unwrap()).count();
2517 fn recursive_mkdir_slash() {
2518 check!(fs::create_dir_all(Path::new("/")));
2522 fn recursive_mkdir_dot() {
2523 check!(fs::create_dir_all(Path::new(".")));
2527 fn recursive_mkdir_empty() {
2528 check!(fs::create_dir_all(Path::new("")));
2532 fn recursive_rmdir() {
2533 let tmpdir = tmpdir();
2534 let d1 = tmpdir.join("d1");
2535 let dt = d1.join("t");
2536 let dtt = dt.join("t");
2537 let d2 = tmpdir.join("d2");
2538 let canary = d2.join("do_not_delete");
2539 check!(fs::create_dir_all(&dtt));
2540 check!(fs::create_dir_all(&d2));
2541 check!(check!(File::create(&canary)).write(b"foo"));
2542 check!(symlink_junction(&d2, &dt.join("d2")));
2543 let _ = symlink_file(&canary, &d1.join("canary"));
2544 check!(fs::remove_dir_all(&d1));
2546 assert!(!d1.is_dir());
2547 assert!(canary.exists());
2551 fn recursive_rmdir_of_symlink() {
2552 // test we do not recursively delete a symlink but only dirs.
2553 let tmpdir = tmpdir();
2554 let link = tmpdir.join("d1");
2555 let dir = tmpdir.join("d2");
2556 let canary = dir.join("do_not_delete");
2557 check!(fs::create_dir_all(&dir));
2558 check!(check!(File::create(&canary)).write(b"foo"));
2559 check!(symlink_junction(&dir, &link));
2560 check!(fs::remove_dir_all(&link));
2562 assert!(!link.is_dir());
2563 assert!(canary.exists());
2567 // only Windows makes a distinction between file and directory symlinks.
2569 fn recursive_rmdir_of_file_symlink() {
2570 let tmpdir = tmpdir();
2571 if !got_symlink_permission(&tmpdir) { return };
2573 let f1 = tmpdir.join("f1");
2574 let f2 = tmpdir.join("f2");
2575 check!(check!(File::create(&f1)).write(b"foo"));
2576 check!(symlink_file(&f1, &f2));
2577 match fs::remove_dir_all(&f2) {
2578 Ok(..) => panic!("wanted a failure"),
2584 fn unicode_path_is_dir() {
2585 assert!(Path::new(".").is_dir());
2586 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2588 let tmpdir = tmpdir();
2590 let mut dirpath = tmpdir.path().to_path_buf();
2591 dirpath.push("test-가一ー你好");
2592 check!(fs::create_dir(&dirpath));
2593 assert!(dirpath.is_dir());
2595 let mut filepath = dirpath;
2596 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2597 check!(File::create(&filepath)); // ignore return; touch only
2598 assert!(!filepath.is_dir());
2599 assert!(filepath.exists());
2603 fn unicode_path_exists() {
2604 assert!(Path::new(".").exists());
2605 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2607 let tmpdir = tmpdir();
2608 let unicode = tmpdir.path();
2609 let unicode = unicode.join("test-각丁ー再见");
2610 check!(fs::create_dir(&unicode));
2611 assert!(unicode.exists());
2612 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2616 fn copy_file_does_not_exist() {
2617 let from = Path::new("test/nonexistent-bogus-path");
2618 let to = Path::new("test/other-bogus-path");
2620 match fs::copy(&from, &to) {
2623 assert!(!from.exists());
2624 assert!(!to.exists());
2630 fn copy_src_does_not_exist() {
2631 let tmpdir = tmpdir();
2632 let from = Path::new("test/nonexistent-bogus-path");
2633 let to = tmpdir.join("out.txt");
2634 check!(check!(File::create(&to)).write(b"hello"));
2635 assert!(fs::copy(&from, &to).is_err());
2636 assert!(!from.exists());
2637 let mut v = Vec::new();
2638 check!(check!(File::open(&to)).read_to_end(&mut v));
2639 assert_eq!(v, b"hello");
2644 let tmpdir = tmpdir();
2645 let input = tmpdir.join("in.txt");
2646 let out = tmpdir.join("out.txt");
2648 check!(check!(File::create(&input)).write(b"hello"));
2649 check!(fs::copy(&input, &out));
2650 let mut v = Vec::new();
2651 check!(check!(File::open(&out)).read_to_end(&mut v));
2652 assert_eq!(v, b"hello");
2654 assert_eq!(check!(input.metadata()).permissions(),
2655 check!(out.metadata()).permissions());
2659 fn copy_file_dst_dir() {
2660 let tmpdir = tmpdir();
2661 let out = tmpdir.join("out");
2663 check!(File::create(&out));
2664 match fs::copy(&*out, tmpdir.path()) {
2665 Ok(..) => panic!(), Err(..) => {}
2670 fn copy_file_dst_exists() {
2671 let tmpdir = tmpdir();
2672 let input = tmpdir.join("in");
2673 let output = tmpdir.join("out");
2675 check!(check!(File::create(&input)).write("foo".as_bytes()));
2676 check!(check!(File::create(&output)).write("bar".as_bytes()));
2677 check!(fs::copy(&input, &output));
2679 let mut v = Vec::new();
2680 check!(check!(File::open(&output)).read_to_end(&mut v));
2681 assert_eq!(v, b"foo".to_vec());
2685 fn copy_file_src_dir() {
2686 let tmpdir = tmpdir();
2687 let out = tmpdir.join("out");
2689 match fs::copy(tmpdir.path(), &out) {
2690 Ok(..) => panic!(), Err(..) => {}
2692 assert!(!out.exists());
2696 fn copy_file_preserves_perm_bits() {
2697 let tmpdir = tmpdir();
2698 let input = tmpdir.join("in.txt");
2699 let out = tmpdir.join("out.txt");
2701 let attr = check!(check!(File::create(&input)).metadata());
2702 let mut p = attr.permissions();
2703 p.set_readonly(true);
2704 check!(fs::set_permissions(&input, p));
2705 check!(fs::copy(&input, &out));
2706 assert!(check!(out.metadata()).permissions().readonly());
2707 check!(fs::set_permissions(&input, attr.permissions()));
2708 check!(fs::set_permissions(&out, attr.permissions()));
2713 fn copy_file_preserves_streams() {
2715 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2716 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2717 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2718 let mut v = Vec::new();
2719 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2720 assert_eq!(v, b"carrot".to_vec());
2724 fn copy_file_returns_metadata_len() {
2726 let in_path = tmp.join("in.txt");
2727 let out_path = tmp.join("out.txt");
2728 check!(check!(File::create(&in_path)).write(b"lettuce"));
2730 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2731 let copied_len = check!(fs::copy(&in_path, &out_path));
2732 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2736 fn symlinks_work() {
2737 let tmpdir = tmpdir();
2738 if !got_symlink_permission(&tmpdir) { return };
2740 let input = tmpdir.join("in.txt");
2741 let out = tmpdir.join("out.txt");
2743 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2744 check!(symlink_file(&input, &out));
2745 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2746 assert_eq!(check!(fs::metadata(&out)).len(),
2747 check!(fs::metadata(&input)).len());
2748 let mut v = Vec::new();
2749 check!(check!(File::open(&out)).read_to_end(&mut v));
2750 assert_eq!(v, b"foobar".to_vec());
2754 fn symlink_noexist() {
2755 // Symlinks can point to things that don't exist
2756 let tmpdir = tmpdir();
2757 if !got_symlink_permission(&tmpdir) { return };
2759 // Use a relative path for testing. Symlinks get normalized by Windows,
2760 // so we may not get the same path back for absolute paths
2761 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2762 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2769 // directory symlink
2770 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2773 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2774 r"C:\Users\Default");
2775 // junction with special permissions
2776 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2779 let tmpdir = tmpdir();
2780 let link = tmpdir.join("link");
2781 if !got_symlink_permission(&tmpdir) { return };
2782 check!(symlink_file(&"foo", &link));
2783 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2787 fn readlink_not_symlink() {
2788 let tmpdir = tmpdir();
2789 match fs::read_link(tmpdir.path()) {
2790 Ok(..) => panic!("wanted a failure"),
2797 let tmpdir = tmpdir();
2798 let input = tmpdir.join("in.txt");
2799 let out = tmpdir.join("out.txt");
2801 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2802 check!(fs::hard_link(&input, &out));
2803 assert_eq!(check!(fs::metadata(&out)).len(),
2804 check!(fs::metadata(&input)).len());
2805 assert_eq!(check!(fs::metadata(&out)).len(),
2806 check!(input.metadata()).len());
2807 let mut v = Vec::new();
2808 check!(check!(File::open(&out)).read_to_end(&mut v));
2809 assert_eq!(v, b"foobar".to_vec());
2811 // can't link to yourself
2812 match fs::hard_link(&input, &input) {
2813 Ok(..) => panic!("wanted a failure"),
2816 // can't link to something that doesn't exist
2817 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2818 Ok(..) => panic!("wanted a failure"),
2825 let tmpdir = tmpdir();
2826 let file = tmpdir.join("in.txt");
2828 check!(File::create(&file));
2829 let attr = check!(fs::metadata(&file));
2830 assert!(!attr.permissions().readonly());
2831 let mut p = attr.permissions();
2832 p.set_readonly(true);
2833 check!(fs::set_permissions(&file, p.clone()));
2834 let attr = check!(fs::metadata(&file));
2835 assert!(attr.permissions().readonly());
2837 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2838 Ok(..) => panic!("wanted an error"),
2842 p.set_readonly(false);
2843 check!(fs::set_permissions(&file, p));
2848 let tmpdir = tmpdir();
2849 let path = tmpdir.join("in.txt");
2851 let file = check!(File::create(&path));
2852 let attr = check!(fs::metadata(&path));
2853 assert!(!attr.permissions().readonly());
2854 let mut p = attr.permissions();
2855 p.set_readonly(true);
2856 check!(file.set_permissions(p.clone()));
2857 let attr = check!(fs::metadata(&path));
2858 assert!(attr.permissions().readonly());
2860 p.set_readonly(false);
2861 check!(file.set_permissions(p));
2865 fn sync_doesnt_kill_anything() {
2866 let tmpdir = tmpdir();
2867 let path = tmpdir.join("in.txt");
2869 let mut file = check!(File::create(&path));
2870 check!(file.sync_all());
2871 check!(file.sync_data());
2872 check!(file.write(b"foo"));
2873 check!(file.sync_all());
2874 check!(file.sync_data());
2878 fn truncate_works() {
2879 let tmpdir = tmpdir();
2880 let path = tmpdir.join("in.txt");
2882 let mut file = check!(File::create(&path));
2883 check!(file.write(b"foo"));
2884 check!(file.sync_all());
2886 // Do some simple things with truncation
2887 assert_eq!(check!(file.metadata()).len(), 3);
2888 check!(file.set_len(10));
2889 assert_eq!(check!(file.metadata()).len(), 10);
2890 check!(file.write(b"bar"));
2891 check!(file.sync_all());
2892 assert_eq!(check!(file.metadata()).len(), 10);
2894 let mut v = Vec::new();
2895 check!(check!(File::open(&path)).read_to_end(&mut v));
2896 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2898 // Truncate to a smaller length, don't seek, and then write something.
2899 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2900 // past the end of the file).
2901 check!(file.set_len(2));
2902 assert_eq!(check!(file.metadata()).len(), 2);
2903 check!(file.write(b"wut"));
2904 check!(file.sync_all());
2905 assert_eq!(check!(file.metadata()).len(), 9);
2906 let mut v = Vec::new();
2907 check!(check!(File::open(&path)).read_to_end(&mut v));
2908 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2913 use fs::OpenOptions as OO;
2914 fn c<T: Clone>(t: &T) -> T { t.clone() }
2916 let tmpdir = tmpdir();
2918 let mut r = OO::new(); r.read(true);
2919 let mut w = OO::new(); w.write(true);
2920 let mut rw = OO::new(); rw.read(true).write(true);
2921 let mut a = OO::new(); a.append(true);
2922 let mut ra = OO::new(); ra.read(true).append(true);
2925 let invalid_options = 87; // ERROR_INVALID_PARAMETER
2927 let invalid_options = "Invalid argument";
2929 // Test various combinations of creation modes and access modes.
2932 // creation mode | read | write | read-write | append | read-append |
2933 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2934 // not set (open existing) | X | X | X | X | X |
2935 // create | | X | X | X | X |
2936 // truncate | | X | X | | |
2937 // create and truncate | | X | X | | |
2938 // create_new | | X | X | X | X |
2940 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2943 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2944 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2945 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2946 check!(c(&w).create(true).open(&tmpdir.join("a")));
2947 check!(c(&w).open(&tmpdir.join("a")));
2950 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2951 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2952 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2953 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2954 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2957 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2958 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2959 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2960 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2961 check!(c(&rw).open(&tmpdir.join("c")));
2964 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2965 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2966 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2967 check!(c(&a).create(true).open(&tmpdir.join("d")));
2968 check!(c(&a).open(&tmpdir.join("d")));
2971 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2972 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2973 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2974 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2975 check!(c(&ra).open(&tmpdir.join("e")));
2977 // Test opening a file without setting an access mode
2978 let mut blank = OO::new();
2979 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2982 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2984 // Test write fails for read-only
2985 check!(r.open(&tmpdir.join("h")));
2987 let mut f = check!(r.open(&tmpdir.join("h")));
2988 assert!(f.write("wut".as_bytes()).is_err());
2991 // Test write overwrites
2993 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2994 check!(f.write("baz".as_bytes()));
2997 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2998 let mut b = vec![0; 6];
2999 check!(f.read(&mut b));
3000 assert_eq!(b, "bazbar".as_bytes());
3003 // Test truncate works
3005 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3006 check!(f.write("foo".as_bytes()));
3008 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3010 // Test append works
3011 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3013 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3014 check!(f.write("bar".as_bytes()));
3016 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3018 // Test .append(true) equals .write(true).append(true)
3020 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3021 check!(f.write("baz".as_bytes()));
3023 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3027 fn _assert_send_sync() {
3028 fn _assert_send_sync<T: Send + Sync>() {}
3029 _assert_send_sync::<OpenOptions>();
3034 let mut bytes = [0; 1024];
3035 StdRng::new().unwrap().fill_bytes(&mut bytes);
3037 let tmpdir = tmpdir();
3039 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3040 let mut v = Vec::new();
3041 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3042 assert!(v == &bytes[..]);
3046 fn write_then_read() {
3047 let mut bytes = [0; 1024];
3048 StdRng::new().unwrap().fill_bytes(&mut bytes);
3050 let tmpdir = tmpdir();
3052 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3053 let v = check!(fs::read(&tmpdir.join("test")));
3054 assert!(v == &bytes[..]);
3056 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3057 error_contains!(fs::read_string(&tmpdir.join("not-utf8")),
3058 "stream did not contain valid UTF-8");
3061 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3062 let string = check!(fs::read_string(&tmpdir.join("utf8")));
3063 assert_eq!(string, s);
3067 fn file_try_clone() {
3068 let tmpdir = tmpdir();
3070 let mut f1 = check!(OpenOptions::new()
3074 .open(&tmpdir.join("test")));
3075 let mut f2 = check!(f1.try_clone());
3077 check!(f1.write_all(b"hello world"));
3078 check!(f1.seek(SeekFrom::Start(2)));
3080 let mut buf = vec![];
3081 check!(f2.read_to_end(&mut buf));
3082 assert_eq!(buf, b"llo world");
3085 check!(f1.write_all(b"!"));
3089 #[cfg(not(windows))]
3090 fn unlink_readonly() {
3091 let tmpdir = tmpdir();
3092 let path = tmpdir.join("file");
3093 check!(File::create(&path));
3094 let mut perm = check!(fs::metadata(&path)).permissions();
3095 perm.set_readonly(true);
3096 check!(fs::set_permissions(&path, perm));
3097 check!(fs::remove_file(&path));
3101 fn mkdir_trailing_slash() {
3102 let tmpdir = tmpdir();
3103 let path = tmpdir.join("file");
3104 check!(fs::create_dir_all(&path.join("a/")));
3108 fn canonicalize_works_simple() {
3109 let tmpdir = tmpdir();
3110 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3111 let file = tmpdir.join("test");
3112 File::create(&file).unwrap();
3113 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3117 fn realpath_works() {
3118 let tmpdir = tmpdir();
3119 if !got_symlink_permission(&tmpdir) { return };
3121 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3122 let file = tmpdir.join("test");
3123 let dir = tmpdir.join("test2");
3124 let link = dir.join("link");
3125 let linkdir = tmpdir.join("test3");
3127 File::create(&file).unwrap();
3128 fs::create_dir(&dir).unwrap();
3129 symlink_file(&file, &link).unwrap();
3130 symlink_dir(&dir, &linkdir).unwrap();
3132 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3134 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3135 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3136 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3137 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3138 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3142 fn realpath_works_tricky() {
3143 let tmpdir = tmpdir();
3144 if !got_symlink_permission(&tmpdir) { return };
3146 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3147 let a = tmpdir.join("a");
3148 let b = a.join("b");
3149 let c = b.join("c");
3150 let d = a.join("d");
3151 let e = d.join("e");
3152 let f = a.join("f");
3154 fs::create_dir_all(&b).unwrap();
3155 fs::create_dir_all(&d).unwrap();
3156 File::create(&f).unwrap();
3157 if cfg!(not(windows)) {
3158 symlink_dir("../d/e", &c).unwrap();
3159 symlink_file("../f", &e).unwrap();
3162 symlink_dir(r"..\d\e", &c).unwrap();
3163 symlink_file(r"..\f", &e).unwrap();
3166 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3167 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3171 fn dir_entry_methods() {
3172 let tmpdir = tmpdir();
3174 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3175 File::create(&tmpdir.join("b")).unwrap();
3177 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3178 let fname = file.file_name();
3179 match fname.to_str() {
3181 assert!(file.file_type().unwrap().is_dir());
3182 assert!(file.metadata().unwrap().is_dir());
3185 assert!(file.file_type().unwrap().is_file());
3186 assert!(file.metadata().unwrap().is_file());
3188 f => panic!("unknown file name: {:?}", f),
3194 fn dir_entry_debug() {
3195 let tmpdir = tmpdir();
3196 File::create(&tmpdir.join("b")).unwrap();
3197 let mut read_dir = tmpdir.path().read_dir().unwrap();
3198 let dir_entry = read_dir.next().unwrap().unwrap();
3199 let actual = format!("{:?}", dir_entry);
3200 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3201 assert_eq!(actual, expected);
3205 fn read_dir_not_found() {
3206 let res = fs::read_dir("/path/that/does/not/exist");
3207 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3211 fn create_dir_all_with_junctions() {
3212 let tmpdir = tmpdir();
3213 let target = tmpdir.join("target");
3215 let junction = tmpdir.join("junction");
3216 let b = junction.join("a/b");
3218 let link = tmpdir.join("link");
3219 let d = link.join("c/d");
3221 fs::create_dir(&target).unwrap();
3223 check!(symlink_junction(&target, &junction));
3224 check!(fs::create_dir_all(&b));
3225 // the junction itself is not a directory, but `is_dir()` on a Path
3227 assert!(junction.is_dir());
3228 assert!(b.exists());
3230 if !got_symlink_permission(&tmpdir) { return };
3231 check!(symlink_dir(&target, &link));
3232 check!(fs::create_dir_all(&d));
3233 assert!(link.is_dir());
3234 assert!(d.exists());
3238 fn metadata_access_times() {
3239 let tmpdir = tmpdir();
3241 let b = tmpdir.join("b");
3242 File::create(&b).unwrap();
3244 let a = check!(fs::metadata(&tmpdir.path()));
3245 let b = check!(fs::metadata(&b));
3247 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3248 assert_eq!(check!(a.modified()), check!(a.modified()));
3249 assert_eq!(check!(b.accessed()), check!(b.modified()));
3251 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3252 check!(a.created());
3253 check!(b.created());