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.
38 /// use std::io::prelude::*;
39 /// use std::fs::File;
41 /// # fn foo() -> std::io::Result<()> {
42 /// let mut f = try!(File::create("foo.txt"));
43 /// try!(f.write_all(b"Hello, world!"));
45 /// let mut f = try!(File::open("foo.txt"));
46 /// let mut s = String::new();
47 /// try!(f.read_to_string(&mut s));
48 /// assert_eq!(s, "Hello, world!");
52 #[stable(feature = "rust1", since = "1.0.0")]
57 /// Metadata information about a file.
59 /// This structure is returned from the `metadata` function or method and
60 /// represents known metadata about a file such as its permissions, size,
61 /// modification times, etc.
62 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Metadata(fs_imp::FileAttr);
66 /// Iterator over the entries in a directory.
68 /// This iterator is returned from the `read_dir` function of this module and
69 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
70 /// information like the entry's path and possibly other metadata can be
75 /// This `io::Result` will be an `Err` if there's some sort of intermittent
76 /// IO error during iteration.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct ReadDir(fs_imp::ReadDir);
80 /// Entries returned by the `ReadDir` iterator.
82 /// An instance of `DirEntry` represents an entry inside of a directory on the
83 /// filesystem. Each entry can be inspected via methods to learn about the full
84 /// path or possibly other metadata through per-platform extension traits.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct DirEntry(fs_imp::DirEntry);
88 /// An iterator that recursively walks over the contents of a directory.
89 #[unstable(feature = "fs_walk",
90 reason = "the precise semantics and defaults for a recursive walk \
91 may change and this may end up accounting for files such \
92 as symlinks differently",
94 #[rustc_deprecated(reason = "superceded by the walkdir crate",
98 stack: Vec<io::Result<ReadDir>>,
101 /// Options and flags which can be used to configure how a file is opened.
103 /// This builder exposes the ability to configure how a `File` is opened and
104 /// what operations are permitted on the open file. The `File::open` and
105 /// `File::create` methods are aliases for commonly used options using this
108 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
109 /// then chain calls to methods to set each option, then call `open()`, passing
110 /// the path of the file you're trying to open. This will give you a
111 /// [`io::Result`][result] with a [`File`][file] inside that you can further
114 /// [result]: ../io/type.Result.html
115 /// [file]: struct.File.html
119 /// Opening a file to read:
122 /// use std::fs::OpenOptions;
124 /// let file = OpenOptions::new().read(true).open("foo.txt");
127 /// Opening a file for both reading and writing, as well as creating it if it
131 /// use std::fs::OpenOptions;
133 /// let file = OpenOptions::new()
137 /// .open("foo.txt");
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub struct OpenOptions(fs_imp::OpenOptions);
143 /// Representation of the various permissions on a file.
145 /// This module only currently provides one bit of information, `readonly`,
146 /// which is exposed on all currently supported platforms. Unix-specific
147 /// functionality, such as mode bits, is available through the
148 /// `os::unix::PermissionsExt` trait.
149 #[derive(Clone, PartialEq, Eq, Debug)]
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub struct Permissions(fs_imp::FilePermissions);
153 /// An structure representing a type of file with accessors for each file type.
154 #[stable(feature = "file_type", since = "1.1.0")]
155 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
156 pub struct FileType(fs_imp::FileType);
158 /// A builder used to create directories in various manners.
160 /// This builder also supports platform-specific options.
161 #[stable(feature = "dir_builder", since = "1.6.0")]
162 pub struct DirBuilder {
163 inner: fs_imp::DirBuilder,
168 /// Attempts to open a file in read-only mode.
170 /// See the `OpenOptions::open` method for more details.
174 /// This function will return an error if `path` does not already exist.
175 /// Other errors may also be returned according to `OpenOptions::open`.
180 /// use std::fs::File;
182 /// # fn foo() -> std::io::Result<()> {
183 /// let mut f = try!(File::open("foo.txt"));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
189 OpenOptions::new().read(true).open(path.as_ref())
192 /// Opens a file in write-only mode.
194 /// This function will create a file if it does not exist,
195 /// and will truncate it if it does.
197 /// See the `OpenOptions::open` function for more details.
202 /// use std::fs::File;
204 /// # fn foo() -> std::io::Result<()> {
205 /// let mut f = try!(File::create("foo.txt"));
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
211 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
214 /// Attempts to sync all OS-internal metadata to disk.
216 /// This function will attempt to ensure that all in-core data reaches the
217 /// filesystem before returning.
222 /// use std::fs::File;
223 /// use std::io::prelude::*;
225 /// # fn foo() -> std::io::Result<()> {
226 /// let mut f = try!(File::create("foo.txt"));
227 /// try!(f.write_all(b"Hello, world!"));
229 /// try!(f.sync_all());
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn sync_all(&self) -> io::Result<()> {
238 /// This function is similar to `sync_all`, except that it may not
239 /// synchronize file metadata to the filesystem.
241 /// This is intended for use cases that must synchronize content, but don't
242 /// need the metadata on disk. The goal of this method is to reduce disk
245 /// Note that some platforms may simply implement this in terms of
251 /// use std::fs::File;
252 /// use std::io::prelude::*;
254 /// # fn foo() -> std::io::Result<()> {
255 /// let mut f = try!(File::create("foo.txt"));
256 /// try!(f.write_all(b"Hello, world!"));
258 /// try!(f.sync_data());
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn sync_data(&self) -> io::Result<()> {
264 self.inner.datasync()
267 /// Truncates or extends the underlying file, updating the size of
268 /// this file to become `size`.
270 /// If the `size` is less than the current file's size, then the file will
271 /// be shrunk. If it is greater than the current file's size, then the file
272 /// will be extended to `size` and have all of the intermediate data filled
277 /// This function will return an error if the file is not opened for writing.
282 /// use std::fs::File;
284 /// # fn foo() -> std::io::Result<()> {
285 /// let mut f = try!(File::create("foo.txt"));
286 /// try!(f.set_len(10));
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn set_len(&self, size: u64) -> io::Result<()> {
292 self.inner.truncate(size)
295 /// Queries metadata about the underlying file.
300 /// use std::fs::File;
302 /// # fn foo() -> std::io::Result<()> {
303 /// let mut f = try!(File::open("foo.txt"));
304 /// let metadata = try!(f.metadata());
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn metadata(&self) -> io::Result<Metadata> {
310 self.inner.file_attr().map(Metadata)
313 /// Creates a new independently owned handle to the underlying file.
315 /// The returned `File` is a reference to the same state that this object
316 /// references. Both handles will read and write with the same cursor
318 #[unstable(feature = "file_try_clone", reason = "newly added", issue = "31405")]
319 pub fn try_clone(&self) -> io::Result<File> {
321 inner: try!(self.inner.duplicate())
326 impl AsInner<fs_imp::File> for File {
327 fn as_inner(&self) -> &fs_imp::File { &self.inner }
329 impl FromInner<fs_imp::File> for File {
330 fn from_inner(f: fs_imp::File) -> File {
334 impl IntoInner<fs_imp::File> for File {
335 fn into_inner(self) -> fs_imp::File {
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl fmt::Debug for File {
342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
347 #[stable(feature = "rust1", since = "1.0.0")]
349 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
352 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
353 self.inner.read_to_end(buf)
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl Write for File {
358 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
359 self.inner.write(buf)
361 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
363 #[stable(feature = "rust1", since = "1.0.0")]
365 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<'a> Read for &'a File {
371 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
374 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
375 self.inner.read_to_end(buf)
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<'a> Write for &'a File {
380 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
381 self.inner.write(buf)
383 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl<'a> Seek for &'a File {
387 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
393 /// Creates a blank new set of options ready for configuration.
395 /// All options are initially set to `false`.
400 /// use std::fs::OpenOptions;
402 /// let mut options = OpenOptions::new();
403 /// let file = options.read(true).open("foo.txt");
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn new() -> OpenOptions {
407 OpenOptions(fs_imp::OpenOptions::new())
410 /// Sets the option for read access.
412 /// This option, when true, will indicate that the file should be
413 /// `read`-able if opened.
418 /// use std::fs::OpenOptions;
420 /// let file = OpenOptions::new().read(true).open("foo.txt");
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
424 self.0.read(read); self
427 /// Sets the option for write access.
429 /// This option, when true, will indicate that the file should be
430 /// `write`-able if opened.
432 /// If the file already exists, any write calls on it will overwrite its
433 /// contents, without truncating it.
438 /// use std::fs::OpenOptions;
440 /// let file = OpenOptions::new().write(true).open("foo.txt");
442 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
444 self.0.write(write); self
447 /// Sets the option for the append mode.
449 /// This option, when true, means that writes will append to a file instead
450 /// of overwriting previous contents.
451 /// Note that setting `.write(true).append(true)` has the same effect as
452 /// setting only `.append(true)`.
454 /// For most filesystems, the operating system guarantees that all writes are
455 /// atomic: no writes get mangled because another process writes at the same
458 /// One maybe obvious note when using append-mode: make sure that all data
459 /// that belongs together is written to the file in one operation. This
460 /// can be done by concatenating strings before passing them to `write()`,
461 /// or using a buffered writer (with a buffer of adequate size),
462 /// and calling `flush()` when the message is complete.
464 /// If a file is opened with both read and append access, beware that after
465 /// opening, and after every write, the position for reading may be set at the
466 /// end of the file. So, before writing, save the current position (using
467 /// `seek(SeekFrom::Current(0))`, and restore it before the next read.
472 /// use std::fs::OpenOptions;
474 /// let file = OpenOptions::new().append(true).open("foo.txt");
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
478 self.0.append(append); self
481 /// Sets the option for truncating a previous file.
483 /// If a file is successfully opened with this option set it will truncate
484 /// the file to 0 length if it already exists.
486 /// The file must be opened with write access for truncate to work.
491 /// use std::fs::OpenOptions;
493 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
497 self.0.truncate(truncate); self
500 /// Sets the option for creating a new file.
502 /// This option indicates whether a new file will be created if the file
503 /// does not yet already exist.
505 /// In order for the file to be created, `write` or `append` access must
511 /// use std::fs::OpenOptions;
513 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
517 self.0.create(create); self
520 /// Sets the option to always create a new file.
522 /// This option indicates whether a new file will be created.
523 /// No file is allowed to exist at the target location, also no (dangling)
526 /// This option is useful because it as atomic. Otherwise between checking
527 /// whether a file exists and creating a new one, the file may have been
528 /// created by another process (a TOCTOU race condition / attack).
530 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are
533 /// The file must be opened with write or append access in order to create
539 /// #![feature(expand_open_options)]
540 /// use std::fs::OpenOptions;
542 /// let file = OpenOptions::new().write(true)
543 /// .create_new(true)
544 /// .open("foo.txt");
546 #[unstable(feature = "expand_open_options",
547 reason = "recently added",
549 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
550 self.0.create_new(create_new); self
553 /// Opens a file at `path` with the options specified by `self`.
557 /// This function will return an error under a number of different
558 /// circumstances, to include but not limited to:
560 /// * Opening a file that does not exist without setting `create` or
562 /// * Attempting to open a file with access that the user lacks
564 /// * Filesystem-level errors (full disk, etc)
565 /// * Invalid combinations of open options (truncate without write access,
566 /// no access mode set, etc)
571 /// use std::fs::OpenOptions;
573 /// let file = OpenOptions::new().open("foo.txt");
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
577 self._open(path.as_ref())
580 fn _open(&self, path: &Path) -> io::Result<File> {
581 let inner = try!(fs_imp::File::open(path, &self.0));
582 Ok(File { inner: inner })
586 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
587 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
591 /// Returns the file type for this metadata.
592 #[stable(feature = "file_type", since = "1.1.0")]
593 pub fn file_type(&self) -> FileType {
594 FileType(self.0.file_type())
597 /// Returns whether this metadata is for a directory.
602 /// # fn foo() -> std::io::Result<()> {
605 /// let metadata = try!(fs::metadata("foo.txt"));
607 /// assert!(!metadata.is_dir());
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
614 /// Returns whether this metadata is for a regular file.
619 /// # fn foo() -> std::io::Result<()> {
622 /// let metadata = try!(fs::metadata("foo.txt"));
624 /// assert!(metadata.is_file());
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn is_file(&self) -> bool { self.file_type().is_file() }
631 /// Returns the size of the file, in bytes, this metadata is for.
636 /// # fn foo() -> std::io::Result<()> {
639 /// let metadata = try!(fs::metadata("foo.txt"));
641 /// assert_eq!(0, metadata.len());
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn len(&self) -> u64 { self.0.size() }
648 /// Returns the permissions of the file this metadata is for.
653 /// # fn foo() -> std::io::Result<()> {
656 /// let metadata = try!(fs::metadata("foo.txt"));
658 /// assert!(!metadata.permissions().readonly());
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn permissions(&self) -> Permissions {
664 Permissions(self.0.perm())
667 /// Returns the last modification time listed in this metadata.
669 /// The returned value corresponds to the `mtime` field of `stat` on Unix
670 /// platforms and the `ftLastWriteTime` field on Windows platforms.
674 /// This field may not be available on all platforms, and will return an
675 /// `Err` on platforms where it is not available.
676 #[unstable(feature = "fs_time", issue = "31399")]
677 pub fn modified(&self) -> io::Result<SystemTime> {
678 self.0.modified().map(FromInner::from_inner)
681 /// Returns the last access time of this metadata.
683 /// The returned value corresponds to the `atime` field of `stat` on Unix
684 /// platforms and the `ftLastAccessTime` field on Windows platforms.
686 /// Note that not all platforms will keep this field update in a file's
687 /// metadata, for example Windows has an option to disable updating this
688 /// time when files are accessed and Linux similarly has `noatime`.
692 /// This field may not be available on all platforms, and will return an
693 /// `Err` on platforms where it is not available.
694 #[unstable(feature = "fs_time", issue = "31399")]
695 pub fn accessed(&self) -> io::Result<SystemTime> {
696 self.0.accessed().map(FromInner::from_inner)
699 /// Returns the creation time listed in the this metadata.
701 /// The returned value corresponds to the `birthtime` field of `stat` on
702 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
706 /// This field may not be available on all platforms, and will return an
707 /// `Err` on platforms where it is not available.
708 #[unstable(feature = "fs_time", issue = "31399")]
709 pub fn created(&self) -> io::Result<SystemTime> {
710 self.0.created().map(FromInner::from_inner)
714 impl AsInner<fs_imp::FileAttr> for Metadata {
715 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
719 /// Returns whether these permissions describe a readonly file.
724 /// use std::fs::File;
726 /// # fn foo() -> std::io::Result<()> {
727 /// let mut f = try!(File::create("foo.txt"));
728 /// let metadata = try!(f.metadata());
730 /// assert_eq!(false, metadata.permissions().readonly());
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn readonly(&self) -> bool { self.0.readonly() }
737 /// Modifies the readonly flag for this set of permissions.
739 /// This operation does **not** modify the filesystem. To modify the
740 /// filesystem use the `fs::set_permissions` function.
745 /// use std::fs::File;
747 /// # fn foo() -> std::io::Result<()> {
748 /// let f = try!(File::create("foo.txt"));
749 /// let metadata = try!(f.metadata());
750 /// let mut permissions = metadata.permissions();
752 /// permissions.set_readonly(true);
754 /// // filesystem doesn't change
755 /// assert_eq!(false, metadata.permissions().readonly());
757 /// // just this particular `permissions`.
758 /// assert_eq!(true, permissions.readonly());
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn set_readonly(&mut self, readonly: bool) {
764 self.0.set_readonly(readonly)
769 /// Test whether this file type represents a directory.
770 #[stable(feature = "file_type", since = "1.1.0")]
771 pub fn is_dir(&self) -> bool { self.0.is_dir() }
773 /// Test whether this file type represents a regular file.
774 #[stable(feature = "file_type", since = "1.1.0")]
775 pub fn is_file(&self) -> bool { self.0.is_file() }
777 /// Test whether this file type represents a symbolic link.
778 #[stable(feature = "file_type", since = "1.1.0")]
779 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
782 impl AsInner<fs_imp::FileType> for FileType {
783 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
786 impl FromInner<fs_imp::FilePermissions> for Permissions {
787 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
792 impl AsInner<fs_imp::FilePermissions> for Permissions {
793 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl Iterator for ReadDir {
798 type Item = io::Result<DirEntry>;
800 fn next(&mut self) -> Option<io::Result<DirEntry>> {
801 self.0.next().map(|entry| entry.map(DirEntry))
806 /// Returns the full path to the file that this entry represents.
808 /// The full path is created by joining the original path to `read_dir` or
809 /// `walk_dir` with the filename of this entry.
815 /// # fn foo() -> std::io::Result<()> {
816 /// for entry in try!(fs::read_dir(".")) {
817 /// let dir = try!(entry);
818 /// println!("{:?}", dir.path());
824 /// This prints output like:
829 /// "./hello_world.rs"
832 /// The exact text, of course, depends on what files you have in `.`.
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn path(&self) -> PathBuf { self.0.path() }
836 /// Return the metadata for the file that this entry points at.
838 /// This function will not traverse symlinks if this entry points at a
841 /// # Platform-specific behavior
843 /// On Windows this function is cheap to call (no extra system calls
844 /// needed), but on Unix platforms this function is the equivalent of
845 /// calling `symlink_metadata` on the path.
846 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
847 pub fn metadata(&self) -> io::Result<Metadata> {
848 self.0.metadata().map(Metadata)
851 /// Return the file type for the file that this entry points at.
853 /// This function will not traverse symlinks if this entry points at a
856 /// # Platform-specific behavior
858 /// On Windows and most Unix platforms this function is free (no extra
859 /// system calls needed), but some Unix platforms may require the equivalent
860 /// call to `symlink_metadata` to learn about the target file type.
861 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
862 pub fn file_type(&self) -> io::Result<FileType> {
863 self.0.file_type().map(FileType)
866 /// Returns the bare file name of this directory entry without any other
867 /// leading path component.
868 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
869 pub fn file_name(&self) -> OsString {
874 impl AsInner<fs_imp::DirEntry> for DirEntry {
875 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
878 /// Removes a file from the filesystem.
880 /// Note that there is no
881 /// guarantee that the file is immediately deleted (e.g. depending on
882 /// platform, other open file descriptors may prevent immediate removal).
884 /// # Platform-specific behavior
886 /// This function currently corresponds to the `unlink` function on Unix
887 /// and the `DeleteFile` function on Windows.
888 /// Note that, this [may change in the future][changes].
889 /// [changes]: ../io/index.html#platform-specific-behavior
893 /// This function will return an error in the following situations, but is not
894 /// limited to just these cases:
896 /// * `path` points to a directory.
897 /// * The user lacks permissions to remove the file.
904 /// # fn foo() -> std::io::Result<()> {
905 /// try!(fs::remove_file("a.txt"));
909 #[stable(feature = "rust1", since = "1.0.0")]
910 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
911 fs_imp::unlink(path.as_ref())
914 /// Given a path, query the file system to get information about a file,
917 /// This function will traverse symbolic links to query information about the
918 /// destination file.
920 /// # Platform-specific behavior
922 /// This function currently corresponds to the `stat` function on Unix
923 /// and the `GetFileAttributesEx` function on Windows.
924 /// Note that, this [may change in the future][changes].
925 /// [changes]: ../io/index.html#platform-specific-behavior
929 /// This function will return an error in the following situations, but is not
930 /// limited to just these cases:
932 /// * The user lacks permissions to perform `metadata` call on `path`.
933 /// * `path` does not exist.
938 /// # fn foo() -> std::io::Result<()> {
941 /// let attr = try!(fs::metadata("/some/file/path.txt"));
942 /// // inspect attr ...
946 #[stable(feature = "rust1", since = "1.0.0")]
947 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
948 fs_imp::stat(path.as_ref()).map(Metadata)
951 /// Query the metadata about a file without following symlinks.
953 /// # Platform-specific behavior
955 /// This function currently corresponds to the `lstat` function on Unix
956 /// and the `GetFileAttributesEx` function on Windows.
957 /// Note that, this [may change in the future][changes].
958 /// [changes]: ../io/index.html#platform-specific-behavior
962 /// This function will return an error in the following situations, but is not
963 /// limited to just these cases:
965 /// * The user lacks permissions to perform `metadata` call on `path`.
966 /// * `path` does not exist.
971 /// # fn foo() -> std::io::Result<()> {
974 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
975 /// // inspect attr ...
979 #[stable(feature = "symlink_metadata", since = "1.1.0")]
980 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
981 fs_imp::lstat(path.as_ref()).map(Metadata)
984 /// Rename a file or directory to a new name.
986 /// This will not work if the new name is on a different mount point.
988 /// # Platform-specific behavior
990 /// This function currently corresponds to the `rename` function on Unix
991 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
992 /// Note that, this [may change in the future][changes].
993 /// [changes]: ../io/index.html#platform-specific-behavior
997 /// This function will return an error in the following situations, but is not
998 /// limited to just these cases:
1000 /// * `from` does not exist.
1001 /// * The user lacks permissions to view contents.
1002 /// * `from` and `to` are on separate filesystems.
1009 /// # fn foo() -> std::io::Result<()> {
1010 /// try!(fs::rename("a.txt", "b.txt")); // Rename a.txt to b.txt
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1016 fs_imp::rename(from.as_ref(), to.as_ref())
1019 /// Copies the contents of one file to another. This function will also
1020 /// copy the permission bits of the original file to the destination file.
1022 /// This function will **overwrite** the contents of `to`.
1024 /// Note that if `from` and `to` both point to the same file, then the file
1025 /// will likely get truncated by this operation.
1027 /// On success, the total number of bytes copied is returned.
1029 /// # Platform-specific behavior
1031 /// This function currently corresponds to the `open` function in Unix
1032 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1033 /// `O_CLOEXEC` is set for returned file descriptors.
1034 /// On Windows, this function currently corresponds to `CopyFileEx`.
1035 /// Note that, this [may change in the future][changes].
1036 /// [changes]: ../io/index.html#platform-specific-behavior
1040 /// This function will return an error in the following situations, but is not
1041 /// limited to just these cases:
1043 /// * The `from` path is not a file.
1044 /// * The `from` file does not exist.
1045 /// * The current process does not have the permission rights to access
1046 /// `from` or write `to`.
1053 /// # fn foo() -> std::io::Result<()> {
1054 /// try!(fs::copy("foo.txt", "bar.txt")); // Copy foo.txt to bar.txt
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1059 fs_imp::copy(from.as_ref(), to.as_ref())
1062 /// Creates a new hard link on the filesystem.
1064 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1065 /// often require these two paths to both be located on the same filesystem.
1067 /// # Platform-specific behavior
1069 /// This function currently corresponds to the `link` function on Unix
1070 /// and the `CreateHardLink` function on Windows.
1071 /// Note that, this [may change in the future][changes].
1072 /// [changes]: ../io/index.html#platform-specific-behavior
1076 /// This function will return an error in the following situations, but is not
1077 /// limited to just these cases:
1079 /// * The `src` path is not a file or doesn't exist.
1086 /// # fn foo() -> std::io::Result<()> {
1087 /// try!(fs::hard_link("a.txt", "b.txt")); // Hard link a.txt to b.txt
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1093 fs_imp::link(src.as_ref(), dst.as_ref())
1096 /// Creates a new symbolic link on the filesystem.
1098 /// The `dst` path will be a symbolic link pointing to the `src` path.
1099 /// On Windows, this will be a file symlink, not a directory symlink;
1100 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1101 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1102 /// used instead to make the intent explicit.
1109 /// # fn foo() -> std::io::Result<()> {
1110 /// try!(fs::soft_link("a.txt", "b.txt"));
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 #[rustc_deprecated(since = "1.1.0",
1116 reason = "replaced with std::os::unix::fs::symlink and \
1117 std::os::windows::fs::{symlink_file, symlink_dir}")]
1118 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1119 fs_imp::symlink(src.as_ref(), dst.as_ref())
1122 /// Reads a symbolic link, returning the file that the link points to.
1124 /// # Platform-specific behavior
1126 /// This function currently corresponds to the `readlink` function on Unix
1127 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1128 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1129 /// Note that, this [may change in the future][changes].
1130 /// [changes]: ../io/index.html#platform-specific-behavior
1134 /// This function will return an error in the following situations, but is not
1135 /// limited to just these cases:
1137 /// * `path` is not a symbolic link.
1138 /// * `path` does not exist.
1145 /// # fn foo() -> std::io::Result<()> {
1146 /// let path = try!(fs::read_link("a.txt"));
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1152 fs_imp::readlink(path.as_ref())
1155 /// Returns the canonical form of a path with all intermediate components
1156 /// normalized and symbolic links resolved.
1158 /// # Platform-specific behavior
1160 /// This function currently corresponds to the `realpath` function on Unix
1161 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1162 /// Note that, this [may change in the future][changes].
1163 /// [changes]: ../io/index.html#platform-specific-behavior
1167 /// This function will return an error in the following situations, but is not
1168 /// limited to just these cases:
1170 /// * `path` does not exist.
1171 /// * A component in path is not a directory.
1178 /// # fn foo() -> std::io::Result<()> {
1179 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
1183 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1184 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1185 fs_imp::canonicalize(path.as_ref())
1188 /// Creates a new, empty directory at the provided path
1190 /// # Platform-specific behavior
1192 /// This function currently corresponds to the `mkdir` function on Unix
1193 /// and the `CreateDirectory` function on Windows.
1194 /// Note that, this [may change in the future][changes].
1195 /// [changes]: ../io/index.html#platform-specific-behavior
1199 /// This function will return an error in the following situations, but is not
1200 /// limited to just these cases:
1202 /// * User lacks permissions to create directory at `path`.
1203 /// * `path` already exists.
1210 /// # fn foo() -> std::io::Result<()> {
1211 /// try!(fs::create_dir("/some/dir"));
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1217 DirBuilder::new().create(path.as_ref())
1220 /// Recursively create a directory and all of its parent components if they
1223 /// # Platform-specific behavior
1225 /// This function currently corresponds to the `mkdir` function on Unix
1226 /// and the `CreateDirectory` function on Windows.
1227 /// Note that, this [may change in the future][changes].
1228 /// [changes]: ../io/index.html#platform-specific-behavior
1232 /// This function will return an error in the following situations, but is not
1233 /// limited to just these cases:
1235 /// * If any directory in the path specified by `path`
1236 /// does not already exist and it could not be created otherwise. The specific
1237 /// error conditions for when a directory is being created (after it is
1238 /// determined to not exist) are outlined by `fs::create_dir`.
1245 /// # fn foo() -> std::io::Result<()> {
1246 /// try!(fs::create_dir_all("/some/dir"));
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1252 DirBuilder::new().recursive(true).create(path.as_ref())
1255 /// Removes an existing, empty directory.
1257 /// # Platform-specific behavior
1259 /// This function currently corresponds to the `rmdir` function on Unix
1260 /// and the `RemoveDirectory` function on Windows.
1261 /// Note that, this [may change in the future][changes].
1262 /// [changes]: ../io/index.html#platform-specific-behavior
1266 /// This function will return an error in the following situations, but is not
1267 /// limited to just these cases:
1269 /// * The user lacks permissions to remove the directory at the provided `path`.
1270 /// * The directory isn't empty.
1277 /// # fn foo() -> std::io::Result<()> {
1278 /// try!(fs::remove_dir("/some/dir"));
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1284 fs_imp::rmdir(path.as_ref())
1287 /// Removes a directory at this path, after removing all its contents. Use
1290 /// This function does **not** follow symbolic links and it will simply remove the
1291 /// symbolic link itself.
1293 /// # Platform-specific behavior
1295 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1296 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1298 /// Note that, this [may change in the future][changes].
1299 /// [changes]: ../io/index.html#platform-specific-behavior
1303 /// See `file::remove_file` and `fs::remove_dir`.
1310 /// # fn foo() -> std::io::Result<()> {
1311 /// try!(fs::remove_dir_all("/some/dir"));
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1317 fs_imp::remove_dir_all(path.as_ref())
1320 /// Returns an iterator over the entries within a directory.
1322 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1323 /// be encountered after an iterator is initially constructed.
1325 /// # Platform-specific behavior
1327 /// This function currently corresponds to the `opendir` function on Unix
1328 /// and the `FindFirstFile` function on Windows.
1329 /// Note that, this [may change in the future][changes].
1330 /// [changes]: ../io/index.html#platform-specific-behavior
1334 /// This function will return an error in the following situations, but is not
1335 /// limited to just these cases:
1337 /// * The provided `path` doesn't exist.
1338 /// * The process lacks permissions to view the contents.
1339 /// * The `path` points at a non-directory file.
1345 /// use std::fs::{self, DirEntry};
1346 /// use std::path::Path;
1348 /// // one possible implementation of fs::walk_dir only visiting files
1349 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1350 /// if try!(fs::metadata(dir)).is_dir() {
1351 /// for entry in try!(fs::read_dir(dir)) {
1352 /// let entry = try!(entry);
1353 /// if try!(fs::metadata(entry.path())).is_dir() {
1354 /// try!(visit_dirs(&entry.path(), cb));
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1365 fs_imp::readdir(path.as_ref()).map(ReadDir)
1368 /// Returns an iterator that will recursively walk the directory structure
1369 /// rooted at `path`.
1371 /// The path given will not be iterated over, and this will perform iteration in
1372 /// some top-down order. The contents of unreadable subdirectories are ignored.
1374 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1375 /// be encountered after an iterator is initially constructed.
1376 #[unstable(feature = "fs_walk",
1377 reason = "the precise semantics and defaults for a recursive walk \
1378 may change and this may end up accounting for files such \
1379 as symlinks differently",
1381 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1383 #[allow(deprecated)]
1384 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1385 _walk_dir(path.as_ref())
1388 #[allow(deprecated)]
1389 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1390 let start = try!(read_dir(path));
1391 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1394 #[unstable(feature = "fs_walk", issue = "27707")]
1395 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1397 #[allow(deprecated)]
1398 impl Iterator for WalkDir {
1399 type Item = io::Result<DirEntry>;
1401 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1403 if let Some(ref mut cur) = self.cur {
1405 Some(Err(e)) => return Some(Err(e)),
1407 let path = next.path();
1409 self.stack.push(read_dir(&*path));
1411 return Some(Ok(next))
1417 match self.stack.pop() {
1418 Some(Err(e)) => return Some(Err(e)),
1419 Some(Ok(next)) => self.cur = Some(next),
1420 None => return None,
1426 /// Changes the permissions found on a file or a directory.
1428 /// # Platform-specific behavior
1430 /// This function currently corresponds to the `chmod` function on Unix
1431 /// and the `SetFileAttributes` function on Windows.
1432 /// Note that, this [may change in the future][changes].
1433 /// [changes]: ../io/index.html#platform-specific-behavior
1437 /// This function will return an error in the following situations, but is not
1438 /// limited to just these cases:
1440 /// * `path` does not exist.
1441 /// * The user lacks the permission to change attributes of the file.
1446 /// # fn foo() -> std::io::Result<()> {
1449 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1450 /// perms.set_readonly(true);
1451 /// try!(fs::set_permissions("foo.txt", perms));
1455 #[stable(feature = "set_permissions", since = "1.1.0")]
1456 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1458 fs_imp::set_perm(path.as_ref(), perm.0)
1462 /// Creates a new set of options with default mode/security settings for all
1463 /// platforms and also non-recursive.
1464 #[stable(feature = "dir_builder", since = "1.6.0")]
1465 pub fn new() -> DirBuilder {
1467 inner: fs_imp::DirBuilder::new(),
1472 /// Indicate that directories create should be created recursively, creating
1473 /// all parent directories if they do not exist with the same security and
1474 /// permissions settings.
1476 /// This option defaults to `false`
1477 #[stable(feature = "dir_builder", since = "1.6.0")]
1478 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1479 self.recursive = recursive;
1483 /// Create the specified directory with the options configured in this
1489 /// use std::fs::{self, DirBuilder};
1491 /// let path = "/tmp/foo/bar/baz";
1492 /// DirBuilder::new()
1493 /// .recursive(true)
1494 /// .create(path).unwrap();
1496 /// assert!(fs::metadata(path).unwrap().is_dir());
1498 #[stable(feature = "dir_builder", since = "1.6.0")]
1499 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1500 self._create(path.as_ref())
1503 fn _create(&self, path: &Path) -> io::Result<()> {
1505 self.create_dir_all(path)
1507 self.inner.mkdir(path)
1511 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1512 if path == Path::new("") || path.is_dir() { return Ok(()) }
1513 if let Some(p) = path.parent() {
1514 try!(self.create_dir_all(p))
1516 self.inner.mkdir(path)
1520 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1521 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1532 use fs::{self, File, OpenOptions};
1533 use io::{ErrorKind, SeekFrom};
1534 use path::{Path, PathBuf};
1535 use rand::{self, StdRng, Rng};
1539 use os::windows::fs::{symlink_dir, symlink_file};
1541 use sys::fs::symlink_junction;
1543 use os::unix::fs::symlink as symlink_dir;
1545 use os::unix::fs::symlink as symlink_file;
1547 use os::unix::fs::symlink as symlink_junction;
1549 macro_rules! check { ($e:expr) => (
1552 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1556 macro_rules! error { ($e:expr, $s:expr) => (
1558 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1559 Err(ref err) => assert!(err.to_string().contains($s),
1560 format!("`{}` did not contain `{}`", err, $s))
1564 pub struct TempDir(PathBuf);
1567 fn join(&self, path: &str) -> PathBuf {
1568 let TempDir(ref p) = *self;
1572 fn path<'a>(&'a self) -> &'a Path {
1573 let TempDir(ref p) = *self;
1578 impl Drop for TempDir {
1579 fn drop(&mut self) {
1580 // Gee, seeing how we're testing the fs module I sure hope that we
1581 // at least implement this correctly!
1582 let TempDir(ref p) = *self;
1583 check!(fs::remove_dir_all(p));
1587 pub fn tmpdir() -> TempDir {
1588 let p = env::temp_dir();
1589 let mut r = rand::thread_rng();
1590 let ret = p.join(&format!("rust-{}", r.next_u32()));
1591 check!(fs::create_dir(&ret));
1595 // Several test fail on windows if the user does not have permission to
1596 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
1597 // disabling these test on Windows, use this function to test whether we
1598 // have permission, and return otherwise. This way, we still don't run these
1599 // tests most of the time, but at least we do if the user has the right
1601 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
1602 if cfg!(unix) { return true }
1603 let link = tmpdir.join("some_hopefully_unique_link_name");
1605 match symlink_file(r"nonexisting_target", link) {
1608 if err.to_string().contains("A required privilege is not held by the client.") {
1617 fn file_test_io_smoke_test() {
1618 let message = "it's alright. have a good time";
1619 let tmpdir = tmpdir();
1620 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1622 let mut write_stream = check!(File::create(filename));
1623 check!(write_stream.write(message.as_bytes()));
1626 let mut read_stream = check!(File::open(filename));
1627 let mut read_buf = [0; 1028];
1628 let read_str = match check!(read_stream.read(&mut read_buf)) {
1629 0 => panic!("shouldn't happen"),
1630 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1632 assert_eq!(read_str, message);
1634 check!(fs::remove_file(filename));
1638 fn invalid_path_raises() {
1639 let tmpdir = tmpdir();
1640 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1641 let result = File::open(filename);
1644 error!(result, "o such file or directory");
1647 error!(result, "The system cannot find the file specified");
1652 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1653 let tmpdir = tmpdir();
1654 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1656 let result = fs::remove_file(filename);
1659 error!(result, "o such file or directory");
1662 error!(result, "The system cannot find the file specified");
1667 fn file_test_io_non_positional_read() {
1668 let message: &str = "ten-four";
1669 let mut read_mem = [0; 8];
1670 let tmpdir = tmpdir();
1671 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1673 let mut rw_stream = check!(File::create(filename));
1674 check!(rw_stream.write(message.as_bytes()));
1677 let mut read_stream = check!(File::open(filename));
1679 let read_buf = &mut read_mem[0..4];
1680 check!(read_stream.read(read_buf));
1683 let read_buf = &mut read_mem[4..8];
1684 check!(read_stream.read(read_buf));
1687 check!(fs::remove_file(filename));
1688 let read_str = str::from_utf8(&read_mem).unwrap();
1689 assert_eq!(read_str, message);
1693 fn file_test_io_seek_and_tell_smoke_test() {
1694 let message = "ten-four";
1695 let mut read_mem = [0; 4];
1696 let set_cursor = 4 as u64;
1697 let tell_pos_pre_read;
1698 let tell_pos_post_read;
1699 let tmpdir = tmpdir();
1700 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1702 let mut rw_stream = check!(File::create(filename));
1703 check!(rw_stream.write(message.as_bytes()));
1706 let mut read_stream = check!(File::open(filename));
1707 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1708 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1709 check!(read_stream.read(&mut read_mem));
1710 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1712 check!(fs::remove_file(filename));
1713 let read_str = str::from_utf8(&read_mem).unwrap();
1714 assert_eq!(read_str, &message[4..8]);
1715 assert_eq!(tell_pos_pre_read, set_cursor);
1716 assert_eq!(tell_pos_post_read, message.len() as u64);
1720 fn file_test_io_seek_and_write() {
1721 let initial_msg = "food-is-yummy";
1722 let overwrite_msg = "-the-bar!!";
1723 let final_msg = "foo-the-bar!!";
1725 let mut read_mem = [0; 13];
1726 let tmpdir = tmpdir();
1727 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1729 let mut rw_stream = check!(File::create(filename));
1730 check!(rw_stream.write(initial_msg.as_bytes()));
1731 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1732 check!(rw_stream.write(overwrite_msg.as_bytes()));
1735 let mut read_stream = check!(File::open(filename));
1736 check!(read_stream.read(&mut read_mem));
1738 check!(fs::remove_file(filename));
1739 let read_str = str::from_utf8(&read_mem).unwrap();
1740 assert!(read_str == final_msg);
1744 fn file_test_io_seek_shakedown() {
1746 let initial_msg = "qwer-asdf-zxcv";
1747 let chunk_one: &str = "qwer";
1748 let chunk_two: &str = "asdf";
1749 let chunk_three: &str = "zxcv";
1750 let mut read_mem = [0; 4];
1751 let tmpdir = tmpdir();
1752 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1754 let mut rw_stream = check!(File::create(filename));
1755 check!(rw_stream.write(initial_msg.as_bytes()));
1758 let mut read_stream = check!(File::open(filename));
1760 check!(read_stream.seek(SeekFrom::End(-4)));
1761 check!(read_stream.read(&mut read_mem));
1762 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1764 check!(read_stream.seek(SeekFrom::Current(-9)));
1765 check!(read_stream.read(&mut read_mem));
1766 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1768 check!(read_stream.seek(SeekFrom::Start(0)));
1769 check!(read_stream.read(&mut read_mem));
1770 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1772 check!(fs::remove_file(filename));
1776 fn file_test_stat_is_correct_on_is_file() {
1777 let tmpdir = tmpdir();
1778 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1780 let mut opts = OpenOptions::new();
1781 let mut fs = check!(opts.read(true).write(true)
1782 .create(true).open(filename));
1784 fs.write(msg.as_bytes()).unwrap();
1786 let fstat_res = check!(fs.metadata());
1787 assert!(fstat_res.is_file());
1789 let stat_res_fn = check!(fs::metadata(filename));
1790 assert!(stat_res_fn.is_file());
1791 let stat_res_meth = check!(filename.metadata());
1792 assert!(stat_res_meth.is_file());
1793 check!(fs::remove_file(filename));
1797 fn file_test_stat_is_correct_on_is_dir() {
1798 let tmpdir = tmpdir();
1799 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1800 check!(fs::create_dir(filename));
1801 let stat_res_fn = check!(fs::metadata(filename));
1802 assert!(stat_res_fn.is_dir());
1803 let stat_res_meth = check!(filename.metadata());
1804 assert!(stat_res_meth.is_dir());
1805 check!(fs::remove_dir(filename));
1809 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1810 let tmpdir = tmpdir();
1811 let dir = &tmpdir.join("fileinfo_false_on_dir");
1812 check!(fs::create_dir(dir));
1813 assert!(dir.is_file() == false);
1814 check!(fs::remove_dir(dir));
1818 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1819 let tmpdir = tmpdir();
1820 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1821 check!(check!(File::create(file)).write(b"foo"));
1822 assert!(file.exists());
1823 check!(fs::remove_file(file));
1824 assert!(!file.exists());
1828 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1829 let tmpdir = tmpdir();
1830 let dir = &tmpdir.join("before_and_after_dir");
1831 assert!(!dir.exists());
1832 check!(fs::create_dir(dir));
1833 assert!(dir.exists());
1834 assert!(dir.is_dir());
1835 check!(fs::remove_dir(dir));
1836 assert!(!dir.exists());
1840 fn file_test_directoryinfo_readdir() {
1841 let tmpdir = tmpdir();
1842 let dir = &tmpdir.join("di_readdir");
1843 check!(fs::create_dir(dir));
1846 let f = dir.join(&format!("{}.txt", n));
1847 let mut w = check!(File::create(&f));
1848 let msg_str = format!("{}{}", prefix, n.to_string());
1849 let msg = msg_str.as_bytes();
1850 check!(w.write(msg));
1852 let files = check!(fs::read_dir(dir));
1853 let mut mem = [0; 4];
1855 let f = f.unwrap().path();
1857 let n = f.file_stem().unwrap();
1858 check!(check!(File::open(&f)).read(&mut mem));
1859 let read_str = str::from_utf8(&mem).unwrap();
1860 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1861 assert_eq!(expected, read_str);
1863 check!(fs::remove_file(&f));
1865 check!(fs::remove_dir(dir));
1869 #[allow(deprecated)]
1870 fn file_test_walk_dir() {
1871 let tmpdir = tmpdir();
1872 let dir = &tmpdir.join("walk_dir");
1873 check!(fs::create_dir(dir));
1875 let dir1 = &dir.join("01/02/03");
1876 check!(fs::create_dir_all(dir1));
1877 check!(File::create(&dir1.join("04")));
1879 let dir2 = &dir.join("11/12/13");
1880 check!(fs::create_dir_all(dir2));
1881 check!(File::create(&dir2.join("14")));
1883 let files = check!(fs::walk_dir(dir));
1884 let mut cur = [0; 2];
1886 let f = f.unwrap().path();
1887 let stem = f.file_stem().unwrap().to_str().unwrap();
1888 let root = stem.as_bytes()[0] - b'0';
1889 let name = stem.as_bytes()[1] - b'0';
1890 assert!(cur[root as usize] < name);
1891 cur[root as usize] = name;
1894 check!(fs::remove_dir_all(dir));
1898 fn mkdir_path_already_exists_error() {
1899 let tmpdir = tmpdir();
1900 let dir = &tmpdir.join("mkdir_error_twice");
1901 check!(fs::create_dir(dir));
1902 let e = fs::create_dir(dir).err().unwrap();
1903 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1907 fn recursive_mkdir() {
1908 let tmpdir = tmpdir();
1909 let dir = tmpdir.join("d1/d2");
1910 check!(fs::create_dir_all(&dir));
1911 assert!(dir.is_dir())
1915 fn recursive_mkdir_failure() {
1916 let tmpdir = tmpdir();
1917 let dir = tmpdir.join("d1");
1918 let file = dir.join("f1");
1920 check!(fs::create_dir_all(&dir));
1921 check!(File::create(&file));
1923 let result = fs::create_dir_all(&file);
1925 assert!(result.is_err());
1929 fn recursive_mkdir_slash() {
1930 check!(fs::create_dir_all(&Path::new("/")));
1934 fn recursive_rmdir() {
1935 let tmpdir = tmpdir();
1936 let d1 = tmpdir.join("d1");
1937 let dt = d1.join("t");
1938 let dtt = dt.join("t");
1939 let d2 = tmpdir.join("d2");
1940 let canary = d2.join("do_not_delete");
1941 check!(fs::create_dir_all(&dtt));
1942 check!(fs::create_dir_all(&d2));
1943 check!(check!(File::create(&canary)).write(b"foo"));
1944 check!(symlink_junction(&d2, &dt.join("d2")));
1945 let _ = symlink_file(&canary, &d1.join("canary"));
1946 check!(fs::remove_dir_all(&d1));
1948 assert!(!d1.is_dir());
1949 assert!(canary.exists());
1953 fn recursive_rmdir_of_symlink() {
1954 // test we do not recursively delete a symlink but only dirs.
1955 let tmpdir = tmpdir();
1956 let link = tmpdir.join("d1");
1957 let dir = tmpdir.join("d2");
1958 let canary = dir.join("do_not_delete");
1959 check!(fs::create_dir_all(&dir));
1960 check!(check!(File::create(&canary)).write(b"foo"));
1961 check!(symlink_junction(&dir, &link));
1962 check!(fs::remove_dir_all(&link));
1964 assert!(!link.is_dir());
1965 assert!(canary.exists());
1969 // only Windows makes a distinction between file and directory symlinks.
1971 fn recursive_rmdir_of_file_symlink() {
1972 let tmpdir = tmpdir();
1973 if !got_symlink_permission(&tmpdir) { return };
1975 let f1 = tmpdir.join("f1");
1976 let f2 = tmpdir.join("f2");
1977 check!(check!(File::create(&f1)).write(b"foo"));
1978 check!(symlink_file(&f1, &f2));
1979 match fs::remove_dir_all(&f2) {
1980 Ok(..) => panic!("wanted a failure"),
1986 fn unicode_path_is_dir() {
1987 assert!(Path::new(".").is_dir());
1988 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
1990 let tmpdir = tmpdir();
1992 let mut dirpath = tmpdir.path().to_path_buf();
1993 dirpath.push("test-가一ー你好");
1994 check!(fs::create_dir(&dirpath));
1995 assert!(dirpath.is_dir());
1997 let mut filepath = dirpath;
1998 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1999 check!(File::create(&filepath)); // ignore return; touch only
2000 assert!(!filepath.is_dir());
2001 assert!(filepath.exists());
2005 fn unicode_path_exists() {
2006 assert!(Path::new(".").exists());
2007 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2009 let tmpdir = tmpdir();
2010 let unicode = tmpdir.path();
2011 let unicode = unicode.join(&format!("test-각丁ー再见"));
2012 check!(fs::create_dir(&unicode));
2013 assert!(unicode.exists());
2014 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2018 fn copy_file_does_not_exist() {
2019 let from = Path::new("test/nonexistent-bogus-path");
2020 let to = Path::new("test/other-bogus-path");
2022 match fs::copy(&from, &to) {
2025 assert!(!from.exists());
2026 assert!(!to.exists());
2032 fn copy_src_does_not_exist() {
2033 let tmpdir = tmpdir();
2034 let from = Path::new("test/nonexistent-bogus-path");
2035 let to = tmpdir.join("out.txt");
2036 check!(check!(File::create(&to)).write(b"hello"));
2037 assert!(fs::copy(&from, &to).is_err());
2038 assert!(!from.exists());
2039 let mut v = Vec::new();
2040 check!(check!(File::open(&to)).read_to_end(&mut v));
2041 assert_eq!(v, b"hello");
2046 let tmpdir = tmpdir();
2047 let input = tmpdir.join("in.txt");
2048 let out = tmpdir.join("out.txt");
2050 check!(check!(File::create(&input)).write(b"hello"));
2051 check!(fs::copy(&input, &out));
2052 let mut v = Vec::new();
2053 check!(check!(File::open(&out)).read_to_end(&mut v));
2054 assert_eq!(v, b"hello");
2056 assert_eq!(check!(input.metadata()).permissions(),
2057 check!(out.metadata()).permissions());
2061 fn copy_file_dst_dir() {
2062 let tmpdir = tmpdir();
2063 let out = tmpdir.join("out");
2065 check!(File::create(&out));
2066 match fs::copy(&*out, tmpdir.path()) {
2067 Ok(..) => panic!(), Err(..) => {}
2072 fn copy_file_dst_exists() {
2073 let tmpdir = tmpdir();
2074 let input = tmpdir.join("in");
2075 let output = tmpdir.join("out");
2077 check!(check!(File::create(&input)).write("foo".as_bytes()));
2078 check!(check!(File::create(&output)).write("bar".as_bytes()));
2079 check!(fs::copy(&input, &output));
2081 let mut v = Vec::new();
2082 check!(check!(File::open(&output)).read_to_end(&mut v));
2083 assert_eq!(v, b"foo".to_vec());
2087 fn copy_file_src_dir() {
2088 let tmpdir = tmpdir();
2089 let out = tmpdir.join("out");
2091 match fs::copy(tmpdir.path(), &out) {
2092 Ok(..) => panic!(), Err(..) => {}
2094 assert!(!out.exists());
2098 fn copy_file_preserves_perm_bits() {
2099 let tmpdir = tmpdir();
2100 let input = tmpdir.join("in.txt");
2101 let out = tmpdir.join("out.txt");
2103 let attr = check!(check!(File::create(&input)).metadata());
2104 let mut p = attr.permissions();
2105 p.set_readonly(true);
2106 check!(fs::set_permissions(&input, p));
2107 check!(fs::copy(&input, &out));
2108 assert!(check!(out.metadata()).permissions().readonly());
2109 check!(fs::set_permissions(&input, attr.permissions()));
2110 check!(fs::set_permissions(&out, attr.permissions()));
2115 fn copy_file_preserves_streams() {
2117 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2118 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2119 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2120 let mut v = Vec::new();
2121 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2122 assert_eq!(v, b"carrot".to_vec());
2126 fn symlinks_work() {
2127 let tmpdir = tmpdir();
2128 if !got_symlink_permission(&tmpdir) { return };
2130 let input = tmpdir.join("in.txt");
2131 let out = tmpdir.join("out.txt");
2133 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2134 check!(symlink_file(&input, &out));
2135 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2136 assert_eq!(check!(fs::metadata(&out)).len(),
2137 check!(fs::metadata(&input)).len());
2138 let mut v = Vec::new();
2139 check!(check!(File::open(&out)).read_to_end(&mut v));
2140 assert_eq!(v, b"foobar".to_vec());
2144 fn symlink_noexist() {
2145 // Symlinks can point to things that don't exist
2146 let tmpdir = tmpdir();
2147 if !got_symlink_permission(&tmpdir) { return };
2149 // Use a relative path for testing. Symlinks get normalized by Windows,
2150 // so we may not get the same path back for absolute paths
2151 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2152 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2159 // directory symlink
2160 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2163 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2164 r"C:\Users\Default");
2165 // junction with special permissions
2166 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2169 let tmpdir = tmpdir();
2170 let link = tmpdir.join("link");
2171 if !got_symlink_permission(&tmpdir) { return };
2172 check!(symlink_file(&"foo", &link));
2173 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2177 fn readlink_not_symlink() {
2178 let tmpdir = tmpdir();
2179 match fs::read_link(tmpdir.path()) {
2180 Ok(..) => panic!("wanted a failure"),
2187 let tmpdir = tmpdir();
2188 let input = tmpdir.join("in.txt");
2189 let out = tmpdir.join("out.txt");
2191 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2192 check!(fs::hard_link(&input, &out));
2193 assert_eq!(check!(fs::metadata(&out)).len(),
2194 check!(fs::metadata(&input)).len());
2195 assert_eq!(check!(fs::metadata(&out)).len(),
2196 check!(input.metadata()).len());
2197 let mut v = Vec::new();
2198 check!(check!(File::open(&out)).read_to_end(&mut v));
2199 assert_eq!(v, b"foobar".to_vec());
2201 // can't link to yourself
2202 match fs::hard_link(&input, &input) {
2203 Ok(..) => panic!("wanted a failure"),
2206 // can't link to something that doesn't exist
2207 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2208 Ok(..) => panic!("wanted a failure"),
2215 let tmpdir = tmpdir();
2216 let file = tmpdir.join("in.txt");
2218 check!(File::create(&file));
2219 let attr = check!(fs::metadata(&file));
2220 assert!(!attr.permissions().readonly());
2221 let mut p = attr.permissions();
2222 p.set_readonly(true);
2223 check!(fs::set_permissions(&file, p.clone()));
2224 let attr = check!(fs::metadata(&file));
2225 assert!(attr.permissions().readonly());
2227 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2228 Ok(..) => panic!("wanted an error"),
2232 p.set_readonly(false);
2233 check!(fs::set_permissions(&file, p));
2237 fn sync_doesnt_kill_anything() {
2238 let tmpdir = tmpdir();
2239 let path = tmpdir.join("in.txt");
2241 let mut file = check!(File::create(&path));
2242 check!(file.sync_all());
2243 check!(file.sync_data());
2244 check!(file.write(b"foo"));
2245 check!(file.sync_all());
2246 check!(file.sync_data());
2250 fn truncate_works() {
2251 let tmpdir = tmpdir();
2252 let path = tmpdir.join("in.txt");
2254 let mut file = check!(File::create(&path));
2255 check!(file.write(b"foo"));
2256 check!(file.sync_all());
2258 // Do some simple things with truncation
2259 assert_eq!(check!(file.metadata()).len(), 3);
2260 check!(file.set_len(10));
2261 assert_eq!(check!(file.metadata()).len(), 10);
2262 check!(file.write(b"bar"));
2263 check!(file.sync_all());
2264 assert_eq!(check!(file.metadata()).len(), 10);
2266 let mut v = Vec::new();
2267 check!(check!(File::open(&path)).read_to_end(&mut v));
2268 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2270 // Truncate to a smaller length, don't seek, and then write something.
2271 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2272 // past the end of the file).
2273 check!(file.set_len(2));
2274 assert_eq!(check!(file.metadata()).len(), 2);
2275 check!(file.write(b"wut"));
2276 check!(file.sync_all());
2277 assert_eq!(check!(file.metadata()).len(), 9);
2278 let mut v = Vec::new();
2279 check!(check!(File::open(&path)).read_to_end(&mut v));
2280 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2285 use fs::OpenOptions as OO;
2286 fn c<T: Clone>(t: &T) -> T { t.clone() }
2288 let tmpdir = tmpdir();
2290 let mut r = OO::new(); r.read(true);
2291 let mut w = OO::new(); w.write(true);
2292 let mut rw = OO::new(); rw.read(true).write(true);
2293 let mut a = OO::new(); a.append(true);
2294 let mut ra = OO::new(); ra.read(true).append(true);
2296 let invalid_options = if cfg!(windows) { "The parameter is incorrect" }
2297 else { "Invalid argument" };
2299 // Test various combinations of creation modes and access modes.
2302 // creation mode | read | write | read-write | append | read-append |
2303 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2304 // not set (open existing) | X | X | X | X | X |
2305 // create | | X | X | X | X |
2306 // truncate | | X | X | | |
2307 // create and truncate | | X | X | | |
2308 // create_new | | X | X | X | X |
2310 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2313 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2314 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2315 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2316 check!(c(&w).create(true).open(&tmpdir.join("a")));
2317 check!(c(&w).open(&tmpdir.join("a")));
2320 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2321 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2322 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2323 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2324 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2327 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2328 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2329 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2330 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2331 check!(c(&rw).open(&tmpdir.join("c")));
2334 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2335 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2336 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2337 check!(c(&a).create(true).open(&tmpdir.join("d")));
2338 check!(c(&a).open(&tmpdir.join("d")));
2341 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2342 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2343 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2344 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2345 check!(c(&ra).open(&tmpdir.join("e")));
2347 // Test opening a file without setting an access mode
2348 let mut blank = OO::new();
2349 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2352 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2354 // Test write fails for read-only
2355 check!(r.open(&tmpdir.join("h")));
2357 let mut f = check!(r.open(&tmpdir.join("h")));
2358 assert!(f.write("wut".as_bytes()).is_err());
2361 // Test write overwrites
2363 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2364 check!(f.write("baz".as_bytes()));
2367 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2368 let mut b = vec![0; 6];
2369 check!(f.read(&mut b));
2370 assert_eq!(b, "bazbar".as_bytes());
2373 // Test truncate works
2375 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2376 check!(f.write("foo".as_bytes()));
2378 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2380 // Test append works
2381 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2383 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2384 check!(f.write("bar".as_bytes()));
2386 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2388 // Test .append(true) equals .write(true).append(true)
2390 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2391 check!(f.write("baz".as_bytes()));
2393 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2397 fn _assert_send_sync() {
2398 fn _assert_send_sync<T: Send + Sync>() {}
2399 _assert_send_sync::<OpenOptions>();
2404 let mut bytes = [0; 1024];
2405 StdRng::new().unwrap().fill_bytes(&mut bytes);
2407 let tmpdir = tmpdir();
2409 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2410 let mut v = Vec::new();
2411 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2412 assert!(v == &bytes[..]);
2416 fn file_try_clone() {
2417 let tmpdir = tmpdir();
2419 let mut f1 = check!(OpenOptions::new()
2423 .open(&tmpdir.join("test")));
2424 let mut f2 = check!(f1.try_clone());
2426 check!(f1.write_all(b"hello world"));
2427 check!(f1.seek(SeekFrom::Start(2)));
2429 let mut buf = vec![];
2430 check!(f2.read_to_end(&mut buf));
2431 assert_eq!(buf, b"llo world");
2434 check!(f1.write_all(b"!"));
2438 #[cfg(not(windows))]
2439 fn unlink_readonly() {
2440 let tmpdir = tmpdir();
2441 let path = tmpdir.join("file");
2442 check!(File::create(&path));
2443 let mut perm = check!(fs::metadata(&path)).permissions();
2444 perm.set_readonly(true);
2445 check!(fs::set_permissions(&path, perm));
2446 check!(fs::remove_file(&path));
2450 fn mkdir_trailing_slash() {
2451 let tmpdir = tmpdir();
2452 let path = tmpdir.join("file");
2453 check!(fs::create_dir_all(&path.join("a/")));
2457 fn canonicalize_works_simple() {
2458 let tmpdir = tmpdir();
2459 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2460 let file = tmpdir.join("test");
2461 File::create(&file).unwrap();
2462 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2466 fn realpath_works() {
2467 let tmpdir = tmpdir();
2468 if !got_symlink_permission(&tmpdir) { return };
2470 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2471 let file = tmpdir.join("test");
2472 let dir = tmpdir.join("test2");
2473 let link = dir.join("link");
2474 let linkdir = tmpdir.join("test3");
2476 File::create(&file).unwrap();
2477 fs::create_dir(&dir).unwrap();
2478 symlink_file(&file, &link).unwrap();
2479 symlink_dir(&dir, &linkdir).unwrap();
2481 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2483 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2484 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2485 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2486 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2487 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2491 fn realpath_works_tricky() {
2492 let tmpdir = tmpdir();
2493 if !got_symlink_permission(&tmpdir) { return };
2495 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2496 let a = tmpdir.join("a");
2497 let b = a.join("b");
2498 let c = b.join("c");
2499 let d = a.join("d");
2500 let e = d.join("e");
2501 let f = a.join("f");
2503 fs::create_dir_all(&b).unwrap();
2504 fs::create_dir_all(&d).unwrap();
2505 File::create(&f).unwrap();
2506 if cfg!(not(windows)) {
2507 symlink_dir("../d/e", &c).unwrap();
2508 symlink_file("../f", &e).unwrap();
2511 symlink_dir(r"..\d\e", &c).unwrap();
2512 symlink_file(r"..\f", &e).unwrap();
2515 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2516 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2520 fn dir_entry_methods() {
2521 let tmpdir = tmpdir();
2523 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2524 File::create(&tmpdir.join("b")).unwrap();
2526 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2527 let fname = file.file_name();
2528 match fname.to_str() {
2530 assert!(file.file_type().unwrap().is_dir());
2531 assert!(file.metadata().unwrap().is_dir());
2534 assert!(file.file_type().unwrap().is_file());
2535 assert!(file.metadata().unwrap().is_file());
2537 f => panic!("unknown file name: {:?}", f),
2543 fn read_dir_not_found() {
2544 let res = fs::read_dir("/path/that/does/not/exist");
2545 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
2549 fn create_dir_all_with_junctions() {
2550 let tmpdir = tmpdir();
2551 let target = tmpdir.join("target");
2553 let junction = tmpdir.join("junction");
2554 let b = junction.join("a/b");
2556 let link = tmpdir.join("link");
2557 let d = link.join("c/d");
2559 fs::create_dir(&target).unwrap();
2561 check!(symlink_junction(&target, &junction));
2562 check!(fs::create_dir_all(&b));
2563 // the junction itself is not a directory, but `is_dir()` on a Path
2565 assert!(junction.is_dir());
2566 assert!(b.exists());
2568 if !got_symlink_permission(&tmpdir) { return };
2569 check!(symlink_dir(&target, &link));
2570 check!(fs::create_dir_all(&d));
2571 assert!(link.is_dir());
2572 assert!(d.exists());
2576 fn metadata_access_times() {
2577 let tmpdir = tmpdir();
2579 let b = tmpdir.join("b");
2580 File::create(&b).unwrap();
2582 let a = check!(fs::metadata(&tmpdir.path()));
2583 let b = check!(fs::metadata(&b));
2585 assert_eq!(check!(a.accessed()), check!(a.accessed()));
2586 assert_eq!(check!(a.modified()), check!(a.modified()));
2587 assert_eq!(check!(b.accessed()), check!(b.modified()));
2589 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
2590 check!(a.created());
2591 check!(b.created());