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, Write};
23 use path::{Path, PathBuf};
24 use sys::fs as fs_imp;
25 use sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
29 /// A reference to an open file on the filesystem.
31 /// An instance of a `File` can be read and/or written depending on what options
32 /// it was opened with. Files also implement `Seek` to alter the logical cursor
33 /// that the file contains internally.
35 /// Files are automatically closed when they go out of scope.
40 /// use std::io::prelude::*;
41 /// use std::fs::File;
43 /// # fn foo() -> std::io::Result<()> {
44 /// let mut f = try!(File::create("foo.txt"));
45 /// try!(f.write_all(b"Hello, world!"));
47 /// let mut f = try!(File::open("foo.txt"));
48 /// let mut s = String::new();
49 /// try!(f.read_to_string(&mut s));
50 /// assert_eq!(s, "Hello, world!");
54 #[stable(feature = "rust1", since = "1.0.0")]
59 /// Metadata information about a file.
61 /// This structure is returned from the `metadata` function or method and
62 /// represents known metadata about a file such as its permissions, size,
63 /// modification times, etc.
64 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct Metadata(fs_imp::FileAttr);
68 /// Iterator over the entries in a directory.
70 /// This iterator is returned from the `read_dir` function of this module and
71 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
72 /// information like the entry's path and possibly other metadata can be
77 /// This `io::Result` will be an `Err` if there's some sort of intermittent
78 /// IO error during iteration.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct ReadDir(fs_imp::ReadDir);
82 /// Entries returned by the `ReadDir` iterator.
84 /// An instance of `DirEntry` represents an entry inside of a directory on the
85 /// filesystem. Each entry can be inspected via methods to learn about the full
86 /// path or possibly other metadata through per-platform extension traits.
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct DirEntry(fs_imp::DirEntry);
90 /// Options and flags which can be used to configure how a file is opened.
92 /// This builder exposes the ability to configure how a `File` is opened and
93 /// what operations are permitted on the open file. The `File::open` and
94 /// `File::create` methods are aliases for commonly used options using this
97 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
98 /// then chain calls to methods to set each option, then call `open()`, passing
99 /// the path of the file you're trying to open. This will give you a
100 /// [`io::Result`][result] with a [`File`][file] inside that you can further
103 /// [result]: ../io/type.Result.html
104 /// [file]: struct.File.html
108 /// Opening a file to read:
111 /// use std::fs::OpenOptions;
113 /// let file = OpenOptions::new().read(true).open("foo.txt");
116 /// Opening a file for both reading and writing, as well as creating it if it
120 /// use std::fs::OpenOptions;
122 /// let file = OpenOptions::new()
126 /// .open("foo.txt");
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub struct OpenOptions(fs_imp::OpenOptions);
132 /// Representation of the various permissions on a file.
134 /// This module only currently provides one bit of information, `readonly`,
135 /// which is exposed on all currently supported platforms. Unix-specific
136 /// functionality, such as mode bits, is available through the
137 /// `os::unix::PermissionsExt` trait.
138 #[derive(Clone, PartialEq, Eq, Debug)]
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub struct Permissions(fs_imp::FilePermissions);
142 /// An structure representing a type of file with accessors for each file type.
143 #[stable(feature = "file_type", since = "1.1.0")]
144 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
145 pub struct FileType(fs_imp::FileType);
147 /// A builder used to create directories in various manners.
149 /// This builder also supports platform-specific options.
150 #[stable(feature = "dir_builder", since = "1.6.0")]
151 pub struct DirBuilder {
152 inner: fs_imp::DirBuilder,
157 /// Attempts to open a file in read-only mode.
159 /// See the `OpenOptions::open` method for more details.
163 /// This function will return an error if `path` does not already exist.
164 /// Other errors may also be returned according to `OpenOptions::open`.
169 /// use std::fs::File;
171 /// # fn foo() -> std::io::Result<()> {
172 /// let mut f = try!(File::open("foo.txt"));
176 #[stable(feature = "rust1", since = "1.0.0")]
177 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
178 OpenOptions::new().read(true).open(path.as_ref())
181 /// Opens a file in write-only mode.
183 /// This function will create a file if it does not exist,
184 /// and will truncate it if it does.
186 /// See the `OpenOptions::open` function for more details.
191 /// use std::fs::File;
193 /// # fn foo() -> std::io::Result<()> {
194 /// let mut f = try!(File::create("foo.txt"));
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
200 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
203 /// Attempts to sync all OS-internal metadata to disk.
205 /// This function will attempt to ensure that all in-core data reaches the
206 /// filesystem before returning.
211 /// use std::fs::File;
212 /// use std::io::prelude::*;
214 /// # fn foo() -> std::io::Result<()> {
215 /// let mut f = try!(File::create("foo.txt"));
216 /// try!(f.write_all(b"Hello, world!"));
218 /// try!(f.sync_all());
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn sync_all(&self) -> io::Result<()> {
227 /// This function is similar to `sync_all`, except that it may not
228 /// synchronize file metadata to the filesystem.
230 /// This is intended for use cases that must synchronize content, but don't
231 /// need the metadata on disk. The goal of this method is to reduce disk
234 /// Note that some platforms may simply implement this in terms of
240 /// use std::fs::File;
241 /// use std::io::prelude::*;
243 /// # fn foo() -> std::io::Result<()> {
244 /// let mut f = try!(File::create("foo.txt"));
245 /// try!(f.write_all(b"Hello, world!"));
247 /// try!(f.sync_data());
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn sync_data(&self) -> io::Result<()> {
253 self.inner.datasync()
256 /// Truncates or extends the underlying file, updating the size of
257 /// this file to become `size`.
259 /// If the `size` is less than the current file's size, then the file will
260 /// be shrunk. If it is greater than the current file's size, then the file
261 /// will be extended to `size` and have all of the intermediate data filled
266 /// This function will return an error if the file is not opened for writing.
271 /// use std::fs::File;
273 /// # fn foo() -> std::io::Result<()> {
274 /// let mut f = try!(File::create("foo.txt"));
275 /// try!(f.set_len(10));
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn set_len(&self, size: u64) -> io::Result<()> {
281 self.inner.truncate(size)
284 /// Queries metadata about the underlying file.
289 /// use std::fs::File;
291 /// # fn foo() -> std::io::Result<()> {
292 /// let mut f = try!(File::open("foo.txt"));
293 /// let metadata = try!(f.metadata());
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn metadata(&self) -> io::Result<Metadata> {
299 self.inner.file_attr().map(Metadata)
302 /// Creates a new independently owned handle to the underlying file.
304 /// The returned `File` is a reference to the same state that this object
305 /// references. Both handles will read and write with the same cursor
307 #[stable(feature = "file_try_clone", since = "1.9.0")]
308 pub fn try_clone(&self) -> io::Result<File> {
310 inner: self.inner.duplicate()?
315 impl AsInner<fs_imp::File> for File {
316 fn as_inner(&self) -> &fs_imp::File { &self.inner }
318 impl FromInner<fs_imp::File> for File {
319 fn from_inner(f: fs_imp::File) -> File {
323 impl IntoInner<fs_imp::File> for File {
324 fn into_inner(self) -> fs_imp::File {
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl fmt::Debug for File {
331 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336 #[stable(feature = "rust1", since = "1.0.0")]
338 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
341 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
342 self.inner.read_to_end(buf)
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl Write for File {
347 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
348 self.inner.write(buf)
350 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
352 #[stable(feature = "rust1", since = "1.0.0")]
354 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<'a> Read for &'a File {
360 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
363 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
364 self.inner.read_to_end(buf)
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<'a> Write for &'a File {
369 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
370 self.inner.write(buf)
372 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<'a> Seek for &'a File {
376 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
382 /// Creates a blank new set of options ready for configuration.
384 /// All options are initially set to `false`.
389 /// use std::fs::OpenOptions;
391 /// let mut options = OpenOptions::new();
392 /// let file = options.read(true).open("foo.txt");
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn new() -> OpenOptions {
396 OpenOptions(fs_imp::OpenOptions::new())
399 /// Sets the option for read access.
401 /// This option, when true, will indicate that the file should be
402 /// `read`-able if opened.
407 /// use std::fs::OpenOptions;
409 /// let file = OpenOptions::new().read(true).open("foo.txt");
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
413 self.0.read(read); self
416 /// Sets the option for write access.
418 /// This option, when true, will indicate that the file should be
419 /// `write`-able if opened.
421 /// If the file already exists, any write calls on it will overwrite its
422 /// contents, without truncating it.
427 /// use std::fs::OpenOptions;
429 /// let file = OpenOptions::new().write(true).open("foo.txt");
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
433 self.0.write(write); self
436 /// Sets the option for the append mode.
438 /// This option, when true, means that writes will append to a file instead
439 /// of overwriting previous contents.
440 /// Note that setting `.write(true).append(true)` has the same effect as
441 /// setting only `.append(true)`.
443 /// For most filesystems, the operating system guarantees that all writes are
444 /// atomic: no writes get mangled because another process writes at the same
447 /// One maybe obvious note when using append-mode: make sure that all data
448 /// that belongs together is written to the file in one operation. This
449 /// can be done by concatenating strings before passing them to `write()`,
450 /// or using a buffered writer (with a buffer of adequate size),
451 /// and calling `flush()` when the message is complete.
453 /// If a file is opened with both read and append access, beware that after
454 /// opening, and after every write, the position for reading may be set at the
455 /// end of the file. So, before writing, save the current position (using
456 /// `seek(SeekFrom::Current(0))`, and restore it before the next read.
461 /// use std::fs::OpenOptions;
463 /// let file = OpenOptions::new().append(true).open("foo.txt");
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
467 self.0.append(append); self
470 /// Sets the option for truncating a previous file.
472 /// If a file is successfully opened with this option set it will truncate
473 /// the file to 0 length if it already exists.
475 /// The file must be opened with write access for truncate to work.
480 /// use std::fs::OpenOptions;
482 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
486 self.0.truncate(truncate); self
489 /// Sets the option for creating a new file.
491 /// This option indicates whether a new file will be created if the file
492 /// does not yet already exist.
494 /// In order for the file to be created, `write` or `append` access must
500 /// use std::fs::OpenOptions;
502 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
506 self.0.create(create); self
509 /// Sets the option to always create a new file.
511 /// This option indicates whether a new file will be created.
512 /// No file is allowed to exist at the target location, also no (dangling)
515 /// This option is useful because it is atomic. Otherwise between checking
516 /// whether a file exists and creating a new one, the file may have been
517 /// created by another process (a TOCTOU race condition / attack).
519 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are
522 /// The file must be opened with write or append access in order to create
528 /// use std::fs::OpenOptions;
530 /// let file = OpenOptions::new().write(true)
531 /// .create_new(true)
532 /// .open("foo.txt");
534 #[stable(feature = "expand_open_options2", since = "1.9.0")]
535 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
536 self.0.create_new(create_new); self
539 /// Opens a file at `path` with the options specified by `self`.
543 /// This function will return an error under a number of different
544 /// circumstances, to include but not limited to:
546 /// * Opening a file that does not exist without setting `create` or
548 /// * Attempting to open a file with access that the user lacks
550 /// * Filesystem-level errors (full disk, etc)
551 /// * Invalid combinations of open options (truncate without write access,
552 /// no access mode set, etc)
557 /// use std::fs::OpenOptions;
559 /// let file = OpenOptions::new().open("foo.txt");
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
563 self._open(path.as_ref())
566 fn _open(&self, path: &Path) -> io::Result<File> {
567 let inner = fs_imp::File::open(path, &self.0)?;
568 Ok(File { inner: inner })
572 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
573 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
577 /// Returns the file type for this metadata.
578 #[stable(feature = "file_type", since = "1.1.0")]
579 pub fn file_type(&self) -> FileType {
580 FileType(self.0.file_type())
583 /// Returns whether this metadata is for a directory.
588 /// # fn foo() -> std::io::Result<()> {
591 /// let metadata = try!(fs::metadata("foo.txt"));
593 /// assert!(!metadata.is_dir());
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
600 /// Returns whether this metadata is for a regular file.
605 /// # fn foo() -> std::io::Result<()> {
608 /// let metadata = try!(fs::metadata("foo.txt"));
610 /// assert!(metadata.is_file());
614 #[stable(feature = "rust1", since = "1.0.0")]
615 pub fn is_file(&self) -> bool { self.file_type().is_file() }
617 /// Returns the size of the file, in bytes, this metadata is for.
622 /// # fn foo() -> std::io::Result<()> {
625 /// let metadata = try!(fs::metadata("foo.txt"));
627 /// assert_eq!(0, metadata.len());
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn len(&self) -> u64 { self.0.size() }
634 /// Returns the permissions of the file this metadata is for.
639 /// # fn foo() -> std::io::Result<()> {
642 /// let metadata = try!(fs::metadata("foo.txt"));
644 /// assert!(!metadata.permissions().readonly());
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn permissions(&self) -> Permissions {
650 Permissions(self.0.perm())
653 /// Returns the last modification time listed in this metadata.
655 /// The returned value corresponds to the `mtime` field of `stat` on Unix
656 /// platforms and the `ftLastWriteTime` field on Windows platforms.
660 /// This field may not be available on all platforms, and will return an
661 /// `Err` on platforms where it is not available.
662 #[stable(feature = "fs_time", since = "1.10.0")]
663 pub fn modified(&self) -> io::Result<SystemTime> {
664 self.0.modified().map(FromInner::from_inner)
667 /// Returns the last access time of this metadata.
669 /// The returned value corresponds to the `atime` field of `stat` on Unix
670 /// platforms and the `ftLastAccessTime` field on Windows platforms.
672 /// Note that not all platforms will keep this field update in a file's
673 /// metadata, for example Windows has an option to disable updating this
674 /// time when files are accessed and Linux similarly has `noatime`.
678 /// This field may not be available on all platforms, and will return an
679 /// `Err` on platforms where it is not available.
680 #[stable(feature = "fs_time", since = "1.10.0")]
681 pub fn accessed(&self) -> io::Result<SystemTime> {
682 self.0.accessed().map(FromInner::from_inner)
685 /// Returns the creation time listed in the this metadata.
687 /// The returned value corresponds to the `birthtime` field of `stat` on
688 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
692 /// This field may not be available on all platforms, and will return an
693 /// `Err` on platforms where it is not available.
694 #[stable(feature = "fs_time", since = "1.10.0")]
695 pub fn created(&self) -> io::Result<SystemTime> {
696 self.0.created().map(FromInner::from_inner)
700 impl AsInner<fs_imp::FileAttr> for Metadata {
701 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
705 /// Returns whether these permissions describe a readonly file.
710 /// use std::fs::File;
712 /// # fn foo() -> std::io::Result<()> {
713 /// let mut f = try!(File::create("foo.txt"));
714 /// let metadata = try!(f.metadata());
716 /// assert_eq!(false, metadata.permissions().readonly());
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn readonly(&self) -> bool { self.0.readonly() }
723 /// Modifies the readonly flag for this set of permissions.
725 /// This operation does **not** modify the filesystem. To modify the
726 /// filesystem use the `fs::set_permissions` function.
731 /// use std::fs::File;
733 /// # fn foo() -> std::io::Result<()> {
734 /// let f = try!(File::create("foo.txt"));
735 /// let metadata = try!(f.metadata());
736 /// let mut permissions = metadata.permissions();
738 /// permissions.set_readonly(true);
740 /// // filesystem doesn't change
741 /// assert_eq!(false, metadata.permissions().readonly());
743 /// // just this particular `permissions`.
744 /// assert_eq!(true, permissions.readonly());
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn set_readonly(&mut self, readonly: bool) {
750 self.0.set_readonly(readonly)
755 /// Test whether this file type represents a directory.
756 #[stable(feature = "file_type", since = "1.1.0")]
757 pub fn is_dir(&self) -> bool { self.0.is_dir() }
759 /// Test whether this file type represents a regular file.
760 #[stable(feature = "file_type", since = "1.1.0")]
761 pub fn is_file(&self) -> bool { self.0.is_file() }
763 /// Test whether this file type represents a symbolic link.
764 #[stable(feature = "file_type", since = "1.1.0")]
765 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
768 impl AsInner<fs_imp::FileType> for FileType {
769 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
772 impl FromInner<fs_imp::FilePermissions> for Permissions {
773 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
778 impl AsInner<fs_imp::FilePermissions> for Permissions {
779 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl Iterator for ReadDir {
784 type Item = io::Result<DirEntry>;
786 fn next(&mut self) -> Option<io::Result<DirEntry>> {
787 self.0.next().map(|entry| entry.map(DirEntry))
792 /// Returns the full path to the file that this entry represents.
794 /// The full path is created by joining the original path to `read_dir` or
795 /// `walk_dir` with the filename of this entry.
801 /// # fn foo() -> std::io::Result<()> {
802 /// for entry in try!(fs::read_dir(".")) {
803 /// let dir = try!(entry);
804 /// println!("{:?}", dir.path());
810 /// This prints output like:
815 /// "./hello_world.rs"
818 /// The exact text, of course, depends on what files you have in `.`.
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn path(&self) -> PathBuf { self.0.path() }
822 /// Return the metadata for the file that this entry points at.
824 /// This function will not traverse symlinks if this entry points at a
827 /// # Platform-specific behavior
829 /// On Windows this function is cheap to call (no extra system calls
830 /// needed), but on Unix platforms this function is the equivalent of
831 /// calling `symlink_metadata` on the path.
832 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
833 pub fn metadata(&self) -> io::Result<Metadata> {
834 self.0.metadata().map(Metadata)
837 /// Return the file type for the file that this entry points at.
839 /// This function will not traverse symlinks if this entry points at a
842 /// # Platform-specific behavior
844 /// On Windows and most Unix platforms this function is free (no extra
845 /// system calls needed), but some Unix platforms may require the equivalent
846 /// call to `symlink_metadata` to learn about the target file type.
847 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
848 pub fn file_type(&self) -> io::Result<FileType> {
849 self.0.file_type().map(FileType)
852 /// Returns the bare file name of this directory entry without any other
853 /// leading path component.
854 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
855 pub fn file_name(&self) -> OsString {
860 impl AsInner<fs_imp::DirEntry> for DirEntry {
861 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
864 /// Removes a file from the filesystem.
866 /// Note that there is no
867 /// guarantee that the file is immediately deleted (e.g. depending on
868 /// platform, other open file descriptors may prevent immediate removal).
870 /// # Platform-specific behavior
872 /// This function currently corresponds to the `unlink` function on Unix
873 /// and the `DeleteFile` function on Windows.
874 /// Note that, this [may change in the future][changes].
875 /// [changes]: ../io/index.html#platform-specific-behavior
879 /// This function will return an error in the following situations, but is not
880 /// limited to just these cases:
882 /// * `path` points to a directory.
883 /// * The user lacks permissions to remove the file.
890 /// # fn foo() -> std::io::Result<()> {
891 /// try!(fs::remove_file("a.txt"));
895 #[stable(feature = "rust1", since = "1.0.0")]
896 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
897 fs_imp::unlink(path.as_ref())
900 /// Given a path, query the file system to get information about a file,
903 /// This function will traverse symbolic links to query information about the
904 /// destination file.
906 /// # Platform-specific behavior
908 /// This function currently corresponds to the `stat` function on Unix
909 /// and the `GetFileAttributesEx` function on Windows.
910 /// Note that, this [may change in the future][changes].
911 /// [changes]: ../io/index.html#platform-specific-behavior
915 /// This function will return an error in the following situations, but is not
916 /// limited to just these cases:
918 /// * The user lacks permissions to perform `metadata` call on `path`.
919 /// * `path` does not exist.
924 /// # fn foo() -> std::io::Result<()> {
927 /// let attr = try!(fs::metadata("/some/file/path.txt"));
928 /// // inspect attr ...
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
934 fs_imp::stat(path.as_ref()).map(Metadata)
937 /// Query the metadata about a file without following symlinks.
939 /// # Platform-specific behavior
941 /// This function currently corresponds to the `lstat` function on Unix
942 /// and the `GetFileAttributesEx` function on Windows.
943 /// Note that, this [may change in the future][changes].
944 /// [changes]: ../io/index.html#platform-specific-behavior
948 /// This function will return an error in the following situations, but is not
949 /// limited to just these cases:
951 /// * The user lacks permissions to perform `metadata` call on `path`.
952 /// * `path` does not exist.
957 /// # fn foo() -> std::io::Result<()> {
960 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
961 /// // inspect attr ...
965 #[stable(feature = "symlink_metadata", since = "1.1.0")]
966 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
967 fs_imp::lstat(path.as_ref()).map(Metadata)
970 /// Rename a file or directory to a new name, replacing the original file if
971 /// `to` already exists.
973 /// This will not work if the new name is on a different mount point.
975 /// # Platform-specific behavior
977 /// This function currently corresponds to the `rename` function on Unix
978 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
980 /// Because of this, the behavior when both `from` and `to` exist differs. On
981 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
982 /// `from` is not a directory, `to` must also be not a directory. In contrast,
983 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
985 /// Note that, this [may change in the future][changes].
986 /// [changes]: ../io/index.html#platform-specific-behavior
990 /// This function will return an error in the following situations, but is not
991 /// limited to just these cases:
993 /// * `from` does not exist.
994 /// * The user lacks permissions to view contents.
995 /// * `from` and `to` are on separate filesystems.
1002 /// # fn foo() -> std::io::Result<()> {
1003 /// try!(fs::rename("a.txt", "b.txt")); // Rename a.txt to b.txt
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1009 fs_imp::rename(from.as_ref(), to.as_ref())
1012 /// Copies the contents of one file to another. This function will also
1013 /// copy the permission bits of the original file to the destination file.
1015 /// This function will **overwrite** the contents of `to`.
1017 /// Note that if `from` and `to` both point to the same file, then the file
1018 /// will likely get truncated by this operation.
1020 /// On success, the total number of bytes copied is returned.
1022 /// # Platform-specific behavior
1024 /// This function currently corresponds to the `open` function in Unix
1025 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1026 /// `O_CLOEXEC` is set for returned file descriptors.
1027 /// On Windows, this function currently corresponds to `CopyFileEx`.
1028 /// Note that, this [may change in the future][changes].
1029 /// [changes]: ../io/index.html#platform-specific-behavior
1033 /// This function will return an error in the following situations, but is not
1034 /// limited to just these cases:
1036 /// * The `from` path is not a file.
1037 /// * The `from` file does not exist.
1038 /// * The current process does not have the permission rights to access
1039 /// `from` or write `to`.
1046 /// # fn foo() -> std::io::Result<()> {
1047 /// try!(fs::copy("foo.txt", "bar.txt")); // Copy foo.txt to bar.txt
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1052 fs_imp::copy(from.as_ref(), to.as_ref())
1055 /// Creates a new hard link on the filesystem.
1057 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1058 /// often require these two paths to both be located on the same filesystem.
1060 /// # Platform-specific behavior
1062 /// This function currently corresponds to the `link` function on Unix
1063 /// and the `CreateHardLink` function on Windows.
1064 /// Note that, this [may change in the future][changes].
1065 /// [changes]: ../io/index.html#platform-specific-behavior
1069 /// This function will return an error in the following situations, but is not
1070 /// limited to just these cases:
1072 /// * The `src` path is not a file or doesn't exist.
1079 /// # fn foo() -> std::io::Result<()> {
1080 /// try!(fs::hard_link("a.txt", "b.txt")); // Hard link a.txt to b.txt
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1086 fs_imp::link(src.as_ref(), dst.as_ref())
1089 /// Creates a new symbolic link on the filesystem.
1091 /// The `dst` path will be a symbolic link pointing to the `src` path.
1092 /// On Windows, this will be a file symlink, not a directory symlink;
1093 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1094 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1095 /// used instead to make the intent explicit.
1102 /// # fn foo() -> std::io::Result<()> {
1103 /// try!(fs::soft_link("a.txt", "b.txt"));
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 #[rustc_deprecated(since = "1.1.0",
1109 reason = "replaced with std::os::unix::fs::symlink and \
1110 std::os::windows::fs::{symlink_file, symlink_dir}")]
1111 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1112 fs_imp::symlink(src.as_ref(), dst.as_ref())
1115 /// Reads a symbolic link, returning the file that the link points to.
1117 /// # Platform-specific behavior
1119 /// This function currently corresponds to the `readlink` function on Unix
1120 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1121 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1122 /// Note that, this [may change in the future][changes].
1123 /// [changes]: ../io/index.html#platform-specific-behavior
1127 /// This function will return an error in the following situations, but is not
1128 /// limited to just these cases:
1130 /// * `path` is not a symbolic link.
1131 /// * `path` does not exist.
1138 /// # fn foo() -> std::io::Result<()> {
1139 /// let path = try!(fs::read_link("a.txt"));
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1145 fs_imp::readlink(path.as_ref())
1148 /// Returns the canonical form of a path with all intermediate components
1149 /// normalized and symbolic links resolved.
1151 /// # Platform-specific behavior
1153 /// This function currently corresponds to the `realpath` function on Unix
1154 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1155 /// Note that, this [may change in the future][changes].
1156 /// [changes]: ../io/index.html#platform-specific-behavior
1160 /// This function will return an error in the following situations, but is not
1161 /// limited to just these cases:
1163 /// * `path` does not exist.
1164 /// * A component in path is not a directory.
1171 /// # fn foo() -> std::io::Result<()> {
1172 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
1176 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1177 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1178 fs_imp::canonicalize(path.as_ref())
1181 /// Creates a new, empty directory at the provided path
1183 /// # Platform-specific behavior
1185 /// This function currently corresponds to the `mkdir` function on Unix
1186 /// and the `CreateDirectory` function on Windows.
1187 /// Note that, this [may change in the future][changes].
1188 /// [changes]: ../io/index.html#platform-specific-behavior
1192 /// This function will return an error in the following situations, but is not
1193 /// limited to just these cases:
1195 /// * User lacks permissions to create directory at `path`.
1196 /// * `path` already exists.
1203 /// # fn foo() -> std::io::Result<()> {
1204 /// try!(fs::create_dir("/some/dir"));
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1210 DirBuilder::new().create(path.as_ref())
1213 /// Recursively create a directory and all of its parent components if they
1216 /// # Platform-specific behavior
1218 /// This function currently corresponds to the `mkdir` function on Unix
1219 /// and the `CreateDirectory` function on Windows.
1220 /// Note that, this [may change in the future][changes].
1221 /// [changes]: ../io/index.html#platform-specific-behavior
1225 /// This function will return an error in the following situations, but is not
1226 /// limited to just these cases:
1228 /// * If any directory in the path specified by `path`
1229 /// does not already exist and it could not be created otherwise. The specific
1230 /// error conditions for when a directory is being created (after it is
1231 /// determined to not exist) are outlined by `fs::create_dir`.
1238 /// # fn foo() -> std::io::Result<()> {
1239 /// try!(fs::create_dir_all("/some/dir"));
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1245 DirBuilder::new().recursive(true).create(path.as_ref())
1248 /// Removes an existing, empty directory.
1250 /// # Platform-specific behavior
1252 /// This function currently corresponds to the `rmdir` function on Unix
1253 /// and the `RemoveDirectory` function on Windows.
1254 /// Note that, this [may change in the future][changes].
1255 /// [changes]: ../io/index.html#platform-specific-behavior
1259 /// This function will return an error in the following situations, but is not
1260 /// limited to just these cases:
1262 /// * The user lacks permissions to remove the directory at the provided `path`.
1263 /// * The directory isn't empty.
1270 /// # fn foo() -> std::io::Result<()> {
1271 /// try!(fs::remove_dir("/some/dir"));
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1277 fs_imp::rmdir(path.as_ref())
1280 /// Removes a directory at this path, after removing all its contents. Use
1283 /// This function does **not** follow symbolic links and it will simply remove the
1284 /// symbolic link itself.
1286 /// # Platform-specific behavior
1288 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1289 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1291 /// Note that, this [may change in the future][changes].
1292 /// [changes]: ../io/index.html#platform-specific-behavior
1296 /// See `file::remove_file` and `fs::remove_dir`.
1303 /// # fn foo() -> std::io::Result<()> {
1304 /// try!(fs::remove_dir_all("/some/dir"));
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1310 fs_imp::remove_dir_all(path.as_ref())
1313 /// Returns an iterator over the entries within a directory.
1315 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1316 /// be encountered after an iterator is initially constructed.
1318 /// # Platform-specific behavior
1320 /// This function currently corresponds to the `opendir` function on Unix
1321 /// and the `FindFirstFile` function on Windows.
1322 /// Note that, this [may change in the future][changes].
1323 /// [changes]: ../io/index.html#platform-specific-behavior
1327 /// This function will return an error in the following situations, but is not
1328 /// limited to just these cases:
1330 /// * The provided `path` doesn't exist.
1331 /// * The process lacks permissions to view the contents.
1332 /// * The `path` points at a non-directory file.
1338 /// use std::fs::{self, DirEntry};
1339 /// use std::path::Path;
1341 /// // one possible implementation of walking a directory only visiting files
1342 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1343 /// if dir.is_dir() {
1344 /// for entry in try!(fs::read_dir(dir)) {
1345 /// let entry = try!(entry);
1346 /// let path = entry.path();
1347 /// if path.is_dir() {
1348 /// try!(visit_dirs(&path, cb));
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1359 fs_imp::readdir(path.as_ref()).map(ReadDir)
1362 /// Changes the permissions found on a file or a directory.
1364 /// # Platform-specific behavior
1366 /// This function currently corresponds to the `chmod` function on Unix
1367 /// and the `SetFileAttributes` function on Windows.
1368 /// Note that, this [may change in the future][changes].
1369 /// [changes]: ../io/index.html#platform-specific-behavior
1373 /// This function will return an error in the following situations, but is not
1374 /// limited to just these cases:
1376 /// * `path` does not exist.
1377 /// * The user lacks the permission to change attributes of the file.
1382 /// # fn foo() -> std::io::Result<()> {
1385 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1386 /// perms.set_readonly(true);
1387 /// try!(fs::set_permissions("foo.txt", perms));
1391 #[stable(feature = "set_permissions", since = "1.1.0")]
1392 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1394 fs_imp::set_perm(path.as_ref(), perm.0)
1398 /// Creates a new set of options with default mode/security settings for all
1399 /// platforms and also non-recursive.
1400 #[stable(feature = "dir_builder", since = "1.6.0")]
1401 pub fn new() -> DirBuilder {
1403 inner: fs_imp::DirBuilder::new(),
1408 /// Indicate that directories create should be created recursively, creating
1409 /// all parent directories if they do not exist with the same security and
1410 /// permissions settings.
1412 /// This option defaults to `false`
1413 #[stable(feature = "dir_builder", since = "1.6.0")]
1414 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1415 self.recursive = recursive;
1419 /// Create the specified directory with the options configured in this
1425 /// use std::fs::{self, DirBuilder};
1427 /// let path = "/tmp/foo/bar/baz";
1428 /// DirBuilder::new()
1429 /// .recursive(true)
1430 /// .create(path).unwrap();
1432 /// assert!(fs::metadata(path).unwrap().is_dir());
1434 #[stable(feature = "dir_builder", since = "1.6.0")]
1435 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1436 self._create(path.as_ref())
1439 fn _create(&self, path: &Path) -> io::Result<()> {
1441 self.create_dir_all(path)
1443 self.inner.mkdir(path)
1447 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1448 if path == Path::new("") || path.is_dir() { return Ok(()) }
1449 if let Some(p) = path.parent() {
1450 self.create_dir_all(p)?
1452 self.inner.mkdir(path)
1456 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1457 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1467 use fs::{self, File, OpenOptions};
1468 use io::{ErrorKind, SeekFrom};
1470 use rand::{StdRng, Rng};
1472 use sys_common::io::test::{TempDir, tmpdir};
1475 use os::windows::fs::{symlink_dir, symlink_file};
1477 use sys::fs::symlink_junction;
1479 use os::unix::fs::symlink as symlink_dir;
1481 use os::unix::fs::symlink as symlink_file;
1483 use os::unix::fs::symlink as symlink_junction;
1485 macro_rules! check { ($e:expr) => (
1488 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1492 macro_rules! error { ($e:expr, $s:expr) => (
1494 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1495 Err(ref err) => assert!(err.to_string().contains($s),
1496 format!("`{}` did not contain `{}`", err, $s))
1500 // Several test fail on windows if the user does not have permission to
1501 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
1502 // disabling these test on Windows, use this function to test whether we
1503 // have permission, and return otherwise. This way, we still don't run these
1504 // tests most of the time, but at least we do if the user has the right
1506 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
1507 if cfg!(unix) { return true }
1508 let link = tmpdir.join("some_hopefully_unique_link_name");
1510 match symlink_file(r"nonexisting_target", link) {
1513 if err.to_string().contains("A required privilege is not held by the client.") {
1522 fn file_test_io_smoke_test() {
1523 let message = "it's alright. have a good time";
1524 let tmpdir = tmpdir();
1525 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1527 let mut write_stream = check!(File::create(filename));
1528 check!(write_stream.write(message.as_bytes()));
1531 let mut read_stream = check!(File::open(filename));
1532 let mut read_buf = [0; 1028];
1533 let read_str = match check!(read_stream.read(&mut read_buf)) {
1534 0 => panic!("shouldn't happen"),
1535 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1537 assert_eq!(read_str, message);
1539 check!(fs::remove_file(filename));
1543 fn invalid_path_raises() {
1544 let tmpdir = tmpdir();
1545 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1546 let result = File::open(filename);
1549 error!(result, "No such file or directory");
1552 error!(result, "The system cannot find the file specified");
1557 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1558 let tmpdir = tmpdir();
1559 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1561 let result = fs::remove_file(filename);
1564 error!(result, "No such file or directory");
1567 error!(result, "The system cannot find the file specified");
1572 fn file_test_io_non_positional_read() {
1573 let message: &str = "ten-four";
1574 let mut read_mem = [0; 8];
1575 let tmpdir = tmpdir();
1576 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1578 let mut rw_stream = check!(File::create(filename));
1579 check!(rw_stream.write(message.as_bytes()));
1582 let mut read_stream = check!(File::open(filename));
1584 let read_buf = &mut read_mem[0..4];
1585 check!(read_stream.read(read_buf));
1588 let read_buf = &mut read_mem[4..8];
1589 check!(read_stream.read(read_buf));
1592 check!(fs::remove_file(filename));
1593 let read_str = str::from_utf8(&read_mem).unwrap();
1594 assert_eq!(read_str, message);
1598 fn file_test_io_seek_and_tell_smoke_test() {
1599 let message = "ten-four";
1600 let mut read_mem = [0; 4];
1601 let set_cursor = 4 as u64;
1602 let tell_pos_pre_read;
1603 let tell_pos_post_read;
1604 let tmpdir = tmpdir();
1605 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1607 let mut rw_stream = check!(File::create(filename));
1608 check!(rw_stream.write(message.as_bytes()));
1611 let mut read_stream = check!(File::open(filename));
1612 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1613 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1614 check!(read_stream.read(&mut read_mem));
1615 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1617 check!(fs::remove_file(filename));
1618 let read_str = str::from_utf8(&read_mem).unwrap();
1619 assert_eq!(read_str, &message[4..8]);
1620 assert_eq!(tell_pos_pre_read, set_cursor);
1621 assert_eq!(tell_pos_post_read, message.len() as u64);
1625 fn file_test_io_seek_and_write() {
1626 let initial_msg = "food-is-yummy";
1627 let overwrite_msg = "-the-bar!!";
1628 let final_msg = "foo-the-bar!!";
1630 let mut read_mem = [0; 13];
1631 let tmpdir = tmpdir();
1632 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1634 let mut rw_stream = check!(File::create(filename));
1635 check!(rw_stream.write(initial_msg.as_bytes()));
1636 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1637 check!(rw_stream.write(overwrite_msg.as_bytes()));
1640 let mut read_stream = check!(File::open(filename));
1641 check!(read_stream.read(&mut read_mem));
1643 check!(fs::remove_file(filename));
1644 let read_str = str::from_utf8(&read_mem).unwrap();
1645 assert!(read_str == final_msg);
1649 fn file_test_io_seek_shakedown() {
1651 let initial_msg = "qwer-asdf-zxcv";
1652 let chunk_one: &str = "qwer";
1653 let chunk_two: &str = "asdf";
1654 let chunk_three: &str = "zxcv";
1655 let mut read_mem = [0; 4];
1656 let tmpdir = tmpdir();
1657 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1659 let mut rw_stream = check!(File::create(filename));
1660 check!(rw_stream.write(initial_msg.as_bytes()));
1663 let mut read_stream = check!(File::open(filename));
1665 check!(read_stream.seek(SeekFrom::End(-4)));
1666 check!(read_stream.read(&mut read_mem));
1667 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1669 check!(read_stream.seek(SeekFrom::Current(-9)));
1670 check!(read_stream.read(&mut read_mem));
1671 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1673 check!(read_stream.seek(SeekFrom::Start(0)));
1674 check!(read_stream.read(&mut read_mem));
1675 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1677 check!(fs::remove_file(filename));
1681 fn file_test_stat_is_correct_on_is_file() {
1682 let tmpdir = tmpdir();
1683 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1685 let mut opts = OpenOptions::new();
1686 let mut fs = check!(opts.read(true).write(true)
1687 .create(true).open(filename));
1689 fs.write(msg.as_bytes()).unwrap();
1691 let fstat_res = check!(fs.metadata());
1692 assert!(fstat_res.is_file());
1694 let stat_res_fn = check!(fs::metadata(filename));
1695 assert!(stat_res_fn.is_file());
1696 let stat_res_meth = check!(filename.metadata());
1697 assert!(stat_res_meth.is_file());
1698 check!(fs::remove_file(filename));
1702 fn file_test_stat_is_correct_on_is_dir() {
1703 let tmpdir = tmpdir();
1704 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1705 check!(fs::create_dir(filename));
1706 let stat_res_fn = check!(fs::metadata(filename));
1707 assert!(stat_res_fn.is_dir());
1708 let stat_res_meth = check!(filename.metadata());
1709 assert!(stat_res_meth.is_dir());
1710 check!(fs::remove_dir(filename));
1714 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1715 let tmpdir = tmpdir();
1716 let dir = &tmpdir.join("fileinfo_false_on_dir");
1717 check!(fs::create_dir(dir));
1718 assert!(!dir.is_file());
1719 check!(fs::remove_dir(dir));
1723 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1724 let tmpdir = tmpdir();
1725 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1726 check!(check!(File::create(file)).write(b"foo"));
1727 assert!(file.exists());
1728 check!(fs::remove_file(file));
1729 assert!(!file.exists());
1733 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1734 let tmpdir = tmpdir();
1735 let dir = &tmpdir.join("before_and_after_dir");
1736 assert!(!dir.exists());
1737 check!(fs::create_dir(dir));
1738 assert!(dir.exists());
1739 assert!(dir.is_dir());
1740 check!(fs::remove_dir(dir));
1741 assert!(!dir.exists());
1745 fn file_test_directoryinfo_readdir() {
1746 let tmpdir = tmpdir();
1747 let dir = &tmpdir.join("di_readdir");
1748 check!(fs::create_dir(dir));
1751 let f = dir.join(&format!("{}.txt", n));
1752 let mut w = check!(File::create(&f));
1753 let msg_str = format!("{}{}", prefix, n.to_string());
1754 let msg = msg_str.as_bytes();
1755 check!(w.write(msg));
1757 let files = check!(fs::read_dir(dir));
1758 let mut mem = [0; 4];
1760 let f = f.unwrap().path();
1762 let n = f.file_stem().unwrap();
1763 check!(check!(File::open(&f)).read(&mut mem));
1764 let read_str = str::from_utf8(&mem).unwrap();
1765 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1766 assert_eq!(expected, read_str);
1768 check!(fs::remove_file(&f));
1770 check!(fs::remove_dir(dir));
1774 fn file_create_new_already_exists_error() {
1775 let tmpdir = tmpdir();
1776 let file = &tmpdir.join("file_create_new_error_exists");
1777 check!(fs::File::create(file));
1778 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
1779 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1783 fn mkdir_path_already_exists_error() {
1784 let tmpdir = tmpdir();
1785 let dir = &tmpdir.join("mkdir_error_twice");
1786 check!(fs::create_dir(dir));
1787 let e = fs::create_dir(dir).unwrap_err();
1788 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1792 fn recursive_mkdir() {
1793 let tmpdir = tmpdir();
1794 let dir = tmpdir.join("d1/d2");
1795 check!(fs::create_dir_all(&dir));
1796 assert!(dir.is_dir())
1800 fn recursive_mkdir_failure() {
1801 let tmpdir = tmpdir();
1802 let dir = tmpdir.join("d1");
1803 let file = dir.join("f1");
1805 check!(fs::create_dir_all(&dir));
1806 check!(File::create(&file));
1808 let result = fs::create_dir_all(&file);
1810 assert!(result.is_err());
1814 fn recursive_mkdir_slash() {
1815 check!(fs::create_dir_all(&Path::new("/")));
1819 fn recursive_rmdir() {
1820 let tmpdir = tmpdir();
1821 let d1 = tmpdir.join("d1");
1822 let dt = d1.join("t");
1823 let dtt = dt.join("t");
1824 let d2 = tmpdir.join("d2");
1825 let canary = d2.join("do_not_delete");
1826 check!(fs::create_dir_all(&dtt));
1827 check!(fs::create_dir_all(&d2));
1828 check!(check!(File::create(&canary)).write(b"foo"));
1829 check!(symlink_junction(&d2, &dt.join("d2")));
1830 let _ = symlink_file(&canary, &d1.join("canary"));
1831 check!(fs::remove_dir_all(&d1));
1833 assert!(!d1.is_dir());
1834 assert!(canary.exists());
1838 fn recursive_rmdir_of_symlink() {
1839 // test we do not recursively delete a symlink but only dirs.
1840 let tmpdir = tmpdir();
1841 let link = tmpdir.join("d1");
1842 let dir = tmpdir.join("d2");
1843 let canary = dir.join("do_not_delete");
1844 check!(fs::create_dir_all(&dir));
1845 check!(check!(File::create(&canary)).write(b"foo"));
1846 check!(symlink_junction(&dir, &link));
1847 check!(fs::remove_dir_all(&link));
1849 assert!(!link.is_dir());
1850 assert!(canary.exists());
1854 // only Windows makes a distinction between file and directory symlinks.
1856 fn recursive_rmdir_of_file_symlink() {
1857 let tmpdir = tmpdir();
1858 if !got_symlink_permission(&tmpdir) { return };
1860 let f1 = tmpdir.join("f1");
1861 let f2 = tmpdir.join("f2");
1862 check!(check!(File::create(&f1)).write(b"foo"));
1863 check!(symlink_file(&f1, &f2));
1864 match fs::remove_dir_all(&f2) {
1865 Ok(..) => panic!("wanted a failure"),
1871 fn unicode_path_is_dir() {
1872 assert!(Path::new(".").is_dir());
1873 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
1875 let tmpdir = tmpdir();
1877 let mut dirpath = tmpdir.path().to_path_buf();
1878 dirpath.push("test-가一ー你好");
1879 check!(fs::create_dir(&dirpath));
1880 assert!(dirpath.is_dir());
1882 let mut filepath = dirpath;
1883 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1884 check!(File::create(&filepath)); // ignore return; touch only
1885 assert!(!filepath.is_dir());
1886 assert!(filepath.exists());
1890 fn unicode_path_exists() {
1891 assert!(Path::new(".").exists());
1892 assert!(!Path::new("test/nonexistent-bogus-path").exists());
1894 let tmpdir = tmpdir();
1895 let unicode = tmpdir.path();
1896 let unicode = unicode.join(&format!("test-각丁ー再见"));
1897 check!(fs::create_dir(&unicode));
1898 assert!(unicode.exists());
1899 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
1903 fn copy_file_does_not_exist() {
1904 let from = Path::new("test/nonexistent-bogus-path");
1905 let to = Path::new("test/other-bogus-path");
1907 match fs::copy(&from, &to) {
1910 assert!(!from.exists());
1911 assert!(!to.exists());
1917 fn copy_src_does_not_exist() {
1918 let tmpdir = tmpdir();
1919 let from = Path::new("test/nonexistent-bogus-path");
1920 let to = tmpdir.join("out.txt");
1921 check!(check!(File::create(&to)).write(b"hello"));
1922 assert!(fs::copy(&from, &to).is_err());
1923 assert!(!from.exists());
1924 let mut v = Vec::new();
1925 check!(check!(File::open(&to)).read_to_end(&mut v));
1926 assert_eq!(v, b"hello");
1931 let tmpdir = tmpdir();
1932 let input = tmpdir.join("in.txt");
1933 let out = tmpdir.join("out.txt");
1935 check!(check!(File::create(&input)).write(b"hello"));
1936 check!(fs::copy(&input, &out));
1937 let mut v = Vec::new();
1938 check!(check!(File::open(&out)).read_to_end(&mut v));
1939 assert_eq!(v, b"hello");
1941 assert_eq!(check!(input.metadata()).permissions(),
1942 check!(out.metadata()).permissions());
1946 fn copy_file_dst_dir() {
1947 let tmpdir = tmpdir();
1948 let out = tmpdir.join("out");
1950 check!(File::create(&out));
1951 match fs::copy(&*out, tmpdir.path()) {
1952 Ok(..) => panic!(), Err(..) => {}
1957 fn copy_file_dst_exists() {
1958 let tmpdir = tmpdir();
1959 let input = tmpdir.join("in");
1960 let output = tmpdir.join("out");
1962 check!(check!(File::create(&input)).write("foo".as_bytes()));
1963 check!(check!(File::create(&output)).write("bar".as_bytes()));
1964 check!(fs::copy(&input, &output));
1966 let mut v = Vec::new();
1967 check!(check!(File::open(&output)).read_to_end(&mut v));
1968 assert_eq!(v, b"foo".to_vec());
1972 fn copy_file_src_dir() {
1973 let tmpdir = tmpdir();
1974 let out = tmpdir.join("out");
1976 match fs::copy(tmpdir.path(), &out) {
1977 Ok(..) => panic!(), Err(..) => {}
1979 assert!(!out.exists());
1983 fn copy_file_preserves_perm_bits() {
1984 let tmpdir = tmpdir();
1985 let input = tmpdir.join("in.txt");
1986 let out = tmpdir.join("out.txt");
1988 let attr = check!(check!(File::create(&input)).metadata());
1989 let mut p = attr.permissions();
1990 p.set_readonly(true);
1991 check!(fs::set_permissions(&input, p));
1992 check!(fs::copy(&input, &out));
1993 assert!(check!(out.metadata()).permissions().readonly());
1994 check!(fs::set_permissions(&input, attr.permissions()));
1995 check!(fs::set_permissions(&out, attr.permissions()));
2000 fn copy_file_preserves_streams() {
2002 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2003 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2004 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2005 let mut v = Vec::new();
2006 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2007 assert_eq!(v, b"carrot".to_vec());
2011 fn symlinks_work() {
2012 let tmpdir = tmpdir();
2013 if !got_symlink_permission(&tmpdir) { return };
2015 let input = tmpdir.join("in.txt");
2016 let out = tmpdir.join("out.txt");
2018 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2019 check!(symlink_file(&input, &out));
2020 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2021 assert_eq!(check!(fs::metadata(&out)).len(),
2022 check!(fs::metadata(&input)).len());
2023 let mut v = Vec::new();
2024 check!(check!(File::open(&out)).read_to_end(&mut v));
2025 assert_eq!(v, b"foobar".to_vec());
2029 fn symlink_noexist() {
2030 // Symlinks can point to things that don't exist
2031 let tmpdir = tmpdir();
2032 if !got_symlink_permission(&tmpdir) { return };
2034 // Use a relative path for testing. Symlinks get normalized by Windows,
2035 // so we may not get the same path back for absolute paths
2036 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2037 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2044 // directory symlink
2045 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2048 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2049 r"C:\Users\Default");
2050 // junction with special permissions
2051 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2054 let tmpdir = tmpdir();
2055 let link = tmpdir.join("link");
2056 if !got_symlink_permission(&tmpdir) { return };
2057 check!(symlink_file(&"foo", &link));
2058 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2062 fn readlink_not_symlink() {
2063 let tmpdir = tmpdir();
2064 match fs::read_link(tmpdir.path()) {
2065 Ok(..) => panic!("wanted a failure"),
2072 let tmpdir = tmpdir();
2073 let input = tmpdir.join("in.txt");
2074 let out = tmpdir.join("out.txt");
2076 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2077 check!(fs::hard_link(&input, &out));
2078 assert_eq!(check!(fs::metadata(&out)).len(),
2079 check!(fs::metadata(&input)).len());
2080 assert_eq!(check!(fs::metadata(&out)).len(),
2081 check!(input.metadata()).len());
2082 let mut v = Vec::new();
2083 check!(check!(File::open(&out)).read_to_end(&mut v));
2084 assert_eq!(v, b"foobar".to_vec());
2086 // can't link to yourself
2087 match fs::hard_link(&input, &input) {
2088 Ok(..) => panic!("wanted a failure"),
2091 // can't link to something that doesn't exist
2092 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2093 Ok(..) => panic!("wanted a failure"),
2100 let tmpdir = tmpdir();
2101 let file = tmpdir.join("in.txt");
2103 check!(File::create(&file));
2104 let attr = check!(fs::metadata(&file));
2105 assert!(!attr.permissions().readonly());
2106 let mut p = attr.permissions();
2107 p.set_readonly(true);
2108 check!(fs::set_permissions(&file, p.clone()));
2109 let attr = check!(fs::metadata(&file));
2110 assert!(attr.permissions().readonly());
2112 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2113 Ok(..) => panic!("wanted an error"),
2117 p.set_readonly(false);
2118 check!(fs::set_permissions(&file, p));
2122 fn sync_doesnt_kill_anything() {
2123 let tmpdir = tmpdir();
2124 let path = tmpdir.join("in.txt");
2126 let mut file = check!(File::create(&path));
2127 check!(file.sync_all());
2128 check!(file.sync_data());
2129 check!(file.write(b"foo"));
2130 check!(file.sync_all());
2131 check!(file.sync_data());
2135 fn truncate_works() {
2136 let tmpdir = tmpdir();
2137 let path = tmpdir.join("in.txt");
2139 let mut file = check!(File::create(&path));
2140 check!(file.write(b"foo"));
2141 check!(file.sync_all());
2143 // Do some simple things with truncation
2144 assert_eq!(check!(file.metadata()).len(), 3);
2145 check!(file.set_len(10));
2146 assert_eq!(check!(file.metadata()).len(), 10);
2147 check!(file.write(b"bar"));
2148 check!(file.sync_all());
2149 assert_eq!(check!(file.metadata()).len(), 10);
2151 let mut v = Vec::new();
2152 check!(check!(File::open(&path)).read_to_end(&mut v));
2153 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2155 // Truncate to a smaller length, don't seek, and then write something.
2156 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2157 // past the end of the file).
2158 check!(file.set_len(2));
2159 assert_eq!(check!(file.metadata()).len(), 2);
2160 check!(file.write(b"wut"));
2161 check!(file.sync_all());
2162 assert_eq!(check!(file.metadata()).len(), 9);
2163 let mut v = Vec::new();
2164 check!(check!(File::open(&path)).read_to_end(&mut v));
2165 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2170 use fs::OpenOptions as OO;
2171 fn c<T: Clone>(t: &T) -> T { t.clone() }
2173 let tmpdir = tmpdir();
2175 let mut r = OO::new(); r.read(true);
2176 let mut w = OO::new(); w.write(true);
2177 let mut rw = OO::new(); rw.read(true).write(true);
2178 let mut a = OO::new(); a.append(true);
2179 let mut ra = OO::new(); ra.read(true).append(true);
2181 let invalid_options = if cfg!(windows) { "The parameter is incorrect" }
2182 else { "Invalid argument" };
2184 // Test various combinations of creation modes and access modes.
2187 // creation mode | read | write | read-write | append | read-append |
2188 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2189 // not set (open existing) | X | X | X | X | X |
2190 // create | | X | X | X | X |
2191 // truncate | | X | X | | |
2192 // create and truncate | | X | X | | |
2193 // create_new | | X | X | X | X |
2195 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2198 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2199 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2200 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2201 check!(c(&w).create(true).open(&tmpdir.join("a")));
2202 check!(c(&w).open(&tmpdir.join("a")));
2205 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2206 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2207 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2208 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2209 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2212 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2213 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2214 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2215 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2216 check!(c(&rw).open(&tmpdir.join("c")));
2219 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2220 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2221 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2222 check!(c(&a).create(true).open(&tmpdir.join("d")));
2223 check!(c(&a).open(&tmpdir.join("d")));
2226 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2227 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2228 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2229 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2230 check!(c(&ra).open(&tmpdir.join("e")));
2232 // Test opening a file without setting an access mode
2233 let mut blank = OO::new();
2234 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2237 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2239 // Test write fails for read-only
2240 check!(r.open(&tmpdir.join("h")));
2242 let mut f = check!(r.open(&tmpdir.join("h")));
2243 assert!(f.write("wut".as_bytes()).is_err());
2246 // Test write overwrites
2248 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2249 check!(f.write("baz".as_bytes()));
2252 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2253 let mut b = vec![0; 6];
2254 check!(f.read(&mut b));
2255 assert_eq!(b, "bazbar".as_bytes());
2258 // Test truncate works
2260 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2261 check!(f.write("foo".as_bytes()));
2263 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2265 // Test append works
2266 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2268 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2269 check!(f.write("bar".as_bytes()));
2271 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2273 // Test .append(true) equals .write(true).append(true)
2275 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2276 check!(f.write("baz".as_bytes()));
2278 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2282 fn _assert_send_sync() {
2283 fn _assert_send_sync<T: Send + Sync>() {}
2284 _assert_send_sync::<OpenOptions>();
2289 let mut bytes = [0; 1024];
2290 StdRng::new().unwrap().fill_bytes(&mut bytes);
2292 let tmpdir = tmpdir();
2294 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2295 let mut v = Vec::new();
2296 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2297 assert!(v == &bytes[..]);
2301 fn file_try_clone() {
2302 let tmpdir = tmpdir();
2304 let mut f1 = check!(OpenOptions::new()
2308 .open(&tmpdir.join("test")));
2309 let mut f2 = check!(f1.try_clone());
2311 check!(f1.write_all(b"hello world"));
2312 check!(f1.seek(SeekFrom::Start(2)));
2314 let mut buf = vec![];
2315 check!(f2.read_to_end(&mut buf));
2316 assert_eq!(buf, b"llo world");
2319 check!(f1.write_all(b"!"));
2323 #[cfg(not(windows))]
2324 fn unlink_readonly() {
2325 let tmpdir = tmpdir();
2326 let path = tmpdir.join("file");
2327 check!(File::create(&path));
2328 let mut perm = check!(fs::metadata(&path)).permissions();
2329 perm.set_readonly(true);
2330 check!(fs::set_permissions(&path, perm));
2331 check!(fs::remove_file(&path));
2335 fn mkdir_trailing_slash() {
2336 let tmpdir = tmpdir();
2337 let path = tmpdir.join("file");
2338 check!(fs::create_dir_all(&path.join("a/")));
2342 fn canonicalize_works_simple() {
2343 let tmpdir = tmpdir();
2344 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2345 let file = tmpdir.join("test");
2346 File::create(&file).unwrap();
2347 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2351 fn realpath_works() {
2352 let tmpdir = tmpdir();
2353 if !got_symlink_permission(&tmpdir) { return };
2355 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2356 let file = tmpdir.join("test");
2357 let dir = tmpdir.join("test2");
2358 let link = dir.join("link");
2359 let linkdir = tmpdir.join("test3");
2361 File::create(&file).unwrap();
2362 fs::create_dir(&dir).unwrap();
2363 symlink_file(&file, &link).unwrap();
2364 symlink_dir(&dir, &linkdir).unwrap();
2366 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2368 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2369 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2370 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2371 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2372 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2376 fn realpath_works_tricky() {
2377 let tmpdir = tmpdir();
2378 if !got_symlink_permission(&tmpdir) { return };
2380 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2381 let a = tmpdir.join("a");
2382 let b = a.join("b");
2383 let c = b.join("c");
2384 let d = a.join("d");
2385 let e = d.join("e");
2386 let f = a.join("f");
2388 fs::create_dir_all(&b).unwrap();
2389 fs::create_dir_all(&d).unwrap();
2390 File::create(&f).unwrap();
2391 if cfg!(not(windows)) {
2392 symlink_dir("../d/e", &c).unwrap();
2393 symlink_file("../f", &e).unwrap();
2396 symlink_dir(r"..\d\e", &c).unwrap();
2397 symlink_file(r"..\f", &e).unwrap();
2400 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2401 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2405 fn dir_entry_methods() {
2406 let tmpdir = tmpdir();
2408 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2409 File::create(&tmpdir.join("b")).unwrap();
2411 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2412 let fname = file.file_name();
2413 match fname.to_str() {
2415 assert!(file.file_type().unwrap().is_dir());
2416 assert!(file.metadata().unwrap().is_dir());
2419 assert!(file.file_type().unwrap().is_file());
2420 assert!(file.metadata().unwrap().is_file());
2422 f => panic!("unknown file name: {:?}", f),
2428 fn read_dir_not_found() {
2429 let res = fs::read_dir("/path/that/does/not/exist");
2430 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
2434 fn create_dir_all_with_junctions() {
2435 let tmpdir = tmpdir();
2436 let target = tmpdir.join("target");
2438 let junction = tmpdir.join("junction");
2439 let b = junction.join("a/b");
2441 let link = tmpdir.join("link");
2442 let d = link.join("c/d");
2444 fs::create_dir(&target).unwrap();
2446 check!(symlink_junction(&target, &junction));
2447 check!(fs::create_dir_all(&b));
2448 // the junction itself is not a directory, but `is_dir()` on a Path
2450 assert!(junction.is_dir());
2451 assert!(b.exists());
2453 if !got_symlink_permission(&tmpdir) { return };
2454 check!(symlink_dir(&target, &link));
2455 check!(fs::create_dir_all(&d));
2456 assert!(link.is_dir());
2457 assert!(d.exists());
2461 fn metadata_access_times() {
2462 let tmpdir = tmpdir();
2464 let b = tmpdir.join("b");
2465 File::create(&b).unwrap();
2467 let a = check!(fs::metadata(&tmpdir.path()));
2468 let b = check!(fs::metadata(&b));
2470 assert_eq!(check!(a.accessed()), check!(a.accessed()));
2471 assert_eq!(check!(a.modified()), check!(a.modified()));
2472 assert_eq!(check!(b.accessed()), check!(b.modified()));
2474 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
2475 check!(a.created());
2476 check!(b.created());