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};
28 /// A reference to an open file on the filesystem.
30 /// An instance of a `File` can be read and/or written depending on what options
31 /// it was opened with. Files also implement `Seek` to alter the logical cursor
32 /// that the file contains internally.
34 /// Files are automatically closed when they go out of scope.
38 /// Create a new file and write bytes to it:
41 /// use std::fs::File;
42 /// use std::io::prelude::*;
44 /// # fn foo() -> std::io::Result<()> {
45 /// let mut file = File::create("foo.txt")?;
46 /// file.write_all(b"Hello, world!")?;
51 /// Read the contents of a file into a `String`:
54 /// use std::fs::File;
55 /// use std::io::prelude::*;
57 /// # fn foo() -> std::io::Result<()> {
58 /// let mut file = File::open("foo.txt")?;
59 /// let mut contents = String::new();
60 /// file.read_to_string(&mut contents)?;
61 /// assert_eq!(contents, "Hello, world!");
66 /// It can be more efficient to read the contents of a file with a buffered
67 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
70 /// use std::fs::File;
71 /// use std::io::BufReader;
72 /// use std::io::prelude::*;
74 /// # fn foo() -> std::io::Result<()> {
75 /// let file = File::open("foo.txt")?;
76 /// let mut buf_reader = BufReader::new(file);
77 /// let mut contents = String::new();
78 /// buf_reader.read_to_string(&mut contents)?;
79 /// assert_eq!(contents, "Hello, world!");
84 /// [`Read`]: ../io/trait.Read.html
85 /// [`BufReader<R>`]: ../io/struct.BufReader.html
86 #[stable(feature = "rust1", since = "1.0.0")]
91 /// Metadata information about a file.
93 /// This structure is returned from the [`metadata`] or
94 /// [`symlink_metadata`] function or method and represents known
95 /// metadata about a file such as its permissions, size, modification
98 /// [`metadata`]: fn.metadata.html
99 /// [`symlink_metadata`]: fn.symlink_metadata.html
100 #[stable(feature = "rust1", since = "1.0.0")]
102 pub struct Metadata(fs_imp::FileAttr);
104 /// Iterator over the entries in a directory.
106 /// This iterator is returned from the [`read_dir`] function of this module and
107 /// will yield instances of `io::Result<DirEntry>`. Through a [`DirEntry`]
108 /// information like the entry's path and possibly other metadata can be
111 /// [`read_dir`]: fn.read_dir.html
112 /// [`DirEntry`]: struct.DirEntry.html
116 /// This [`io::Result`] will be an `Err` if there's some sort of intermittent
117 /// IO error during iteration.
119 /// [`io::Result`]: ../io/type.Result.html
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub struct ReadDir(fs_imp::ReadDir);
124 /// Entries returned by the [`ReadDir`] iterator.
126 /// [`ReadDir`]: struct.ReadDir.html
128 /// An instance of `DirEntry` represents an entry inside of a directory on the
129 /// filesystem. Each entry can be inspected via methods to learn about the full
130 /// path or possibly other metadata through per-platform extension traits.
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub struct DirEntry(fs_imp::DirEntry);
134 /// Options and flags which can be used to configure how a file is opened.
136 /// This builder exposes the ability to configure how a [`File`] is opened and
137 /// what operations are permitted on the open file. The [`File::open`] and
138 /// [`File::create`] methods are aliases for commonly used options using this
141 /// [`File`]: struct.File.html
142 /// [`File::open`]: struct.File.html#method.open
143 /// [`File::create`]: struct.File.html#method.create
145 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
146 /// then chain calls to methods to set each option, then call [`open`],
147 /// passing the path of the file you're trying to open. This will give you a
148 /// [`io::Result`][result] with a [`File`][file] inside that you can further
151 /// [`new`]: struct.OpenOptions.html#method.new
152 /// [`open`]: struct.OpenOptions.html#method.open
153 /// [result]: ../io/type.Result.html
154 /// [file]: struct.File.html
158 /// Opening a file to read:
161 /// use std::fs::OpenOptions;
163 /// let file = OpenOptions::new().read(true).open("foo.txt");
166 /// Opening a file for both reading and writing, as well as creating it if it
170 /// use std::fs::OpenOptions;
172 /// let file = OpenOptions::new()
176 /// .open("foo.txt");
178 #[derive(Clone, Debug)]
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct OpenOptions(fs_imp::OpenOptions);
182 /// Representation of the various permissions on a file.
184 /// This module only currently provides one bit of information, [`readonly`],
185 /// which is exposed on all currently supported platforms. Unix-specific
186 /// functionality, such as mode bits, is available through the
187 /// `os::unix::PermissionsExt` trait.
189 /// [`readonly`]: struct.Permissions.html#method.readonly
190 #[derive(Clone, PartialEq, Eq, Debug)]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct Permissions(fs_imp::FilePermissions);
194 /// A structure representing a type of file with accessors for each file type.
195 /// It is returned by [`Metadata::file_type`] method.
197 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
198 #[stable(feature = "file_type", since = "1.1.0")]
199 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
200 pub struct FileType(fs_imp::FileType);
202 /// A builder used to create directories in various manners.
204 /// This builder also supports platform-specific options.
205 #[stable(feature = "dir_builder", since = "1.6.0")]
207 pub struct DirBuilder {
208 inner: fs_imp::DirBuilder,
213 /// Attempts to open a file in read-only mode.
215 /// See the [`OpenOptions::open`] method for more details.
219 /// This function will return an error if `path` does not already exist.
220 /// Other errors may also be returned according to [`OpenOptions::open`].
222 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
227 /// use std::fs::File;
229 /// # fn foo() -> std::io::Result<()> {
230 /// let mut f = File::open("foo.txt")?;
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
236 OpenOptions::new().read(true).open(path.as_ref())
239 /// Opens a file in write-only mode.
241 /// This function will create a file if it does not exist,
242 /// and will truncate it if it does.
244 /// See the [`OpenOptions::open`] function for more details.
246 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
251 /// use std::fs::File;
253 /// # fn foo() -> std::io::Result<()> {
254 /// let mut f = File::create("foo.txt")?;
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
260 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
263 /// Attempts to sync all OS-internal metadata to disk.
265 /// This function will attempt to ensure that all in-core data reaches the
266 /// filesystem before returning.
271 /// use std::fs::File;
272 /// use std::io::prelude::*;
274 /// # fn foo() -> std::io::Result<()> {
275 /// let mut f = File::create("foo.txt")?;
276 /// f.write_all(b"Hello, world!")?;
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn sync_all(&self) -> io::Result<()> {
287 /// This function is similar to [`sync_all`], except that it may not
288 /// synchronize file metadata to the filesystem.
290 /// This is intended for use cases that must synchronize content, but don't
291 /// need the metadata on disk. The goal of this method is to reduce disk
294 /// Note that some platforms may simply implement this in terms of
297 /// [`sync_all`]: struct.File.html#method.sync_all
302 /// use std::fs::File;
303 /// use std::io::prelude::*;
305 /// # fn foo() -> std::io::Result<()> {
306 /// let mut f = File::create("foo.txt")?;
307 /// f.write_all(b"Hello, world!")?;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn sync_data(&self) -> io::Result<()> {
315 self.inner.datasync()
318 /// Truncates or extends the underlying file, updating the size of
319 /// this file to become `size`.
321 /// If the `size` is less than the current file's size, then the file will
322 /// be shrunk. If it is greater than the current file's size, then the file
323 /// will be extended to `size` and have all of the intermediate data filled
328 /// This function will return an error if the file is not opened for writing.
333 /// use std::fs::File;
335 /// # fn foo() -> std::io::Result<()> {
336 /// let mut f = File::create("foo.txt")?;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn set_len(&self, size: u64) -> io::Result<()> {
343 self.inner.truncate(size)
346 /// Queries metadata about the underlying file.
351 /// use std::fs::File;
353 /// # fn foo() -> std::io::Result<()> {
354 /// let mut f = File::open("foo.txt")?;
355 /// let metadata = f.metadata()?;
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn metadata(&self) -> io::Result<Metadata> {
361 self.inner.file_attr().map(Metadata)
364 /// Creates a new independently owned handle to the underlying file.
366 /// The returned `File` is a reference to the same state that this object
367 /// references. Both handles will read and write with the same cursor
373 /// use std::fs::File;
375 /// # fn foo() -> std::io::Result<()> {
376 /// let mut f = File::open("foo.txt")?;
377 /// let file_copy = f.try_clone()?;
381 #[stable(feature = "file_try_clone", since = "1.9.0")]
382 pub fn try_clone(&self) -> io::Result<File> {
384 inner: self.inner.duplicate()?
388 /// Changes the permissions on the underlying file.
390 /// # Platform-specific behavior
392 /// This function currently corresponds to the `fchmod` function on Unix and
393 /// the `SetFileInformationByHandle` function on Windows. Note that, this
394 /// [may change in the future][changes].
396 /// [changes]: ../io/index.html#platform-specific-behavior
400 /// This function will return an error if the user lacks permission change
401 /// attributes on the underlying file. It may also return an error in other
402 /// os-specific unspecified cases.
407 /// # fn foo() -> std::io::Result<()> {
408 /// use std::fs::File;
410 /// let file = File::open("foo.txt")?;
411 /// let mut perms = file.metadata()?.permissions();
412 /// perms.set_readonly(true);
413 /// file.set_permissions(perms)?;
417 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
418 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
419 self.inner.set_permissions(perm.0)
423 impl AsInner<fs_imp::File> for File {
424 fn as_inner(&self) -> &fs_imp::File { &self.inner }
426 impl FromInner<fs_imp::File> for File {
427 fn from_inner(f: fs_imp::File) -> File {
431 impl IntoInner<fs_imp::File> for File {
432 fn into_inner(self) -> fs_imp::File {
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl fmt::Debug for File {
439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 #[stable(feature = "rust1", since = "1.0.0")]
446 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
449 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
450 self.inner.read_to_end(buf)
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl Write for File {
455 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
456 self.inner.write(buf)
458 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
460 #[stable(feature = "rust1", since = "1.0.0")]
462 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl<'a> Read for &'a File {
468 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
471 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
472 self.inner.read_to_end(buf)
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<'a> Write for &'a File {
477 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
478 self.inner.write(buf)
480 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<'a> Seek for &'a File {
484 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
490 /// Creates a blank new set of options ready for configuration.
492 /// All options are initially set to `false`.
497 /// use std::fs::OpenOptions;
499 /// let mut options = OpenOptions::new();
500 /// let file = options.read(true).open("foo.txt");
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn new() -> OpenOptions {
504 OpenOptions(fs_imp::OpenOptions::new())
507 /// Sets the option for read access.
509 /// This option, when true, will indicate that the file should be
510 /// `read`-able if opened.
515 /// use std::fs::OpenOptions;
517 /// let file = OpenOptions::new().read(true).open("foo.txt");
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
521 self.0.read(read); self
524 /// Sets the option for write access.
526 /// This option, when true, will indicate that the file should be
527 /// `write`-able if opened.
529 /// If the file already exists, any write calls on it will overwrite its
530 /// contents, without truncating it.
535 /// use std::fs::OpenOptions;
537 /// let file = OpenOptions::new().write(true).open("foo.txt");
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
541 self.0.write(write); self
544 /// Sets the option for the append mode.
546 /// This option, when true, means that writes will append to a file instead
547 /// of overwriting previous contents.
548 /// Note that setting `.write(true).append(true)` has the same effect as
549 /// setting only `.append(true)`.
551 /// For most filesystems, the operating system guarantees that all writes are
552 /// atomic: no writes get mangled because another process writes at the same
555 /// One maybe obvious note when using append-mode: make sure that all data
556 /// that belongs together is written to the file in one operation. This
557 /// can be done by concatenating strings before passing them to `write()`,
558 /// or using a buffered writer (with a buffer of adequate size),
559 /// and calling `flush()` when the message is complete.
561 /// If a file is opened with both read and append access, beware that after
562 /// opening, and after every write, the position for reading may be set at the
563 /// end of the file. So, before writing, save the current position (using
564 /// `seek(SeekFrom::Current(0))`, and restore it before the next read.
569 /// use std::fs::OpenOptions;
571 /// let file = OpenOptions::new().append(true).open("foo.txt");
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
575 self.0.append(append); self
578 /// Sets the option for truncating a previous file.
580 /// If a file is successfully opened with this option set it will truncate
581 /// the file to 0 length if it already exists.
583 /// The file must be opened with write access for truncate to work.
588 /// use std::fs::OpenOptions;
590 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
594 self.0.truncate(truncate); self
597 /// Sets the option for creating a new file.
599 /// This option indicates whether a new file will be created if the file
600 /// does not yet already exist.
602 /// In order for the file to be created, `write` or `append` access must
608 /// use std::fs::OpenOptions;
610 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
614 self.0.create(create); self
617 /// Sets the option to always create a new file.
619 /// This option indicates whether a new file will be created.
620 /// No file is allowed to exist at the target location, also no (dangling)
623 /// This option is useful because it is atomic. Otherwise between checking
624 /// whether a file exists and creating a new one, the file may have been
625 /// created by another process (a TOCTOU race condition / attack).
627 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are
630 /// The file must be opened with write or append access in order to create
636 /// use std::fs::OpenOptions;
638 /// let file = OpenOptions::new().write(true)
639 /// .create_new(true)
640 /// .open("foo.txt");
642 #[stable(feature = "expand_open_options2", since = "1.9.0")]
643 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
644 self.0.create_new(create_new); self
647 /// Opens a file at `path` with the options specified by `self`.
651 /// This function will return an error under a number of different
652 /// circumstances, to include but not limited to:
654 /// * Opening a file that does not exist without setting `create` or
656 /// * Attempting to open a file with access that the user lacks
658 /// * Filesystem-level errors (full disk, etc)
659 /// * Invalid combinations of open options (truncate without write access,
660 /// no access mode set, etc)
665 /// use std::fs::OpenOptions;
667 /// let file = OpenOptions::new().open("foo.txt");
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
671 self._open(path.as_ref())
674 fn _open(&self, path: &Path) -> io::Result<File> {
675 let inner = fs_imp::File::open(path, &self.0)?;
676 Ok(File { inner: inner })
680 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
681 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
685 /// Returns the file type for this metadata.
690 /// # fn foo() -> std::io::Result<()> {
693 /// let metadata = fs::metadata("foo.txt")?;
695 /// println!("{:?}", metadata.file_type());
699 #[stable(feature = "file_type", since = "1.1.0")]
700 pub fn file_type(&self) -> FileType {
701 FileType(self.0.file_type())
704 /// Returns whether this metadata is for a directory.
709 /// # fn foo() -> std::io::Result<()> {
712 /// let metadata = fs::metadata("foo.txt")?;
714 /// assert!(!metadata.is_dir());
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
721 /// Returns whether this metadata is for a regular file.
726 /// # fn foo() -> std::io::Result<()> {
729 /// let metadata = fs::metadata("foo.txt")?;
731 /// assert!(metadata.is_file());
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn is_file(&self) -> bool { self.file_type().is_file() }
738 /// Returns the size of the file, in bytes, this metadata is for.
743 /// # fn foo() -> std::io::Result<()> {
746 /// let metadata = fs::metadata("foo.txt")?;
748 /// assert_eq!(0, metadata.len());
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn len(&self) -> u64 { self.0.size() }
755 /// Returns the permissions of the file this metadata is for.
760 /// # fn foo() -> std::io::Result<()> {
763 /// let metadata = fs::metadata("foo.txt")?;
765 /// assert!(!metadata.permissions().readonly());
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn permissions(&self) -> Permissions {
771 Permissions(self.0.perm())
774 /// Returns the last modification time listed in this metadata.
776 /// The returned value corresponds to the `mtime` field of `stat` on Unix
777 /// platforms and the `ftLastWriteTime` field on Windows platforms.
781 /// This field may not be available on all platforms, and will return an
782 /// `Err` on platforms where it is not available.
787 /// # fn foo() -> std::io::Result<()> {
790 /// let metadata = fs::metadata("foo.txt")?;
792 /// if let Ok(time) = metadata.modified() {
793 /// println!("{:?}", time);
795 /// println!("Not supported on this platform");
800 #[stable(feature = "fs_time", since = "1.10.0")]
801 pub fn modified(&self) -> io::Result<SystemTime> {
802 self.0.modified().map(FromInner::from_inner)
805 /// Returns the last access time of this metadata.
807 /// The returned value corresponds to the `atime` field of `stat` on Unix
808 /// platforms and the `ftLastAccessTime` field on Windows platforms.
810 /// Note that not all platforms will keep this field update in a file's
811 /// metadata, for example Windows has an option to disable updating this
812 /// time when files are accessed and Linux similarly has `noatime`.
816 /// This field may not be available on all platforms, and will return an
817 /// `Err` on platforms where it is not available.
822 /// # fn foo() -> std::io::Result<()> {
825 /// let metadata = fs::metadata("foo.txt")?;
827 /// if let Ok(time) = metadata.accessed() {
828 /// println!("{:?}", time);
830 /// println!("Not supported on this platform");
835 #[stable(feature = "fs_time", since = "1.10.0")]
836 pub fn accessed(&self) -> io::Result<SystemTime> {
837 self.0.accessed().map(FromInner::from_inner)
840 /// Returns the creation time listed in the this metadata.
842 /// The returned value corresponds to the `birthtime` field of `stat` on
843 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
847 /// This field may not be available on all platforms, and will return an
848 /// `Err` on platforms where it is not available.
853 /// # fn foo() -> std::io::Result<()> {
856 /// let metadata = fs::metadata("foo.txt")?;
858 /// if let Ok(time) = metadata.created() {
859 /// println!("{:?}", time);
861 /// println!("Not supported on this platform");
866 #[stable(feature = "fs_time", since = "1.10.0")]
867 pub fn created(&self) -> io::Result<SystemTime> {
868 self.0.created().map(FromInner::from_inner)
872 #[stable(feature = "std_debug", since = "1.16.0")]
873 impl fmt::Debug for Metadata {
874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 f.debug_struct("Metadata")
876 .field("file_type", &self.file_type())
877 .field("is_dir", &self.is_dir())
878 .field("is_file", &self.is_file())
879 .field("permissions", &self.permissions())
880 .field("modified", &self.modified())
881 .field("accessed", &self.accessed())
882 .field("created", &self.created())
887 impl AsInner<fs_imp::FileAttr> for Metadata {
888 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
892 /// Returns whether these permissions describe a readonly file.
897 /// use std::fs::File;
899 /// # fn foo() -> std::io::Result<()> {
900 /// let mut f = File::create("foo.txt")?;
901 /// let metadata = f.metadata()?;
903 /// assert_eq!(false, metadata.permissions().readonly());
907 #[stable(feature = "rust1", since = "1.0.0")]
908 pub fn readonly(&self) -> bool { self.0.readonly() }
910 /// Modifies the readonly flag for this set of permissions.
912 /// This operation does **not** modify the filesystem. To modify the
913 /// filesystem use the `fs::set_permissions` function.
918 /// use std::fs::File;
920 /// # fn foo() -> std::io::Result<()> {
921 /// let f = File::create("foo.txt")?;
922 /// let metadata = f.metadata()?;
923 /// let mut permissions = metadata.permissions();
925 /// permissions.set_readonly(true);
927 /// // filesystem doesn't change
928 /// assert_eq!(false, metadata.permissions().readonly());
930 /// // just this particular `permissions`.
931 /// assert_eq!(true, permissions.readonly());
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn set_readonly(&mut self, readonly: bool) {
937 self.0.set_readonly(readonly)
942 /// Test whether this file type represents a directory.
947 /// # fn foo() -> std::io::Result<()> {
950 /// let metadata = fs::metadata("foo.txt")?;
951 /// let file_type = metadata.file_type();
953 /// assert_eq!(file_type.is_dir(), false);
957 #[stable(feature = "file_type", since = "1.1.0")]
958 pub fn is_dir(&self) -> bool { self.0.is_dir() }
960 /// Test whether this file type represents a regular file.
965 /// # fn foo() -> std::io::Result<()> {
968 /// let metadata = fs::metadata("foo.txt")?;
969 /// let file_type = metadata.file_type();
971 /// assert_eq!(file_type.is_file(), true);
975 #[stable(feature = "file_type", since = "1.1.0")]
976 pub fn is_file(&self) -> bool { self.0.is_file() }
978 /// Test whether this file type represents a symbolic link.
980 /// The underlying [`Metadata`] struct needs to be retrieved
981 /// with the [`fs::symlink_metadata`] function and not the
982 /// [`fs::metadata`] function. The [`fs::metadata`] function
983 /// follows symbolic links, so [`is_symlink`] would always
984 /// return false for the target file.
986 /// [`Metadata`]: struct.Metadata.html
987 /// [`fs::metadata`]: fn.metadata.html
988 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
989 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
994 /// # fn foo() -> std::io::Result<()> {
997 /// let metadata = fs::symlink_metadata("foo.txt")?;
998 /// let file_type = metadata.file_type();
1000 /// assert_eq!(file_type.is_symlink(), false);
1004 #[stable(feature = "file_type", since = "1.1.0")]
1005 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1008 impl AsInner<fs_imp::FileType> for FileType {
1009 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1012 impl FromInner<fs_imp::FilePermissions> for Permissions {
1013 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1018 impl AsInner<fs_imp::FilePermissions> for Permissions {
1019 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl Iterator for ReadDir {
1024 type Item = io::Result<DirEntry>;
1026 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1027 self.0.next().map(|entry| entry.map(DirEntry))
1032 /// Returns the full path to the file that this entry represents.
1034 /// The full path is created by joining the original path to `read_dir`
1035 /// with the filename of this entry.
1041 /// # fn foo() -> std::io::Result<()> {
1042 /// for entry in fs::read_dir(".")? {
1043 /// let dir = entry?;
1044 /// println!("{:?}", dir.path());
1050 /// This prints output like:
1053 /// "./whatever.txt"
1055 /// "./hello_world.rs"
1058 /// The exact text, of course, depends on what files you have in `.`.
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 pub fn path(&self) -> PathBuf { self.0.path() }
1062 /// Return the metadata for the file that this entry points at.
1064 /// This function will not traverse symlinks if this entry points at a
1067 /// # Platform-specific behavior
1069 /// On Windows this function is cheap to call (no extra system calls
1070 /// needed), but on Unix platforms this function is the equivalent of
1071 /// calling `symlink_metadata` on the path.
1078 /// if let Ok(entries) = fs::read_dir(".") {
1079 /// for entry in entries {
1080 /// if let Ok(entry) = entry {
1081 /// // Here, `entry` is a `DirEntry`.
1082 /// if let Ok(metadata) = entry.metadata() {
1083 /// // Now let's show our entry's permissions!
1084 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1086 /// println!("Couldn't get metadata for {:?}", entry.path());
1092 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1093 pub fn metadata(&self) -> io::Result<Metadata> {
1094 self.0.metadata().map(Metadata)
1097 /// Return the file type for the file that this entry points at.
1099 /// This function will not traverse symlinks if this entry points at a
1102 /// # Platform-specific behavior
1104 /// On Windows and most Unix platforms this function is free (no extra
1105 /// system calls needed), but some Unix platforms may require the equivalent
1106 /// call to `symlink_metadata` to learn about the target file type.
1113 /// if let Ok(entries) = fs::read_dir(".") {
1114 /// for entry in entries {
1115 /// if let Ok(entry) = entry {
1116 /// // Here, `entry` is a `DirEntry`.
1117 /// if let Ok(file_type) = entry.file_type() {
1118 /// // Now let's show our entry's file type!
1119 /// println!("{:?}: {:?}", entry.path(), file_type);
1121 /// println!("Couldn't get file type for {:?}", entry.path());
1127 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1128 pub fn file_type(&self) -> io::Result<FileType> {
1129 self.0.file_type().map(FileType)
1132 /// Returns the bare file name of this directory entry without any other
1133 /// leading path component.
1140 /// if let Ok(entries) = fs::read_dir(".") {
1141 /// for entry in entries {
1142 /// if let Ok(entry) = entry {
1143 /// // Here, `entry` is a `DirEntry`.
1144 /// println!("{:?}", entry.file_name());
1149 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1150 pub fn file_name(&self) -> OsString {
1155 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1156 impl fmt::Debug for DirEntry {
1157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158 f.debug_tuple("DirEntry")
1159 .field(&self.path())
1164 impl AsInner<fs_imp::DirEntry> for DirEntry {
1165 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1168 /// Removes a file from the filesystem.
1170 /// Note that there is no
1171 /// guarantee that the file is immediately deleted (e.g. depending on
1172 /// platform, other open file descriptors may prevent immediate removal).
1174 /// # Platform-specific behavior
1176 /// This function currently corresponds to the `unlink` function on Unix
1177 /// and the `DeleteFile` function on Windows.
1178 /// Note that, this [may change in the future][changes].
1179 /// [changes]: ../io/index.html#platform-specific-behavior
1183 /// This function will return an error in the following situations, but is not
1184 /// limited to just these cases:
1186 /// * `path` points to a directory.
1187 /// * The user lacks permissions to remove the file.
1194 /// # fn foo() -> std::io::Result<()> {
1195 /// fs::remove_file("a.txt")?;
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1201 fs_imp::unlink(path.as_ref())
1204 /// Given a path, query the file system to get information about a file,
1207 /// This function will traverse symbolic links to query information about the
1208 /// destination file.
1210 /// # Platform-specific behavior
1212 /// This function currently corresponds to the `stat` function on Unix
1213 /// and the `GetFileAttributesEx` function on Windows.
1214 /// Note that, this [may change in the future][changes].
1215 /// [changes]: ../io/index.html#platform-specific-behavior
1219 /// This function will return an error in the following situations, but is not
1220 /// limited to just these cases:
1222 /// * The user lacks permissions to perform `metadata` call on `path`.
1223 /// * `path` does not exist.
1228 /// # fn foo() -> std::io::Result<()> {
1231 /// let attr = fs::metadata("/some/file/path.txt")?;
1232 /// // inspect attr ...
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1238 fs_imp::stat(path.as_ref()).map(Metadata)
1241 /// Query the metadata about a file without following symlinks.
1243 /// # Platform-specific behavior
1245 /// This function currently corresponds to the `lstat` function on Unix
1246 /// and the `GetFileAttributesEx` function on Windows.
1247 /// Note that, this [may change in the future][changes].
1248 /// [changes]: ../io/index.html#platform-specific-behavior
1252 /// This function will return an error in the following situations, but is not
1253 /// limited to just these cases:
1255 /// * The user lacks permissions to perform `metadata` call on `path`.
1256 /// * `path` does not exist.
1261 /// # fn foo() -> std::io::Result<()> {
1264 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1265 /// // inspect attr ...
1269 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1270 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1271 fs_imp::lstat(path.as_ref()).map(Metadata)
1274 /// Rename a file or directory to a new name, replacing the original file if
1275 /// `to` already exists.
1277 /// This will not work if the new name is on a different mount point.
1279 /// # Platform-specific behavior
1281 /// This function currently corresponds to the `rename` function on Unix
1282 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1284 /// Because of this, the behavior when both `from` and `to` exist differs. On
1285 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1286 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1287 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1289 /// Note that, this [may change in the future][changes].
1290 /// [changes]: ../io/index.html#platform-specific-behavior
1294 /// This function will return an error in the following situations, but is not
1295 /// limited to just these cases:
1297 /// * `from` does not exist.
1298 /// * The user lacks permissions to view contents.
1299 /// * `from` and `to` are on separate filesystems.
1306 /// # fn foo() -> std::io::Result<()> {
1307 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1313 fs_imp::rename(from.as_ref(), to.as_ref())
1316 /// Copies the contents of one file to another. This function will also
1317 /// copy the permission bits of the original file to the destination file.
1319 /// This function will **overwrite** the contents of `to`.
1321 /// Note that if `from` and `to` both point to the same file, then the file
1322 /// will likely get truncated by this operation.
1324 /// On success, the total number of bytes copied is returned.
1326 /// # Platform-specific behavior
1328 /// This function currently corresponds to the `open` function in Unix
1329 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1330 /// `O_CLOEXEC` is set for returned file descriptors.
1331 /// On Windows, this function currently corresponds to `CopyFileEx`.
1332 /// Note that, this [may change in the future][changes].
1333 /// [changes]: ../io/index.html#platform-specific-behavior
1337 /// This function will return an error in the following situations, but is not
1338 /// limited to just these cases:
1340 /// * The `from` path is not a file.
1341 /// * The `from` file does not exist.
1342 /// * The current process does not have the permission rights to access
1343 /// `from` or write `to`.
1350 /// # fn foo() -> std::io::Result<()> {
1351 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1356 fs_imp::copy(from.as_ref(), to.as_ref())
1359 /// Creates a new hard link on the filesystem.
1361 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1362 /// often require these two paths to both be located on the same filesystem.
1364 /// # Platform-specific behavior
1366 /// This function currently corresponds to the `link` function on Unix
1367 /// and the `CreateHardLink` 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 /// * The `src` path is not a file or doesn't exist.
1383 /// # fn foo() -> std::io::Result<()> {
1384 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1390 fs_imp::link(src.as_ref(), dst.as_ref())
1393 /// Creates a new symbolic link on the filesystem.
1395 /// The `dst` path will be a symbolic link pointing to the `src` path.
1396 /// On Windows, this will be a file symlink, not a directory symlink;
1397 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1398 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1399 /// used instead to make the intent explicit.
1406 /// # fn foo() -> std::io::Result<()> {
1407 /// fs::soft_link("a.txt", "b.txt")?;
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 #[rustc_deprecated(since = "1.1.0",
1413 reason = "replaced with std::os::unix::fs::symlink and \
1414 std::os::windows::fs::{symlink_file, symlink_dir}")]
1415 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1416 fs_imp::symlink(src.as_ref(), dst.as_ref())
1419 /// Reads a symbolic link, returning the file that the link points to.
1421 /// # Platform-specific behavior
1423 /// This function currently corresponds to the `readlink` function on Unix
1424 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1425 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1426 /// Note that, this [may change in the future][changes].
1427 /// [changes]: ../io/index.html#platform-specific-behavior
1431 /// This function will return an error in the following situations, but is not
1432 /// limited to just these cases:
1434 /// * `path` is not a symbolic link.
1435 /// * `path` does not exist.
1442 /// # fn foo() -> std::io::Result<()> {
1443 /// let path = fs::read_link("a.txt")?;
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1449 fs_imp::readlink(path.as_ref())
1452 /// Returns the canonical form of a path with all intermediate components
1453 /// normalized and symbolic links resolved.
1455 /// # Platform-specific behavior
1457 /// This function currently corresponds to the `realpath` function on Unix
1458 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1459 /// Note that, this [may change in the future][changes].
1460 /// [changes]: ../io/index.html#platform-specific-behavior
1464 /// This function will return an error in the following situations, but is not
1465 /// limited to just these cases:
1467 /// * `path` does not exist.
1468 /// * A component in path is not a directory.
1475 /// # fn foo() -> std::io::Result<()> {
1476 /// let path = fs::canonicalize("../a/../foo.txt")?;
1480 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1481 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1482 fs_imp::canonicalize(path.as_ref())
1485 /// Creates a new, empty directory at the provided path
1487 /// # Platform-specific behavior
1489 /// This function currently corresponds to the `mkdir` function on Unix
1490 /// and the `CreateDirectory` function on Windows.
1491 /// Note that, this [may change in the future][changes].
1492 /// [changes]: ../io/index.html#platform-specific-behavior
1496 /// This function will return an error in the following situations, but is not
1497 /// limited to just these cases:
1499 /// * User lacks permissions to create directory at `path`.
1500 /// * `path` already exists.
1507 /// # fn foo() -> std::io::Result<()> {
1508 /// fs::create_dir("/some/dir")?;
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1514 DirBuilder::new().create(path.as_ref())
1517 /// Recursively create a directory and all of its parent components if they
1520 /// # Platform-specific behavior
1522 /// This function currently corresponds to the `mkdir` function on Unix
1523 /// and the `CreateDirectory` function on Windows.
1524 /// Note that, this [may change in the future][changes].
1525 /// [changes]: ../io/index.html#platform-specific-behavior
1529 /// This function will return an error in the following situations, but is not
1530 /// limited to just these cases:
1532 /// * If any directory in the path specified by `path`
1533 /// does not already exist and it could not be created otherwise. The specific
1534 /// error conditions for when a directory is being created (after it is
1535 /// determined to not exist) are outlined by `fs::create_dir`.
1537 /// Notable exception is made for situations where any of the directories
1538 /// specified in the `path` could not be created as it was created concurrently.
1539 /// Such cases are considered success. In other words: calling `create_dir_all`
1540 /// concurrently from multiple threads or processes is guaranteed to not fail
1541 /// due to race itself.
1548 /// # fn foo() -> std::io::Result<()> {
1549 /// fs::create_dir_all("/some/dir")?;
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1555 DirBuilder::new().recursive(true).create(path.as_ref())
1558 /// Removes an existing, empty directory.
1560 /// # Platform-specific behavior
1562 /// This function currently corresponds to the `rmdir` function on Unix
1563 /// and the `RemoveDirectory` function on Windows.
1564 /// Note that, this [may change in the future][changes].
1565 /// [changes]: ../io/index.html#platform-specific-behavior
1569 /// This function will return an error in the following situations, but is not
1570 /// limited to just these cases:
1572 /// * The user lacks permissions to remove the directory at the provided `path`.
1573 /// * The directory isn't empty.
1580 /// # fn foo() -> std::io::Result<()> {
1581 /// fs::remove_dir("/some/dir")?;
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1587 fs_imp::rmdir(path.as_ref())
1590 /// Removes a directory at this path, after removing all its contents. Use
1593 /// This function does **not** follow symbolic links and it will simply remove the
1594 /// symbolic link itself.
1596 /// # Platform-specific behavior
1598 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1599 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1601 /// Note that, this [may change in the future][changes].
1602 /// [changes]: ../io/index.html#platform-specific-behavior
1606 /// See `file::remove_file` and `fs::remove_dir`.
1613 /// # fn foo() -> std::io::Result<()> {
1614 /// fs::remove_dir_all("/some/dir")?;
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1620 fs_imp::remove_dir_all(path.as_ref())
1623 /// Returns an iterator over the entries within a directory.
1625 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1626 /// New errors may be encountered after an iterator is initially constructed.
1628 /// [`io::Result`]: ../io/type.Result.html
1629 /// [`DirEntry`]: struct.DirEntry.html
1631 /// # Platform-specific behavior
1633 /// This function currently corresponds to the `opendir` function on Unix
1634 /// and the `FindFirstFile` function on Windows.
1635 /// Note that, this [may change in the future][changes].
1636 /// [changes]: ../io/index.html#platform-specific-behavior
1640 /// This function will return an error in the following situations, but is not
1641 /// limited to just these cases:
1643 /// * The provided `path` doesn't exist.
1644 /// * The process lacks permissions to view the contents.
1645 /// * The `path` points at a non-directory file.
1651 /// use std::fs::{self, DirEntry};
1652 /// use std::path::Path;
1654 /// // one possible implementation of walking a directory only visiting files
1655 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1656 /// if dir.is_dir() {
1657 /// for entry in fs::read_dir(dir)? {
1658 /// let entry = entry?;
1659 /// let path = entry.path();
1660 /// if path.is_dir() {
1661 /// visit_dirs(&path, cb)?;
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1672 fs_imp::readdir(path.as_ref()).map(ReadDir)
1675 /// Changes the permissions found on a file or a directory.
1677 /// # Platform-specific behavior
1679 /// This function currently corresponds to the `chmod` function on Unix
1680 /// and the `SetFileAttributes` function on Windows.
1681 /// Note that, this [may change in the future][changes].
1682 /// [changes]: ../io/index.html#platform-specific-behavior
1686 /// This function will return an error in the following situations, but is not
1687 /// limited to just these cases:
1689 /// * `path` does not exist.
1690 /// * The user lacks the permission to change attributes of the file.
1695 /// # fn foo() -> std::io::Result<()> {
1698 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1699 /// perms.set_readonly(true);
1700 /// fs::set_permissions("foo.txt", perms)?;
1704 #[stable(feature = "set_permissions", since = "1.1.0")]
1705 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1707 fs_imp::set_perm(path.as_ref(), perm.0)
1711 /// Creates a new set of options with default mode/security settings for all
1712 /// platforms and also non-recursive.
1717 /// use std::fs::DirBuilder;
1719 /// let builder = DirBuilder::new();
1721 #[stable(feature = "dir_builder", since = "1.6.0")]
1722 pub fn new() -> DirBuilder {
1724 inner: fs_imp::DirBuilder::new(),
1729 /// Indicate that directories create should be created recursively, creating
1730 /// all parent directories if they do not exist with the same security and
1731 /// permissions settings.
1733 /// This option defaults to `false`.
1738 /// use std::fs::DirBuilder;
1740 /// let mut builder = DirBuilder::new();
1741 /// builder.recursive(true);
1743 #[stable(feature = "dir_builder", since = "1.6.0")]
1744 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1745 self.recursive = recursive;
1749 /// Create the specified directory with the options configured in this
1755 /// use std::fs::{self, DirBuilder};
1757 /// let path = "/tmp/foo/bar/baz";
1758 /// DirBuilder::new()
1759 /// .recursive(true)
1760 /// .create(path).unwrap();
1762 /// assert!(fs::metadata(path).unwrap().is_dir());
1764 #[stable(feature = "dir_builder", since = "1.6.0")]
1765 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1766 self._create(path.as_ref())
1769 fn _create(&self, path: &Path) -> io::Result<()> {
1771 self.create_dir_all(path)
1773 self.inner.mkdir(path)
1777 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1778 if path == Path::new("") {
1782 match self.inner.mkdir(path) {
1783 Ok(()) => return Ok(()),
1784 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
1785 Err(_) if path.is_dir() => return Ok(()),
1786 Err(e) => return Err(e),
1788 match path.parent() {
1789 Some(p) => try!(self.create_dir_all(p)),
1790 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
1792 match self.inner.mkdir(path) {
1794 Err(_) if path.is_dir() => Ok(()),
1800 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1801 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1806 #[cfg(all(test, not(target_os = "emscripten")))]
1810 use fs::{self, File, OpenOptions};
1811 use io::{ErrorKind, SeekFrom};
1813 use rand::{StdRng, Rng};
1815 use sys_common::io::test::{TempDir, tmpdir};
1819 use os::windows::fs::{symlink_dir, symlink_file};
1821 use sys::fs::symlink_junction;
1823 use os::unix::fs::symlink as symlink_dir;
1825 use os::unix::fs::symlink as symlink_file;
1827 use os::unix::fs::symlink as symlink_junction;
1829 macro_rules! check { ($e:expr) => (
1832 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1837 macro_rules! error { ($e:expr, $s:expr) => (
1839 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1840 Err(ref err) => assert!(err.raw_os_error() == Some($s),
1841 format!("`{}` did not have a code of `{}`", err, $s))
1846 macro_rules! error { ($e:expr, $s:expr) => (
1848 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1849 Err(ref err) => assert!(err.to_string().contains($s),
1850 format!("`{}` did not contain `{}`", err, $s))
1854 // Several test fail on windows if the user does not have permission to
1855 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
1856 // disabling these test on Windows, use this function to test whether we
1857 // have permission, and return otherwise. This way, we still don't run these
1858 // tests most of the time, but at least we do if the user has the right
1860 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
1861 if cfg!(unix) { return true }
1862 let link = tmpdir.join("some_hopefully_unique_link_name");
1864 match symlink_file(r"nonexisting_target", link) {
1866 // ERROR_PRIVILEGE_NOT_HELD = 1314
1867 Err(ref err) if err.raw_os_error() == Some(1314) => false,
1873 fn file_test_io_smoke_test() {
1874 let message = "it's alright. have a good time";
1875 let tmpdir = tmpdir();
1876 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1878 let mut write_stream = check!(File::create(filename));
1879 check!(write_stream.write(message.as_bytes()));
1882 let mut read_stream = check!(File::open(filename));
1883 let mut read_buf = [0; 1028];
1884 let read_str = match check!(read_stream.read(&mut read_buf)) {
1885 0 => panic!("shouldn't happen"),
1886 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1888 assert_eq!(read_str, message);
1890 check!(fs::remove_file(filename));
1894 fn invalid_path_raises() {
1895 let tmpdir = tmpdir();
1896 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1897 let result = File::open(filename);
1900 error!(result, "No such file or directory");
1902 error!(result, 2); // ERROR_FILE_NOT_FOUND
1906 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1907 let tmpdir = tmpdir();
1908 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1910 let result = fs::remove_file(filename);
1913 error!(result, "No such file or directory");
1915 error!(result, 2); // ERROR_FILE_NOT_FOUND
1919 fn file_test_io_non_positional_read() {
1920 let message: &str = "ten-four";
1921 let mut read_mem = [0; 8];
1922 let tmpdir = tmpdir();
1923 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1925 let mut rw_stream = check!(File::create(filename));
1926 check!(rw_stream.write(message.as_bytes()));
1929 let mut read_stream = check!(File::open(filename));
1931 let read_buf = &mut read_mem[0..4];
1932 check!(read_stream.read(read_buf));
1935 let read_buf = &mut read_mem[4..8];
1936 check!(read_stream.read(read_buf));
1939 check!(fs::remove_file(filename));
1940 let read_str = str::from_utf8(&read_mem).unwrap();
1941 assert_eq!(read_str, message);
1945 fn file_test_io_seek_and_tell_smoke_test() {
1946 let message = "ten-four";
1947 let mut read_mem = [0; 4];
1948 let set_cursor = 4 as u64;
1949 let tell_pos_pre_read;
1950 let tell_pos_post_read;
1951 let tmpdir = tmpdir();
1952 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1954 let mut rw_stream = check!(File::create(filename));
1955 check!(rw_stream.write(message.as_bytes()));
1958 let mut read_stream = check!(File::open(filename));
1959 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1960 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1961 check!(read_stream.read(&mut read_mem));
1962 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1964 check!(fs::remove_file(filename));
1965 let read_str = str::from_utf8(&read_mem).unwrap();
1966 assert_eq!(read_str, &message[4..8]);
1967 assert_eq!(tell_pos_pre_read, set_cursor);
1968 assert_eq!(tell_pos_post_read, message.len() as u64);
1972 fn file_test_io_seek_and_write() {
1973 let initial_msg = "food-is-yummy";
1974 let overwrite_msg = "-the-bar!!";
1975 let final_msg = "foo-the-bar!!";
1977 let mut read_mem = [0; 13];
1978 let tmpdir = tmpdir();
1979 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1981 let mut rw_stream = check!(File::create(filename));
1982 check!(rw_stream.write(initial_msg.as_bytes()));
1983 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1984 check!(rw_stream.write(overwrite_msg.as_bytes()));
1987 let mut read_stream = check!(File::open(filename));
1988 check!(read_stream.read(&mut read_mem));
1990 check!(fs::remove_file(filename));
1991 let read_str = str::from_utf8(&read_mem).unwrap();
1992 assert!(read_str == final_msg);
1996 fn file_test_io_seek_shakedown() {
1998 let initial_msg = "qwer-asdf-zxcv";
1999 let chunk_one: &str = "qwer";
2000 let chunk_two: &str = "asdf";
2001 let chunk_three: &str = "zxcv";
2002 let mut read_mem = [0; 4];
2003 let tmpdir = tmpdir();
2004 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2006 let mut rw_stream = check!(File::create(filename));
2007 check!(rw_stream.write(initial_msg.as_bytes()));
2010 let mut read_stream = check!(File::open(filename));
2012 check!(read_stream.seek(SeekFrom::End(-4)));
2013 check!(read_stream.read(&mut read_mem));
2014 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2016 check!(read_stream.seek(SeekFrom::Current(-9)));
2017 check!(read_stream.read(&mut read_mem));
2018 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2020 check!(read_stream.seek(SeekFrom::Start(0)));
2021 check!(read_stream.read(&mut read_mem));
2022 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2024 check!(fs::remove_file(filename));
2028 fn file_test_io_eof() {
2029 let tmpdir = tmpdir();
2030 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2031 let mut buf = [0; 256];
2033 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2034 let mut rw = check!(oo.open(&filename));
2035 assert_eq!(check!(rw.read(&mut buf)), 0);
2036 assert_eq!(check!(rw.read(&mut buf)), 0);
2038 check!(fs::remove_file(&filename));
2043 fn file_test_io_read_write_at() {
2044 use os::unix::fs::FileExt;
2046 let tmpdir = tmpdir();
2047 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2048 let mut buf = [0; 256];
2049 let write1 = "asdf";
2050 let write2 = "qwer-";
2051 let write3 = "-zxcv";
2052 let content = "qwer-asdf-zxcv";
2054 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2055 let mut rw = check!(oo.open(&filename));
2056 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2057 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2058 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2059 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2060 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2061 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2062 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2063 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2064 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2065 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2066 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2067 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2068 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2069 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2070 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2071 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2072 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2073 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2076 let mut read = check!(File::open(&filename));
2077 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2078 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2079 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2080 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2081 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2082 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2083 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2084 assert_eq!(check!(read.read(&mut buf)), write3.len());
2085 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2086 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2087 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2088 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2089 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2090 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2091 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2092 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2094 check!(fs::remove_file(&filename));
2099 fn file_test_io_seek_read_write() {
2100 use os::windows::fs::FileExt;
2102 let tmpdir = tmpdir();
2103 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2104 let mut buf = [0; 256];
2105 let write1 = "asdf";
2106 let write2 = "qwer-";
2107 let write3 = "-zxcv";
2108 let content = "qwer-asdf-zxcv";
2110 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2111 let mut rw = check!(oo.open(&filename));
2112 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2113 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2114 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2115 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2116 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2117 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2118 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2119 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2120 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2121 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2122 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2123 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2124 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2125 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2126 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2127 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2130 let mut read = check!(File::open(&filename));
2131 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2132 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2133 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2134 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2135 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2136 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2137 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2138 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2139 assert_eq!(check!(read.read(&mut buf)), write3.len());
2140 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2141 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2142 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2143 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2144 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2145 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2146 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2148 check!(fs::remove_file(&filename));
2152 fn file_test_stat_is_correct_on_is_file() {
2153 let tmpdir = tmpdir();
2154 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2156 let mut opts = OpenOptions::new();
2157 let mut fs = check!(opts.read(true).write(true)
2158 .create(true).open(filename));
2160 fs.write(msg.as_bytes()).unwrap();
2162 let fstat_res = check!(fs.metadata());
2163 assert!(fstat_res.is_file());
2165 let stat_res_fn = check!(fs::metadata(filename));
2166 assert!(stat_res_fn.is_file());
2167 let stat_res_meth = check!(filename.metadata());
2168 assert!(stat_res_meth.is_file());
2169 check!(fs::remove_file(filename));
2173 fn file_test_stat_is_correct_on_is_dir() {
2174 let tmpdir = tmpdir();
2175 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2176 check!(fs::create_dir(filename));
2177 let stat_res_fn = check!(fs::metadata(filename));
2178 assert!(stat_res_fn.is_dir());
2179 let stat_res_meth = check!(filename.metadata());
2180 assert!(stat_res_meth.is_dir());
2181 check!(fs::remove_dir(filename));
2185 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2186 let tmpdir = tmpdir();
2187 let dir = &tmpdir.join("fileinfo_false_on_dir");
2188 check!(fs::create_dir(dir));
2189 assert!(!dir.is_file());
2190 check!(fs::remove_dir(dir));
2194 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2195 let tmpdir = tmpdir();
2196 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2197 check!(check!(File::create(file)).write(b"foo"));
2198 assert!(file.exists());
2199 check!(fs::remove_file(file));
2200 assert!(!file.exists());
2204 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2205 let tmpdir = tmpdir();
2206 let dir = &tmpdir.join("before_and_after_dir");
2207 assert!(!dir.exists());
2208 check!(fs::create_dir(dir));
2209 assert!(dir.exists());
2210 assert!(dir.is_dir());
2211 check!(fs::remove_dir(dir));
2212 assert!(!dir.exists());
2216 fn file_test_directoryinfo_readdir() {
2217 let tmpdir = tmpdir();
2218 let dir = &tmpdir.join("di_readdir");
2219 check!(fs::create_dir(dir));
2222 let f = dir.join(&format!("{}.txt", n));
2223 let mut w = check!(File::create(&f));
2224 let msg_str = format!("{}{}", prefix, n.to_string());
2225 let msg = msg_str.as_bytes();
2226 check!(w.write(msg));
2228 let files = check!(fs::read_dir(dir));
2229 let mut mem = [0; 4];
2231 let f = f.unwrap().path();
2233 let n = f.file_stem().unwrap();
2234 check!(check!(File::open(&f)).read(&mut mem));
2235 let read_str = str::from_utf8(&mem).unwrap();
2236 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2237 assert_eq!(expected, read_str);
2239 check!(fs::remove_file(&f));
2241 check!(fs::remove_dir(dir));
2245 fn file_create_new_already_exists_error() {
2246 let tmpdir = tmpdir();
2247 let file = &tmpdir.join("file_create_new_error_exists");
2248 check!(fs::File::create(file));
2249 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2250 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2254 fn mkdir_path_already_exists_error() {
2255 let tmpdir = tmpdir();
2256 let dir = &tmpdir.join("mkdir_error_twice");
2257 check!(fs::create_dir(dir));
2258 let e = fs::create_dir(dir).unwrap_err();
2259 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2263 fn recursive_mkdir() {
2264 let tmpdir = tmpdir();
2265 let dir = tmpdir.join("d1/d2");
2266 check!(fs::create_dir_all(&dir));
2267 assert!(dir.is_dir())
2271 fn recursive_mkdir_failure() {
2272 let tmpdir = tmpdir();
2273 let dir = tmpdir.join("d1");
2274 let file = dir.join("f1");
2276 check!(fs::create_dir_all(&dir));
2277 check!(File::create(&file));
2279 let result = fs::create_dir_all(&file);
2281 assert!(result.is_err());
2285 fn concurrent_recursive_mkdir() {
2288 let mut dir = dir.join("a");
2290 dir = dir.join("a");
2292 let mut join = vec!();
2294 let dir = dir.clone();
2295 join.push(thread::spawn(move || {
2296 check!(fs::create_dir_all(&dir));
2300 // No `Display` on result of `join()`
2301 join.drain(..).map(|join| join.join().unwrap()).count();
2306 fn recursive_mkdir_slash() {
2307 check!(fs::create_dir_all(&Path::new("/")));
2311 fn recursive_mkdir_dot() {
2312 check!(fs::create_dir_all(&Path::new(".")));
2316 fn recursive_mkdir_empty() {
2317 check!(fs::create_dir_all(&Path::new("")));
2321 fn recursive_rmdir() {
2322 let tmpdir = tmpdir();
2323 let d1 = tmpdir.join("d1");
2324 let dt = d1.join("t");
2325 let dtt = dt.join("t");
2326 let d2 = tmpdir.join("d2");
2327 let canary = d2.join("do_not_delete");
2328 check!(fs::create_dir_all(&dtt));
2329 check!(fs::create_dir_all(&d2));
2330 check!(check!(File::create(&canary)).write(b"foo"));
2331 check!(symlink_junction(&d2, &dt.join("d2")));
2332 let _ = symlink_file(&canary, &d1.join("canary"));
2333 check!(fs::remove_dir_all(&d1));
2335 assert!(!d1.is_dir());
2336 assert!(canary.exists());
2340 fn recursive_rmdir_of_symlink() {
2341 // test we do not recursively delete a symlink but only dirs.
2342 let tmpdir = tmpdir();
2343 let link = tmpdir.join("d1");
2344 let dir = tmpdir.join("d2");
2345 let canary = dir.join("do_not_delete");
2346 check!(fs::create_dir_all(&dir));
2347 check!(check!(File::create(&canary)).write(b"foo"));
2348 check!(symlink_junction(&dir, &link));
2349 check!(fs::remove_dir_all(&link));
2351 assert!(!link.is_dir());
2352 assert!(canary.exists());
2356 // only Windows makes a distinction between file and directory symlinks.
2358 fn recursive_rmdir_of_file_symlink() {
2359 let tmpdir = tmpdir();
2360 if !got_symlink_permission(&tmpdir) { return };
2362 let f1 = tmpdir.join("f1");
2363 let f2 = tmpdir.join("f2");
2364 check!(check!(File::create(&f1)).write(b"foo"));
2365 check!(symlink_file(&f1, &f2));
2366 match fs::remove_dir_all(&f2) {
2367 Ok(..) => panic!("wanted a failure"),
2373 fn unicode_path_is_dir() {
2374 assert!(Path::new(".").is_dir());
2375 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2377 let tmpdir = tmpdir();
2379 let mut dirpath = tmpdir.path().to_path_buf();
2380 dirpath.push("test-가一ー你好");
2381 check!(fs::create_dir(&dirpath));
2382 assert!(dirpath.is_dir());
2384 let mut filepath = dirpath;
2385 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2386 check!(File::create(&filepath)); // ignore return; touch only
2387 assert!(!filepath.is_dir());
2388 assert!(filepath.exists());
2392 fn unicode_path_exists() {
2393 assert!(Path::new(".").exists());
2394 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2396 let tmpdir = tmpdir();
2397 let unicode = tmpdir.path();
2398 let unicode = unicode.join(&format!("test-각丁ー再见"));
2399 check!(fs::create_dir(&unicode));
2400 assert!(unicode.exists());
2401 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2405 fn copy_file_does_not_exist() {
2406 let from = Path::new("test/nonexistent-bogus-path");
2407 let to = Path::new("test/other-bogus-path");
2409 match fs::copy(&from, &to) {
2412 assert!(!from.exists());
2413 assert!(!to.exists());
2419 fn copy_src_does_not_exist() {
2420 let tmpdir = tmpdir();
2421 let from = Path::new("test/nonexistent-bogus-path");
2422 let to = tmpdir.join("out.txt");
2423 check!(check!(File::create(&to)).write(b"hello"));
2424 assert!(fs::copy(&from, &to).is_err());
2425 assert!(!from.exists());
2426 let mut v = Vec::new();
2427 check!(check!(File::open(&to)).read_to_end(&mut v));
2428 assert_eq!(v, b"hello");
2433 let tmpdir = tmpdir();
2434 let input = tmpdir.join("in.txt");
2435 let out = tmpdir.join("out.txt");
2437 check!(check!(File::create(&input)).write(b"hello"));
2438 check!(fs::copy(&input, &out));
2439 let mut v = Vec::new();
2440 check!(check!(File::open(&out)).read_to_end(&mut v));
2441 assert_eq!(v, b"hello");
2443 assert_eq!(check!(input.metadata()).permissions(),
2444 check!(out.metadata()).permissions());
2448 fn copy_file_dst_dir() {
2449 let tmpdir = tmpdir();
2450 let out = tmpdir.join("out");
2452 check!(File::create(&out));
2453 match fs::copy(&*out, tmpdir.path()) {
2454 Ok(..) => panic!(), Err(..) => {}
2459 fn copy_file_dst_exists() {
2460 let tmpdir = tmpdir();
2461 let input = tmpdir.join("in");
2462 let output = tmpdir.join("out");
2464 check!(check!(File::create(&input)).write("foo".as_bytes()));
2465 check!(check!(File::create(&output)).write("bar".as_bytes()));
2466 check!(fs::copy(&input, &output));
2468 let mut v = Vec::new();
2469 check!(check!(File::open(&output)).read_to_end(&mut v));
2470 assert_eq!(v, b"foo".to_vec());
2474 fn copy_file_src_dir() {
2475 let tmpdir = tmpdir();
2476 let out = tmpdir.join("out");
2478 match fs::copy(tmpdir.path(), &out) {
2479 Ok(..) => panic!(), Err(..) => {}
2481 assert!(!out.exists());
2485 fn copy_file_preserves_perm_bits() {
2486 let tmpdir = tmpdir();
2487 let input = tmpdir.join("in.txt");
2488 let out = tmpdir.join("out.txt");
2490 let attr = check!(check!(File::create(&input)).metadata());
2491 let mut p = attr.permissions();
2492 p.set_readonly(true);
2493 check!(fs::set_permissions(&input, p));
2494 check!(fs::copy(&input, &out));
2495 assert!(check!(out.metadata()).permissions().readonly());
2496 check!(fs::set_permissions(&input, attr.permissions()));
2497 check!(fs::set_permissions(&out, attr.permissions()));
2502 fn copy_file_preserves_streams() {
2504 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2505 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2506 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2507 let mut v = Vec::new();
2508 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2509 assert_eq!(v, b"carrot".to_vec());
2513 fn symlinks_work() {
2514 let tmpdir = tmpdir();
2515 if !got_symlink_permission(&tmpdir) { return };
2517 let input = tmpdir.join("in.txt");
2518 let out = tmpdir.join("out.txt");
2520 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2521 check!(symlink_file(&input, &out));
2522 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2523 assert_eq!(check!(fs::metadata(&out)).len(),
2524 check!(fs::metadata(&input)).len());
2525 let mut v = Vec::new();
2526 check!(check!(File::open(&out)).read_to_end(&mut v));
2527 assert_eq!(v, b"foobar".to_vec());
2531 fn symlink_noexist() {
2532 // Symlinks can point to things that don't exist
2533 let tmpdir = tmpdir();
2534 if !got_symlink_permission(&tmpdir) { return };
2536 // Use a relative path for testing. Symlinks get normalized by Windows,
2537 // so we may not get the same path back for absolute paths
2538 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2539 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2546 // directory symlink
2547 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2550 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2551 r"C:\Users\Default");
2552 // junction with special permissions
2553 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2556 let tmpdir = tmpdir();
2557 let link = tmpdir.join("link");
2558 if !got_symlink_permission(&tmpdir) { return };
2559 check!(symlink_file(&"foo", &link));
2560 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2564 fn readlink_not_symlink() {
2565 let tmpdir = tmpdir();
2566 match fs::read_link(tmpdir.path()) {
2567 Ok(..) => panic!("wanted a failure"),
2574 let tmpdir = tmpdir();
2575 let input = tmpdir.join("in.txt");
2576 let out = tmpdir.join("out.txt");
2578 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2579 check!(fs::hard_link(&input, &out));
2580 assert_eq!(check!(fs::metadata(&out)).len(),
2581 check!(fs::metadata(&input)).len());
2582 assert_eq!(check!(fs::metadata(&out)).len(),
2583 check!(input.metadata()).len());
2584 let mut v = Vec::new();
2585 check!(check!(File::open(&out)).read_to_end(&mut v));
2586 assert_eq!(v, b"foobar".to_vec());
2588 // can't link to yourself
2589 match fs::hard_link(&input, &input) {
2590 Ok(..) => panic!("wanted a failure"),
2593 // can't link to something that doesn't exist
2594 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2595 Ok(..) => panic!("wanted a failure"),
2602 let tmpdir = tmpdir();
2603 let file = tmpdir.join("in.txt");
2605 check!(File::create(&file));
2606 let attr = check!(fs::metadata(&file));
2607 assert!(!attr.permissions().readonly());
2608 let mut p = attr.permissions();
2609 p.set_readonly(true);
2610 check!(fs::set_permissions(&file, p.clone()));
2611 let attr = check!(fs::metadata(&file));
2612 assert!(attr.permissions().readonly());
2614 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2615 Ok(..) => panic!("wanted an error"),
2619 p.set_readonly(false);
2620 check!(fs::set_permissions(&file, p));
2625 let tmpdir = tmpdir();
2626 let path = tmpdir.join("in.txt");
2628 let file = check!(File::create(&path));
2629 let attr = check!(fs::metadata(&path));
2630 assert!(!attr.permissions().readonly());
2631 let mut p = attr.permissions();
2632 p.set_readonly(true);
2633 check!(file.set_permissions(p.clone()));
2634 let attr = check!(fs::metadata(&path));
2635 assert!(attr.permissions().readonly());
2637 p.set_readonly(false);
2638 check!(file.set_permissions(p));
2642 fn sync_doesnt_kill_anything() {
2643 let tmpdir = tmpdir();
2644 let path = tmpdir.join("in.txt");
2646 let mut file = check!(File::create(&path));
2647 check!(file.sync_all());
2648 check!(file.sync_data());
2649 check!(file.write(b"foo"));
2650 check!(file.sync_all());
2651 check!(file.sync_data());
2655 fn truncate_works() {
2656 let tmpdir = tmpdir();
2657 let path = tmpdir.join("in.txt");
2659 let mut file = check!(File::create(&path));
2660 check!(file.write(b"foo"));
2661 check!(file.sync_all());
2663 // Do some simple things with truncation
2664 assert_eq!(check!(file.metadata()).len(), 3);
2665 check!(file.set_len(10));
2666 assert_eq!(check!(file.metadata()).len(), 10);
2667 check!(file.write(b"bar"));
2668 check!(file.sync_all());
2669 assert_eq!(check!(file.metadata()).len(), 10);
2671 let mut v = Vec::new();
2672 check!(check!(File::open(&path)).read_to_end(&mut v));
2673 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2675 // Truncate to a smaller length, don't seek, and then write something.
2676 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2677 // past the end of the file).
2678 check!(file.set_len(2));
2679 assert_eq!(check!(file.metadata()).len(), 2);
2680 check!(file.write(b"wut"));
2681 check!(file.sync_all());
2682 assert_eq!(check!(file.metadata()).len(), 9);
2683 let mut v = Vec::new();
2684 check!(check!(File::open(&path)).read_to_end(&mut v));
2685 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2690 use fs::OpenOptions as OO;
2691 fn c<T: Clone>(t: &T) -> T { t.clone() }
2693 let tmpdir = tmpdir();
2695 let mut r = OO::new(); r.read(true);
2696 let mut w = OO::new(); w.write(true);
2697 let mut rw = OO::new(); rw.read(true).write(true);
2698 let mut a = OO::new(); a.append(true);
2699 let mut ra = OO::new(); ra.read(true).append(true);
2702 let invalid_options = 87; // ERROR_INVALID_PARAMETER
2704 let invalid_options = "Invalid argument";
2706 // Test various combinations of creation modes and access modes.
2709 // creation mode | read | write | read-write | append | read-append |
2710 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2711 // not set (open existing) | X | X | X | X | X |
2712 // create | | X | X | X | X |
2713 // truncate | | X | X | | |
2714 // create and truncate | | X | X | | |
2715 // create_new | | X | X | X | X |
2717 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2720 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2721 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2722 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2723 check!(c(&w).create(true).open(&tmpdir.join("a")));
2724 check!(c(&w).open(&tmpdir.join("a")));
2727 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2728 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2729 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2730 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2731 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2734 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2735 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2736 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2737 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2738 check!(c(&rw).open(&tmpdir.join("c")));
2741 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2742 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2743 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2744 check!(c(&a).create(true).open(&tmpdir.join("d")));
2745 check!(c(&a).open(&tmpdir.join("d")));
2748 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2749 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2750 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2751 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2752 check!(c(&ra).open(&tmpdir.join("e")));
2754 // Test opening a file without setting an access mode
2755 let mut blank = OO::new();
2756 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2759 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2761 // Test write fails for read-only
2762 check!(r.open(&tmpdir.join("h")));
2764 let mut f = check!(r.open(&tmpdir.join("h")));
2765 assert!(f.write("wut".as_bytes()).is_err());
2768 // Test write overwrites
2770 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2771 check!(f.write("baz".as_bytes()));
2774 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2775 let mut b = vec![0; 6];
2776 check!(f.read(&mut b));
2777 assert_eq!(b, "bazbar".as_bytes());
2780 // Test truncate works
2782 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2783 check!(f.write("foo".as_bytes()));
2785 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2787 // Test append works
2788 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2790 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2791 check!(f.write("bar".as_bytes()));
2793 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2795 // Test .append(true) equals .write(true).append(true)
2797 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2798 check!(f.write("baz".as_bytes()));
2800 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2804 fn _assert_send_sync() {
2805 fn _assert_send_sync<T: Send + Sync>() {}
2806 _assert_send_sync::<OpenOptions>();
2811 let mut bytes = [0; 1024];
2812 StdRng::new().unwrap().fill_bytes(&mut bytes);
2814 let tmpdir = tmpdir();
2816 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2817 let mut v = Vec::new();
2818 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2819 assert!(v == &bytes[..]);
2823 fn file_try_clone() {
2824 let tmpdir = tmpdir();
2826 let mut f1 = check!(OpenOptions::new()
2830 .open(&tmpdir.join("test")));
2831 let mut f2 = check!(f1.try_clone());
2833 check!(f1.write_all(b"hello world"));
2834 check!(f1.seek(SeekFrom::Start(2)));
2836 let mut buf = vec![];
2837 check!(f2.read_to_end(&mut buf));
2838 assert_eq!(buf, b"llo world");
2841 check!(f1.write_all(b"!"));
2845 #[cfg(not(windows))]
2846 fn unlink_readonly() {
2847 let tmpdir = tmpdir();
2848 let path = tmpdir.join("file");
2849 check!(File::create(&path));
2850 let mut perm = check!(fs::metadata(&path)).permissions();
2851 perm.set_readonly(true);
2852 check!(fs::set_permissions(&path, perm));
2853 check!(fs::remove_file(&path));
2857 fn mkdir_trailing_slash() {
2858 let tmpdir = tmpdir();
2859 let path = tmpdir.join("file");
2860 check!(fs::create_dir_all(&path.join("a/")));
2864 fn canonicalize_works_simple() {
2865 let tmpdir = tmpdir();
2866 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2867 let file = tmpdir.join("test");
2868 File::create(&file).unwrap();
2869 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2873 fn realpath_works() {
2874 let tmpdir = tmpdir();
2875 if !got_symlink_permission(&tmpdir) { return };
2877 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2878 let file = tmpdir.join("test");
2879 let dir = tmpdir.join("test2");
2880 let link = dir.join("link");
2881 let linkdir = tmpdir.join("test3");
2883 File::create(&file).unwrap();
2884 fs::create_dir(&dir).unwrap();
2885 symlink_file(&file, &link).unwrap();
2886 symlink_dir(&dir, &linkdir).unwrap();
2888 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2890 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2891 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2892 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2893 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2894 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2898 fn realpath_works_tricky() {
2899 let tmpdir = tmpdir();
2900 if !got_symlink_permission(&tmpdir) { return };
2902 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2903 let a = tmpdir.join("a");
2904 let b = a.join("b");
2905 let c = b.join("c");
2906 let d = a.join("d");
2907 let e = d.join("e");
2908 let f = a.join("f");
2910 fs::create_dir_all(&b).unwrap();
2911 fs::create_dir_all(&d).unwrap();
2912 File::create(&f).unwrap();
2913 if cfg!(not(windows)) {
2914 symlink_dir("../d/e", &c).unwrap();
2915 symlink_file("../f", &e).unwrap();
2918 symlink_dir(r"..\d\e", &c).unwrap();
2919 symlink_file(r"..\f", &e).unwrap();
2922 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2923 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2927 fn dir_entry_methods() {
2928 let tmpdir = tmpdir();
2930 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2931 File::create(&tmpdir.join("b")).unwrap();
2933 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2934 let fname = file.file_name();
2935 match fname.to_str() {
2937 assert!(file.file_type().unwrap().is_dir());
2938 assert!(file.metadata().unwrap().is_dir());
2941 assert!(file.file_type().unwrap().is_file());
2942 assert!(file.metadata().unwrap().is_file());
2944 f => panic!("unknown file name: {:?}", f),
2950 fn dir_entry_debug() {
2951 let tmpdir = tmpdir();
2952 File::create(&tmpdir.join("b")).unwrap();
2953 let mut read_dir = tmpdir.path().read_dir().unwrap();
2954 let dir_entry = read_dir.next().unwrap().unwrap();
2955 let actual = format!("{:?}", dir_entry);
2956 let expected = format!("DirEntry({:?})", dir_entry.0.path());
2957 assert_eq!(actual, expected);
2961 fn read_dir_not_found() {
2962 let res = fs::read_dir("/path/that/does/not/exist");
2963 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
2967 fn create_dir_all_with_junctions() {
2968 let tmpdir = tmpdir();
2969 let target = tmpdir.join("target");
2971 let junction = tmpdir.join("junction");
2972 let b = junction.join("a/b");
2974 let link = tmpdir.join("link");
2975 let d = link.join("c/d");
2977 fs::create_dir(&target).unwrap();
2979 check!(symlink_junction(&target, &junction));
2980 check!(fs::create_dir_all(&b));
2981 // the junction itself is not a directory, but `is_dir()` on a Path
2983 assert!(junction.is_dir());
2984 assert!(b.exists());
2986 if !got_symlink_permission(&tmpdir) { return };
2987 check!(symlink_dir(&target, &link));
2988 check!(fs::create_dir_all(&d));
2989 assert!(link.is_dir());
2990 assert!(d.exists());
2994 fn metadata_access_times() {
2995 let tmpdir = tmpdir();
2997 let b = tmpdir.join("b");
2998 File::create(&b).unwrap();
3000 let a = check!(fs::metadata(&tmpdir.path()));
3001 let b = check!(fs::metadata(&b));
3003 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3004 assert_eq!(check!(a.modified()), check!(a.modified()));
3005 assert_eq!(check!(b.accessed()), check!(b.modified()));
3007 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3008 check!(a.created());
3009 check!(b.created());