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::io::read_to_end_uninitialized;
26 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)
314 impl AsInner<fs_imp::File> for File {
315 fn as_inner(&self) -> &fs_imp::File { &self.inner }
317 impl FromInner<fs_imp::File> for File {
318 fn from_inner(f: fs_imp::File) -> File {
322 impl IntoInner<fs_imp::File> for File {
323 fn into_inner(self) -> fs_imp::File {
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl fmt::Debug for File {
330 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
335 #[stable(feature = "rust1", since = "1.0.0")]
337 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
340 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
341 unsafe { read_to_end_uninitialized(self, buf) }
344 #[stable(feature = "rust1", since = "1.0.0")]
345 impl Write for File {
346 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
347 self.inner.write(buf)
349 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
351 #[stable(feature = "rust1", since = "1.0.0")]
353 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a> Read for &'a File {
359 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<'a> Write for &'a File {
365 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
366 self.inner.write(buf)
368 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl<'a> Seek for &'a File {
372 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
378 /// Creates a blank new set of options ready for configuration.
380 /// All options are initially set to `false`.
385 /// use std::fs::OpenOptions;
387 /// let mut options = OpenOptions::new();
388 /// let file = options.read(true).open("foo.txt");
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn new() -> OpenOptions {
392 OpenOptions(fs_imp::OpenOptions::new())
395 /// Sets the option for read access.
397 /// This option, when true, will indicate that the file should be
398 /// `read`-able if opened.
403 /// use std::fs::OpenOptions;
405 /// let file = OpenOptions::new().read(true).open("foo.txt");
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
409 self.0.read(read); self
412 /// Sets the option for write access.
414 /// This option, when true, will indicate that the file should be
415 /// `write`-able if opened.
417 /// If a file already exist, any write calls on the file will overwrite its
418 /// contents, without truncating it.
423 /// use std::fs::OpenOptions;
425 /// let file = OpenOptions::new().write(true).open("foo.txt");
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
429 self.0.write(write); self
432 /// Sets the option for the append mode.
434 /// This option, when true, means that writes will append to a file instead
435 /// of overwriting previous contents.
436 /// Note that setting `.write(true).append(true)` has the same effect as
437 /// setting only `.append(true)`.
439 /// For most filesystems the operating system guarantees all writes are
440 /// atomic: no writes get mangled because another process writes at the same
443 /// One maybe obvious note when using append-mode: make sure that all data
444 /// that belongs together, is written the the file in one operation. This
445 /// can be done by concatenating strings before passing them to `write()`,
446 /// or using a buffered writer (with a more than adequately sized buffer)
447 /// and calling `flush()` when the message is complete.
449 /// If a file is opened with both read and append access, beware that after
450 /// opening and after every write the position for reading may be set at the
451 /// end of the file. So before writing save the current position (using
452 /// `seek(SeekFrom::Current(0))`, and restore it before the next read.
457 /// use std::fs::OpenOptions;
459 /// let file = OpenOptions::new().append(true).open("foo.txt");
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
463 self.0.append(append); self
466 /// Sets the option for truncating a previous file.
468 /// If a file is successfully opened with this option set it will truncate
469 /// the file to 0 length if it already exists.
471 /// The file must be opened with write access for truncate to work.
476 /// use std::fs::OpenOptions;
478 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
482 self.0.truncate(truncate); self
485 /// Sets the option for creating a new file.
487 /// This option indicates whether a new file will be created if the file
488 /// does not yet already exist.
490 /// The file must be opened with write or append access in order to create
496 /// use std::fs::OpenOptions;
498 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
502 self.0.create(create); self
505 /// Sets the option to always create a new file.
507 /// This option indicates whether a new file will be created.
508 /// No file is allowed to exist at the target location, also no (dangling)
511 /// This option is usefull because it as atomic. Otherwise between checking
512 /// whether a file exists and creating a new one, the file may have been
513 /// created by another process (a TOCTOU race condition / attack).
515 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are
518 /// The file must be opened with write or append access in order to create
524 /// #![feature(expand_open_options)]
525 /// use std::fs::OpenOptions;
527 /// let file = OpenOptions::new().write(true)
528 /// .create_new(true)
529 /// .open("foo.txt");
531 #[unstable(feature = "expand_open_options",
532 reason = "recently added",
534 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
535 self.0.create_new(create_new); self
538 /// Opens a file at `path` with the options specified by `self`.
542 /// This function will return an error under a number of different
543 /// circumstances, to include but not limited to:
545 /// * Opening a file that does not exist without setting `create` or
547 /// * Attempting to open a file with access that the user lacks
549 /// * Filesystem-level errors (full disk, etc)
550 /// * Invalid combinations of open options (truncate without write access,
551 /// no access mode set, etc)
556 /// use std::fs::OpenOptions;
558 /// let file = OpenOptions::new().open("foo.txt");
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
562 self._open(path.as_ref())
565 fn _open(&self, path: &Path) -> io::Result<File> {
566 let inner = try!(fs_imp::File::open(path, &self.0));
567 Ok(File { inner: inner })
571 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
572 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
576 /// Returns the file type for this metadata.
577 #[stable(feature = "file_type", since = "1.1.0")]
578 pub fn file_type(&self) -> FileType {
579 FileType(self.0.file_type())
582 /// Returns whether this metadata is for a directory.
587 /// # fn foo() -> std::io::Result<()> {
590 /// let metadata = try!(fs::metadata("foo.txt"));
592 /// assert!(!metadata.is_dir());
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
599 /// Returns whether this metadata is for a regular file.
604 /// # fn foo() -> std::io::Result<()> {
607 /// let metadata = try!(fs::metadata("foo.txt"));
609 /// assert!(metadata.is_file());
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn is_file(&self) -> bool { self.file_type().is_file() }
616 /// Returns the size of the file, in bytes, this metadata is for.
621 /// # fn foo() -> std::io::Result<()> {
624 /// let metadata = try!(fs::metadata("foo.txt"));
626 /// assert_eq!(0, metadata.len());
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn len(&self) -> u64 { self.0.size() }
633 /// Returns the permissions of the file this metadata is for.
638 /// # fn foo() -> std::io::Result<()> {
641 /// let metadata = try!(fs::metadata("foo.txt"));
643 /// assert!(!metadata.permissions().readonly());
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn permissions(&self) -> Permissions {
649 Permissions(self.0.perm())
653 impl AsInner<fs_imp::FileAttr> for Metadata {
654 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
658 /// Returns whether these permissions describe a readonly file.
663 /// use std::fs::File;
665 /// # fn foo() -> std::io::Result<()> {
666 /// let mut f = try!(File::create("foo.txt"));
667 /// let metadata = try!(f.metadata());
669 /// assert_eq!(false, metadata.permissions().readonly());
673 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn readonly(&self) -> bool { self.0.readonly() }
676 /// Modifies the readonly flag for this set of permissions.
678 /// This operation does **not** modify the filesystem. To modify the
679 /// filesystem use the `fs::set_permissions` function.
684 /// use std::fs::File;
686 /// # fn foo() -> std::io::Result<()> {
687 /// let f = try!(File::create("foo.txt"));
688 /// let metadata = try!(f.metadata());
689 /// let mut permissions = metadata.permissions();
691 /// permissions.set_readonly(true);
693 /// // filesystem doesn't change
694 /// assert_eq!(false, metadata.permissions().readonly());
696 /// // just this particular `permissions`.
697 /// assert_eq!(true, permissions.readonly());
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn set_readonly(&mut self, readonly: bool) {
703 self.0.set_readonly(readonly)
708 /// Test whether this file type represents a directory.
709 #[stable(feature = "file_type", since = "1.1.0")]
710 pub fn is_dir(&self) -> bool { self.0.is_dir() }
712 /// Test whether this file type represents a regular file.
713 #[stable(feature = "file_type", since = "1.1.0")]
714 pub fn is_file(&self) -> bool { self.0.is_file() }
716 /// Test whether this file type represents a symbolic link.
717 #[stable(feature = "file_type", since = "1.1.0")]
718 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
721 impl AsInner<fs_imp::FileType> for FileType {
722 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
725 impl FromInner<fs_imp::FilePermissions> for Permissions {
726 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
731 impl AsInner<fs_imp::FilePermissions> for Permissions {
732 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl Iterator for ReadDir {
737 type Item = io::Result<DirEntry>;
739 fn next(&mut self) -> Option<io::Result<DirEntry>> {
740 self.0.next().map(|entry| entry.map(DirEntry))
745 /// Returns the full path to the file that this entry represents.
747 /// The full path is created by joining the original path to `read_dir` or
748 /// `walk_dir` with the filename of this entry.
754 /// # fn foo() -> std::io::Result<()> {
755 /// for entry in try!(fs::read_dir(".")) {
756 /// let dir = try!(entry);
757 /// println!("{:?}", dir.path());
763 /// This prints output like:
768 /// "./hello_world.rs"
771 /// The exact text, of course, depends on what files you have in `.`.
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn path(&self) -> PathBuf { self.0.path() }
775 /// Return the metadata for the file that this entry points at.
777 /// This function will not traverse symlinks if this entry points at a
780 /// # Platform-specific behavior
782 /// On Windows this function is cheap to call (no extra system calls
783 /// needed), but on Unix platforms this function is the equivalent of
784 /// calling `symlink_metadata` on the path.
785 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
786 pub fn metadata(&self) -> io::Result<Metadata> {
787 self.0.metadata().map(Metadata)
790 /// Return the file type for the file that this entry points at.
792 /// This function will not traverse symlinks if this entry points at a
795 /// # Platform-specific behavior
797 /// On Windows and most Unix platforms this function is free (no extra
798 /// system calls needed), but some Unix platforms may require the equivalent
799 /// call to `symlink_metadata` to learn about the target file type.
800 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
801 pub fn file_type(&self) -> io::Result<FileType> {
802 self.0.file_type().map(FileType)
805 /// Returns the bare file name of this directory entry without any other
806 /// leading path component.
807 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
808 pub fn file_name(&self) -> OsString {
813 impl AsInner<fs_imp::DirEntry> for DirEntry {
814 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
817 /// Removes a file from the filesystem.
819 /// Note that there is no
820 /// guarantee that the file is immediately deleted (e.g. depending on
821 /// platform, other open file descriptors may prevent immediate removal).
823 /// # Platform-specific behavior
825 /// This function currently corresponds to the `unlink` function on Unix
826 /// and the `DeleteFile` function on Windows.
827 /// Note that, this [may change in the future][changes].
828 /// [changes]: ../io/index.html#platform-specific-behavior
832 /// This function will return an error in the following situations, but is not
833 /// limited to just these cases:
835 /// * `path` points to a directory.
836 /// * The user lacks permissions to remove the file.
843 /// # fn foo() -> std::io::Result<()> {
844 /// try!(fs::remove_file("a.txt"));
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
850 fs_imp::unlink(path.as_ref())
853 /// Given a path, query the file system to get information about a file,
856 /// This function will traverse symbolic links to query information about the
857 /// destination file.
859 /// # Platform-specific behavior
861 /// This function currently corresponds to the `stat` function on Unix
862 /// and the `GetFileAttributesEx` function on Windows.
863 /// Note that, this [may change in the future][changes].
864 /// [changes]: ../io/index.html#platform-specific-behavior
868 /// This function will return an error in the following situations, but is not
869 /// limited to just these cases:
871 /// * The user lacks permissions to perform `metadata` call on `path`.
872 /// * `path` does not exist.
877 /// # fn foo() -> std::io::Result<()> {
880 /// let attr = try!(fs::metadata("/some/file/path.txt"));
881 /// // inspect attr ...
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
887 fs_imp::stat(path.as_ref()).map(Metadata)
890 /// Query the metadata about a file without following symlinks.
892 /// # Platform-specific behavior
894 /// This function currently corresponds to the `lstat` function on Unix
895 /// and the `GetFileAttributesEx` function on Windows.
896 /// Note that, this [may change in the future][changes].
897 /// [changes]: ../io/index.html#platform-specific-behavior
901 /// This function will return an error in the following situations, but is not
902 /// limited to just these cases:
904 /// * The user lacks permissions to perform `metadata` call on `path`.
905 /// * `path` does not exist.
910 /// # fn foo() -> std::io::Result<()> {
913 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
914 /// // inspect attr ...
918 #[stable(feature = "symlink_metadata", since = "1.1.0")]
919 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
920 fs_imp::lstat(path.as_ref()).map(Metadata)
923 /// Rename a file or directory to a new name.
925 /// This will not work if the new name is on a different mount point.
927 /// # Platform-specific behavior
929 /// This function currently corresponds to the `rename` function on Unix
930 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
931 /// Note that, this [may change in the future][changes].
932 /// [changes]: ../io/index.html#platform-specific-behavior
936 /// This function will return an error in the following situations, but is not
937 /// limited to just these cases:
939 /// * `from` does not exist.
940 /// * The user lacks permissions to view contents.
941 /// * `from` and `to` are on separate filesystems.
948 /// # fn foo() -> std::io::Result<()> {
949 /// try!(fs::rename("a.txt", "b.txt")); // Rename a.txt to b.txt
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
955 fs_imp::rename(from.as_ref(), to.as_ref())
958 /// Copies the contents of one file to another. This function will also
959 /// copy the permission bits of the original file to the destination file.
961 /// This function will **overwrite** the contents of `to`.
963 /// Note that if `from` and `to` both point to the same file, then the file
964 /// will likely get truncated by this operation.
966 /// On success, the total number of bytes copied is returned.
968 /// # Platform-specific behavior
970 /// This function currently corresponds to the `open` function in Unix
971 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
972 /// `O_CLOEXEC` is set for returned file descriptors.
973 /// On Windows, this function currently corresponds to `CopyFileEx`.
974 /// Note that, this [may change in the future][changes].
975 /// [changes]: ../io/index.html#platform-specific-behavior
979 /// This function will return an error in the following situations, but is not
980 /// limited to just these cases:
982 /// * The `from` path is not a file.
983 /// * The `from` file does not exist.
984 /// * The current process does not have the permission rights to access
985 /// `from` or write `to`.
992 /// # fn foo() -> std::io::Result<()> {
993 /// try!(fs::copy("foo.txt", "bar.txt")); // Copy foo.txt to bar.txt
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
998 fs_imp::copy(from.as_ref(), to.as_ref())
1001 /// Creates a new hard link on the filesystem.
1003 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1004 /// often require these two paths to both be located on the same filesystem.
1006 /// # Platform-specific behavior
1008 /// This function currently corresponds to the `link` function on Unix
1009 /// and the `CreateHardLink` function on Windows.
1010 /// Note that, this [may change in the future][changes].
1011 /// [changes]: ../io/index.html#platform-specific-behavior
1015 /// This function will return an error in the following situations, but is not
1016 /// limited to just these cases:
1018 /// * The `src` path is not a file or doesn't exist.
1025 /// # fn foo() -> std::io::Result<()> {
1026 /// try!(fs::hard_link("a.txt", "b.txt")); // Hard link a.txt to b.txt
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1032 fs_imp::link(src.as_ref(), dst.as_ref())
1035 /// Creates a new symbolic link on the filesystem.
1037 /// The `dst` path will be a symbolic link pointing to the `src` path.
1038 /// On Windows, this will be a file symlink, not a directory symlink;
1039 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1040 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1041 /// used instead to make the intent explicit.
1048 /// # fn foo() -> std::io::Result<()> {
1049 /// try!(fs::soft_link("a.txt", "b.txt"));
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 #[rustc_deprecated(since = "1.1.0",
1055 reason = "replaced with std::os::unix::fs::symlink and \
1056 std::os::windows::fs::{symlink_file, symlink_dir}")]
1057 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1058 fs_imp::symlink(src.as_ref(), dst.as_ref())
1061 /// Reads a symbolic link, returning the file that the link points to.
1063 /// # Platform-specific behavior
1065 /// This function currently corresponds to the `readlink` function on Unix
1066 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1067 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1068 /// Note that, this [may change in the future][changes].
1069 /// [changes]: ../io/index.html#platform-specific-behavior
1073 /// This function will return an error in the following situations, but is not
1074 /// limited to just these cases:
1076 /// * `path` is not a symbolic link.
1077 /// * `path` does not exist.
1084 /// # fn foo() -> std::io::Result<()> {
1085 /// let path = try!(fs::read_link("a.txt"));
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1091 fs_imp::readlink(path.as_ref())
1094 /// Returns the canonical form of a path with all intermediate components
1095 /// normalized and symbolic links resolved.
1097 /// # Platform-specific behavior
1099 /// This function currently corresponds to the `realpath` function on Unix
1100 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1101 /// Note that, this [may change in the future][changes].
1102 /// [changes]: ../io/index.html#platform-specific-behavior
1106 /// This function will return an error in the following situations, but is not
1107 /// limited to just these cases:
1109 /// * `path` does not exist.
1110 /// * A component in path is not a directory.
1117 /// # fn foo() -> std::io::Result<()> {
1118 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
1122 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1123 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1124 fs_imp::canonicalize(path.as_ref())
1127 /// Creates a new, empty directory at the provided path
1129 /// # Platform-specific behavior
1131 /// This function currently corresponds to the `mkdir` function on Unix
1132 /// and the `CreateDirectory` function on Windows.
1133 /// Note that, this [may change in the future][changes].
1134 /// [changes]: ../io/index.html#platform-specific-behavior
1138 /// This function will return an error in the following situations, but is not
1139 /// limited to just these cases:
1141 /// * User lacks permissions to create directory at `path`.
1142 /// * `path` already exists.
1149 /// # fn foo() -> std::io::Result<()> {
1150 /// try!(fs::create_dir("/some/dir"));
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1156 DirBuilder::new().create(path.as_ref())
1159 /// Recursively create a directory and all of its parent components if they
1162 /// # Platform-specific behavior
1164 /// This function currently corresponds to the `mkdir` function on Unix
1165 /// and the `CreateDirectory` function on Windows.
1166 /// Note that, this [may change in the future][changes].
1167 /// [changes]: ../io/index.html#platform-specific-behavior
1171 /// This function will return an error in the following situations, but is not
1172 /// limited to just these cases:
1174 /// * If any directory in the path specified by `path`
1175 /// does not already exist and it could not be created otherwise. The specific
1176 /// error conditions for when a directory is being created (after it is
1177 /// determined to not exist) are outlined by `fs::create_dir`.
1184 /// # fn foo() -> std::io::Result<()> {
1185 /// try!(fs::create_dir_all("/some/dir"));
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1191 DirBuilder::new().recursive(true).create(path.as_ref())
1194 /// Removes an existing, empty directory.
1196 /// # Platform-specific behavior
1198 /// This function currently corresponds to the `rmdir` function on Unix
1199 /// and the `RemoveDirectory` function on Windows.
1200 /// Note that, this [may change in the future][changes].
1201 /// [changes]: ../io/index.html#platform-specific-behavior
1205 /// This function will return an error in the following situations, but is not
1206 /// limited to just these cases:
1208 /// * The user lacks permissions to remove the directory at the provided `path`.
1209 /// * The directory isn't empty.
1216 /// # fn foo() -> std::io::Result<()> {
1217 /// try!(fs::remove_dir("/some/dir"));
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1223 fs_imp::rmdir(path.as_ref())
1226 /// Removes a directory at this path, after removing all its contents. Use
1229 /// This function does **not** follow symbolic links and it will simply remove the
1230 /// symbolic link itself.
1232 /// # Platform-specific behavior
1234 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1235 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1237 /// Note that, this [may change in the future][changes].
1238 /// [changes]: ../io/index.html#platform-specific-behavior
1242 /// See `file::remove_file` and `fs::remove_dir`.
1249 /// # fn foo() -> std::io::Result<()> {
1250 /// try!(fs::remove_dir_all("/some/dir"));
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1256 _remove_dir_all(path.as_ref())
1259 fn _remove_dir_all(path: &Path) -> io::Result<()> {
1260 for child in try!(read_dir(path)) {
1261 let child = try!(child).path();
1262 let stat = try!(symlink_metadata(&*child));
1264 try!(remove_dir_all(&*child));
1266 try!(remove_file(&*child));
1272 /// Returns an iterator over the entries within a directory.
1274 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1275 /// be encountered after an iterator is initially constructed.
1277 /// # Platform-specific behavior
1279 /// This function currently corresponds to the `opendir` function on Unix
1280 /// and the `FindFirstFile` function on Windows.
1281 /// Note that, this [may change in the future][changes].
1282 /// [changes]: ../io/index.html#platform-specific-behavior
1286 /// This function will return an error in the following situations, but is not
1287 /// limited to just these cases:
1289 /// * The provided `path` doesn't exist.
1290 /// * The process lacks permissions to view the contents.
1291 /// * The `path` points at a non-directory file.
1297 /// use std::fs::{self, DirEntry};
1298 /// use std::path::Path;
1300 /// // one possible implementation of fs::walk_dir only visiting files
1301 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1302 /// if try!(fs::metadata(dir)).is_dir() {
1303 /// for entry in try!(fs::read_dir(dir)) {
1304 /// let entry = try!(entry);
1305 /// if try!(fs::metadata(entry.path())).is_dir() {
1306 /// try!(visit_dirs(&entry.path(), cb));
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1317 fs_imp::readdir(path.as_ref()).map(ReadDir)
1320 /// Returns an iterator that will recursively walk the directory structure
1321 /// rooted at `path`.
1323 /// The path given will not be iterated over, and this will perform iteration in
1324 /// some top-down order. The contents of unreadable subdirectories are ignored.
1326 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1327 /// be encountered after an iterator is initially constructed.
1328 #[unstable(feature = "fs_walk",
1329 reason = "the precise semantics and defaults for a recursive walk \
1330 may change and this may end up accounting for files such \
1331 as symlinks differently",
1333 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1335 #[allow(deprecated)]
1336 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1337 _walk_dir(path.as_ref())
1340 #[allow(deprecated)]
1341 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1342 let start = try!(read_dir(path));
1343 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1346 #[unstable(feature = "fs_walk", issue = "27707")]
1347 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1349 #[allow(deprecated)]
1350 impl Iterator for WalkDir {
1351 type Item = io::Result<DirEntry>;
1353 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1355 if let Some(ref mut cur) = self.cur {
1357 Some(Err(e)) => return Some(Err(e)),
1359 let path = next.path();
1361 self.stack.push(read_dir(&*path));
1363 return Some(Ok(next))
1369 match self.stack.pop() {
1370 Some(Err(e)) => return Some(Err(e)),
1371 Some(Ok(next)) => self.cur = Some(next),
1372 None => return None,
1378 /// Changes the permissions found on a file or a directory.
1380 /// # Platform-specific behavior
1382 /// This function currently corresponds to the `chmod` function on Unix
1383 /// and the `SetFileAttributes` function on Windows.
1384 /// Note that, this [may change in the future][changes].
1385 /// [changes]: ../io/index.html#platform-specific-behavior
1389 /// This function will return an error in the following situations, but is not
1390 /// limited to just these cases:
1392 /// * `path` does not exist.
1393 /// * The user lacks the permission to change attributes of the file.
1398 /// # fn foo() -> std::io::Result<()> {
1401 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1402 /// perms.set_readonly(true);
1403 /// try!(fs::set_permissions("foo.txt", perms));
1407 #[stable(feature = "set_permissions", since = "1.1.0")]
1408 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1410 fs_imp::set_perm(path.as_ref(), perm.0)
1414 /// Creates a new set of options with default mode/security settings for all
1415 /// platforms and also non-recursive.
1416 #[stable(feature = "dir_builder", since = "1.6.0")]
1417 pub fn new() -> DirBuilder {
1419 inner: fs_imp::DirBuilder::new(),
1424 /// Indicate that directories create should be created recursively, creating
1425 /// all parent directories if they do not exist with the same security and
1426 /// permissions settings.
1428 /// This option defaults to `false`
1429 #[stable(feature = "dir_builder", since = "1.6.0")]
1430 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1431 self.recursive = recursive;
1435 /// Create the specified directory with the options configured in this
1441 /// use std::fs::{self, DirBuilder};
1443 /// let path = "/tmp/foo/bar/baz";
1444 /// DirBuilder::new()
1445 /// .recursive(true)
1446 /// .create(path).unwrap();
1448 /// assert!(fs::metadata(path).unwrap().is_dir());
1450 #[stable(feature = "dir_builder", since = "1.6.0")]
1451 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1452 self._create(path.as_ref())
1455 fn _create(&self, path: &Path) -> io::Result<()> {
1457 self.create_dir_all(path)
1459 self.inner.mkdir(path)
1463 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1464 if path == Path::new("") || path.is_dir() { return Ok(()) }
1465 if let Some(p) = path.parent() {
1466 try!(self.create_dir_all(p))
1468 self.inner.mkdir(path)
1472 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1473 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1480 #![allow(deprecated)] //rand
1486 use fs::{self, File, OpenOptions};
1487 use io::{ErrorKind, SeekFrom};
1489 use path::Path as Path2;
1490 use rand::{self, StdRng, Rng};
1493 macro_rules! check { ($e:expr) => (
1496 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1500 macro_rules! error { ($e:expr, $s:expr) => (
1502 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1503 Err(ref err) => assert!(err.to_string().contains($s),
1504 format!("`{}` did not contain `{}`", err, $s))
1508 pub struct TempDir(PathBuf);
1511 fn join(&self, path: &str) -> PathBuf {
1512 let TempDir(ref p) = *self;
1516 fn path<'a>(&'a self) -> &'a Path2 {
1517 let TempDir(ref p) = *self;
1522 impl Drop for TempDir {
1523 fn drop(&mut self) {
1524 // Gee, seeing how we're testing the fs module I sure hope that we
1525 // at least implement this correctly!
1526 let TempDir(ref p) = *self;
1527 check!(fs::remove_dir_all(p));
1531 pub fn tmpdir() -> TempDir {
1532 let p = env::temp_dir();
1533 let mut r = rand::thread_rng();
1534 let ret = p.join(&format!("rust-{}", r.next_u32()));
1535 check!(fs::create_dir(&ret));
1540 fn file_test_io_smoke_test() {
1541 let message = "it's alright. have a good time";
1542 let tmpdir = tmpdir();
1543 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1545 let mut write_stream = check!(File::create(filename));
1546 check!(write_stream.write(message.as_bytes()));
1549 let mut read_stream = check!(File::open(filename));
1550 let mut read_buf = [0; 1028];
1551 let read_str = match check!(read_stream.read(&mut read_buf)) {
1552 0 => panic!("shouldn't happen"),
1553 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1555 assert_eq!(read_str, message);
1557 check!(fs::remove_file(filename));
1561 fn invalid_path_raises() {
1562 let tmpdir = tmpdir();
1563 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1564 let result = File::open(filename);
1567 error!(result, "o such file or directory");
1569 // error!(result, "couldn't open path as file");
1570 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1574 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1575 let tmpdir = tmpdir();
1576 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1578 let result = fs::remove_file(filename);
1581 error!(result, "o such file or directory");
1583 // error!(result, "couldn't unlink path");
1584 // error!(result, format!("path={}", filename.display()));
1588 fn file_test_io_non_positional_read() {
1589 let message: &str = "ten-four";
1590 let mut read_mem = [0; 8];
1591 let tmpdir = tmpdir();
1592 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1594 let mut rw_stream = check!(File::create(filename));
1595 check!(rw_stream.write(message.as_bytes()));
1598 let mut read_stream = check!(File::open(filename));
1600 let read_buf = &mut read_mem[0..4];
1601 check!(read_stream.read(read_buf));
1604 let read_buf = &mut read_mem[4..8];
1605 check!(read_stream.read(read_buf));
1608 check!(fs::remove_file(filename));
1609 let read_str = str::from_utf8(&read_mem).unwrap();
1610 assert_eq!(read_str, message);
1614 fn file_test_io_seek_and_tell_smoke_test() {
1615 let message = "ten-four";
1616 let mut read_mem = [0; 4];
1617 let set_cursor = 4 as u64;
1618 let tell_pos_pre_read;
1619 let tell_pos_post_read;
1620 let tmpdir = tmpdir();
1621 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1623 let mut rw_stream = check!(File::create(filename));
1624 check!(rw_stream.write(message.as_bytes()));
1627 let mut read_stream = check!(File::open(filename));
1628 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1629 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1630 check!(read_stream.read(&mut read_mem));
1631 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1633 check!(fs::remove_file(filename));
1634 let read_str = str::from_utf8(&read_mem).unwrap();
1635 assert_eq!(read_str, &message[4..8]);
1636 assert_eq!(tell_pos_pre_read, set_cursor);
1637 assert_eq!(tell_pos_post_read, message.len() as u64);
1641 fn file_test_io_seek_and_write() {
1642 let initial_msg = "food-is-yummy";
1643 let overwrite_msg = "-the-bar!!";
1644 let final_msg = "foo-the-bar!!";
1646 let mut read_mem = [0; 13];
1647 let tmpdir = tmpdir();
1648 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1650 let mut rw_stream = check!(File::create(filename));
1651 check!(rw_stream.write(initial_msg.as_bytes()));
1652 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1653 check!(rw_stream.write(overwrite_msg.as_bytes()));
1656 let mut read_stream = check!(File::open(filename));
1657 check!(read_stream.read(&mut read_mem));
1659 check!(fs::remove_file(filename));
1660 let read_str = str::from_utf8(&read_mem).unwrap();
1661 assert!(read_str == final_msg);
1665 fn file_test_io_seek_shakedown() {
1667 let initial_msg = "qwer-asdf-zxcv";
1668 let chunk_one: &str = "qwer";
1669 let chunk_two: &str = "asdf";
1670 let chunk_three: &str = "zxcv";
1671 let mut read_mem = [0; 4];
1672 let tmpdir = tmpdir();
1673 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1675 let mut rw_stream = check!(File::create(filename));
1676 check!(rw_stream.write(initial_msg.as_bytes()));
1679 let mut read_stream = check!(File::open(filename));
1681 check!(read_stream.seek(SeekFrom::End(-4)));
1682 check!(read_stream.read(&mut read_mem));
1683 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1685 check!(read_stream.seek(SeekFrom::Current(-9)));
1686 check!(read_stream.read(&mut read_mem));
1687 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1689 check!(read_stream.seek(SeekFrom::Start(0)));
1690 check!(read_stream.read(&mut read_mem));
1691 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1693 check!(fs::remove_file(filename));
1697 fn file_test_stat_is_correct_on_is_file() {
1698 let tmpdir = tmpdir();
1699 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1701 let mut opts = OpenOptions::new();
1702 let mut fs = check!(opts.read(true).write(true)
1703 .create(true).open(filename));
1705 fs.write(msg.as_bytes()).unwrap();
1707 let fstat_res = check!(fs.metadata());
1708 assert!(fstat_res.is_file());
1710 let stat_res_fn = check!(fs::metadata(filename));
1711 assert!(stat_res_fn.is_file());
1712 let stat_res_meth = check!(filename.metadata());
1713 assert!(stat_res_meth.is_file());
1714 check!(fs::remove_file(filename));
1718 fn file_test_stat_is_correct_on_is_dir() {
1719 let tmpdir = tmpdir();
1720 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1721 check!(fs::create_dir(filename));
1722 let stat_res_fn = check!(fs::metadata(filename));
1723 assert!(stat_res_fn.is_dir());
1724 let stat_res_meth = check!(filename.metadata());
1725 assert!(stat_res_meth.is_dir());
1726 check!(fs::remove_dir(filename));
1730 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1731 let tmpdir = tmpdir();
1732 let dir = &tmpdir.join("fileinfo_false_on_dir");
1733 check!(fs::create_dir(dir));
1734 assert!(dir.is_file() == false);
1735 check!(fs::remove_dir(dir));
1739 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1740 let tmpdir = tmpdir();
1741 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1742 check!(check!(File::create(file)).write(b"foo"));
1743 assert!(file.exists());
1744 check!(fs::remove_file(file));
1745 assert!(!file.exists());
1749 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1750 let tmpdir = tmpdir();
1751 let dir = &tmpdir.join("before_and_after_dir");
1752 assert!(!dir.exists());
1753 check!(fs::create_dir(dir));
1754 assert!(dir.exists());
1755 assert!(dir.is_dir());
1756 check!(fs::remove_dir(dir));
1757 assert!(!dir.exists());
1761 fn file_test_directoryinfo_readdir() {
1762 let tmpdir = tmpdir();
1763 let dir = &tmpdir.join("di_readdir");
1764 check!(fs::create_dir(dir));
1767 let f = dir.join(&format!("{}.txt", n));
1768 let mut w = check!(File::create(&f));
1769 let msg_str = format!("{}{}", prefix, n.to_string());
1770 let msg = msg_str.as_bytes();
1771 check!(w.write(msg));
1773 let files = check!(fs::read_dir(dir));
1774 let mut mem = [0; 4];
1776 let f = f.unwrap().path();
1778 let n = f.file_stem().unwrap();
1779 check!(check!(File::open(&f)).read(&mut mem));
1780 let read_str = str::from_utf8(&mem).unwrap();
1781 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1782 assert_eq!(expected, read_str);
1784 check!(fs::remove_file(&f));
1786 check!(fs::remove_dir(dir));
1790 fn file_test_walk_dir() {
1791 let tmpdir = tmpdir();
1792 let dir = &tmpdir.join("walk_dir");
1793 check!(fs::create_dir(dir));
1795 let dir1 = &dir.join("01/02/03");
1796 check!(fs::create_dir_all(dir1));
1797 check!(File::create(&dir1.join("04")));
1799 let dir2 = &dir.join("11/12/13");
1800 check!(fs::create_dir_all(dir2));
1801 check!(File::create(&dir2.join("14")));
1803 let files = check!(fs::walk_dir(dir));
1804 let mut cur = [0; 2];
1806 let f = f.unwrap().path();
1807 let stem = f.file_stem().unwrap().to_str().unwrap();
1808 let root = stem.as_bytes()[0] - b'0';
1809 let name = stem.as_bytes()[1] - b'0';
1810 assert!(cur[root as usize] < name);
1811 cur[root as usize] = name;
1814 check!(fs::remove_dir_all(dir));
1818 fn mkdir_path_already_exists_error() {
1819 let tmpdir = tmpdir();
1820 let dir = &tmpdir.join("mkdir_error_twice");
1821 check!(fs::create_dir(dir));
1822 let e = fs::create_dir(dir).err().unwrap();
1823 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1827 fn recursive_mkdir() {
1828 let tmpdir = tmpdir();
1829 let dir = tmpdir.join("d1/d2");
1830 check!(fs::create_dir_all(&dir));
1831 assert!(dir.is_dir())
1835 fn recursive_mkdir_failure() {
1836 let tmpdir = tmpdir();
1837 let dir = tmpdir.join("d1");
1838 let file = dir.join("f1");
1840 check!(fs::create_dir_all(&dir));
1841 check!(File::create(&file));
1843 let result = fs::create_dir_all(&file);
1845 assert!(result.is_err());
1846 // error!(result, "couldn't recursively mkdir");
1847 // error!(result, "couldn't create directory");
1848 // error!(result, "mode=0700");
1849 // error!(result, format!("path={}", file.display()));
1853 fn recursive_mkdir_slash() {
1854 check!(fs::create_dir_all(&Path2::new("/")));
1857 // FIXME(#12795) depends on lstat to work on windows
1858 #[cfg(not(windows))]
1860 fn recursive_rmdir() {
1861 let tmpdir = tmpdir();
1862 let d1 = tmpdir.join("d1");
1863 let dt = d1.join("t");
1864 let dtt = dt.join("t");
1865 let d2 = tmpdir.join("d2");
1866 let canary = d2.join("do_not_delete");
1867 check!(fs::create_dir_all(&dtt));
1868 check!(fs::create_dir_all(&d2));
1869 check!(check!(File::create(&canary)).write(b"foo"));
1870 check!(fs::soft_link(&d2, &dt.join("d2")));
1871 check!(fs::remove_dir_all(&d1));
1873 assert!(!d1.is_dir());
1874 assert!(canary.exists());
1878 fn unicode_path_is_dir() {
1879 assert!(Path2::new(".").is_dir());
1880 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1882 let tmpdir = tmpdir();
1884 let mut dirpath = tmpdir.path().to_path_buf();
1885 dirpath.push("test-가一ー你好");
1886 check!(fs::create_dir(&dirpath));
1887 assert!(dirpath.is_dir());
1889 let mut filepath = dirpath;
1890 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1891 check!(File::create(&filepath)); // ignore return; touch only
1892 assert!(!filepath.is_dir());
1893 assert!(filepath.exists());
1897 fn unicode_path_exists() {
1898 assert!(Path2::new(".").exists());
1899 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1901 let tmpdir = tmpdir();
1902 let unicode = tmpdir.path();
1903 let unicode = unicode.join(&format!("test-각丁ー再见"));
1904 check!(fs::create_dir(&unicode));
1905 assert!(unicode.exists());
1906 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1910 fn copy_file_does_not_exist() {
1911 let from = Path2::new("test/nonexistent-bogus-path");
1912 let to = Path2::new("test/other-bogus-path");
1914 match fs::copy(&from, &to) {
1917 assert!(!from.exists());
1918 assert!(!to.exists());
1924 fn copy_src_does_not_exist() {
1925 let tmpdir = tmpdir();
1926 let from = Path2::new("test/nonexistent-bogus-path");
1927 let to = tmpdir.join("out.txt");
1928 check!(check!(File::create(&to)).write(b"hello"));
1929 assert!(fs::copy(&from, &to).is_err());
1930 assert!(!from.exists());
1931 let mut v = Vec::new();
1932 check!(check!(File::open(&to)).read_to_end(&mut v));
1933 assert_eq!(v, b"hello");
1938 let tmpdir = tmpdir();
1939 let input = tmpdir.join("in.txt");
1940 let out = tmpdir.join("out.txt");
1942 check!(check!(File::create(&input)).write(b"hello"));
1943 check!(fs::copy(&input, &out));
1944 let mut v = Vec::new();
1945 check!(check!(File::open(&out)).read_to_end(&mut v));
1946 assert_eq!(v, b"hello");
1948 assert_eq!(check!(input.metadata()).permissions(),
1949 check!(out.metadata()).permissions());
1953 fn copy_file_dst_dir() {
1954 let tmpdir = tmpdir();
1955 let out = tmpdir.join("out");
1957 check!(File::create(&out));
1958 match fs::copy(&*out, tmpdir.path()) {
1959 Ok(..) => panic!(), Err(..) => {}
1964 fn copy_file_dst_exists() {
1965 let tmpdir = tmpdir();
1966 let input = tmpdir.join("in");
1967 let output = tmpdir.join("out");
1969 check!(check!(File::create(&input)).write("foo".as_bytes()));
1970 check!(check!(File::create(&output)).write("bar".as_bytes()));
1971 check!(fs::copy(&input, &output));
1973 let mut v = Vec::new();
1974 check!(check!(File::open(&output)).read_to_end(&mut v));
1975 assert_eq!(v, b"foo".to_vec());
1979 fn copy_file_src_dir() {
1980 let tmpdir = tmpdir();
1981 let out = tmpdir.join("out");
1983 match fs::copy(tmpdir.path(), &out) {
1984 Ok(..) => panic!(), Err(..) => {}
1986 assert!(!out.exists());
1990 fn copy_file_preserves_perm_bits() {
1991 let tmpdir = tmpdir();
1992 let input = tmpdir.join("in.txt");
1993 let out = tmpdir.join("out.txt");
1995 let attr = check!(check!(File::create(&input)).metadata());
1996 let mut p = attr.permissions();
1997 p.set_readonly(true);
1998 check!(fs::set_permissions(&input, p));
1999 check!(fs::copy(&input, &out));
2000 assert!(check!(out.metadata()).permissions().readonly());
2001 check!(fs::set_permissions(&input, attr.permissions()));
2002 check!(fs::set_permissions(&out, attr.permissions()));
2007 fn copy_file_preserves_streams() {
2009 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2010 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2011 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2012 let mut v = Vec::new();
2013 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2014 assert_eq!(v, b"carrot".to_vec());
2017 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
2019 fn symlinks_work() {
2020 let tmpdir = tmpdir();
2021 let input = tmpdir.join("in.txt");
2022 let out = tmpdir.join("out.txt");
2024 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2025 check!(fs::soft_link(&input, &out));
2026 // if cfg!(not(windows)) {
2027 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
2028 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
2030 assert_eq!(check!(fs::metadata(&out)).len(),
2031 check!(fs::metadata(&input)).len());
2032 let mut v = Vec::new();
2033 check!(check!(File::open(&out)).read_to_end(&mut v));
2034 assert_eq!(v, b"foobar".to_vec());
2037 #[cfg(not(windows))] // apparently windows doesn't like symlinks
2039 fn symlink_noexist() {
2040 let tmpdir = tmpdir();
2041 // symlinks can point to things that don't exist
2042 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
2043 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
2044 tmpdir.join("foo"));
2048 fn readlink_not_symlink() {
2049 let tmpdir = tmpdir();
2050 match fs::read_link(tmpdir.path()) {
2051 Ok(..) => panic!("wanted a failure"),
2058 let tmpdir = tmpdir();
2059 let input = tmpdir.join("in.txt");
2060 let out = tmpdir.join("out.txt");
2062 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2063 check!(fs::hard_link(&input, &out));
2064 assert_eq!(check!(fs::metadata(&out)).len(),
2065 check!(fs::metadata(&input)).len());
2066 assert_eq!(check!(fs::metadata(&out)).len(),
2067 check!(input.metadata()).len());
2068 let mut v = Vec::new();
2069 check!(check!(File::open(&out)).read_to_end(&mut v));
2070 assert_eq!(v, b"foobar".to_vec());
2072 // can't link to yourself
2073 match fs::hard_link(&input, &input) {
2074 Ok(..) => panic!("wanted a failure"),
2077 // can't link to something that doesn't exist
2078 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2079 Ok(..) => panic!("wanted a failure"),
2086 let tmpdir = tmpdir();
2087 let file = tmpdir.join("in.txt");
2089 check!(File::create(&file));
2090 let attr = check!(fs::metadata(&file));
2091 assert!(!attr.permissions().readonly());
2092 let mut p = attr.permissions();
2093 p.set_readonly(true);
2094 check!(fs::set_permissions(&file, p.clone()));
2095 let attr = check!(fs::metadata(&file));
2096 assert!(attr.permissions().readonly());
2098 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2099 Ok(..) => panic!("wanted an error"),
2103 p.set_readonly(false);
2104 check!(fs::set_permissions(&file, p));
2108 fn sync_doesnt_kill_anything() {
2109 let tmpdir = tmpdir();
2110 let path = tmpdir.join("in.txt");
2112 let mut file = check!(File::create(&path));
2113 check!(file.sync_all());
2114 check!(file.sync_data());
2115 check!(file.write(b"foo"));
2116 check!(file.sync_all());
2117 check!(file.sync_data());
2121 fn truncate_works() {
2122 let tmpdir = tmpdir();
2123 let path = tmpdir.join("in.txt");
2125 let mut file = check!(File::create(&path));
2126 check!(file.write(b"foo"));
2127 check!(file.sync_all());
2129 // Do some simple things with truncation
2130 assert_eq!(check!(file.metadata()).len(), 3);
2131 check!(file.set_len(10));
2132 assert_eq!(check!(file.metadata()).len(), 10);
2133 check!(file.write(b"bar"));
2134 check!(file.sync_all());
2135 assert_eq!(check!(file.metadata()).len(), 10);
2137 let mut v = Vec::new();
2138 check!(check!(File::open(&path)).read_to_end(&mut v));
2139 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2141 // Truncate to a smaller length, don't seek, and then write something.
2142 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2143 // past the end of the file).
2144 check!(file.set_len(2));
2145 assert_eq!(check!(file.metadata()).len(), 2);
2146 check!(file.write(b"wut"));
2147 check!(file.sync_all());
2148 assert_eq!(check!(file.metadata()).len(), 9);
2149 let mut v = Vec::new();
2150 check!(check!(File::open(&path)).read_to_end(&mut v));
2151 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2156 use fs::OpenOptions as OO;
2157 fn c<T: Clone>(t: &T) -> T { t.clone() }
2159 let tmpdir = tmpdir();
2161 let mut r = OO::new(); r.read(true);
2162 let mut w = OO::new(); w.write(true);
2163 let mut rw = OO::new(); rw.read(true).write(true);
2164 let mut a = OO::new(); a.append(true);
2165 let mut ra = OO::new(); ra.read(true).append(true);
2167 let invalid_options = if cfg!(windows) { "The parameter is incorrect" }
2168 else { "Invalid argument" };
2170 // Test various combinations of creation modes and access modes.
2173 // creation mode | read | write | read-write | append | read-append |
2174 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2175 // not set (open existing) | X | X | X | X | X |
2176 // create | | X | X | X | X |
2177 // truncate | | X | X | | |
2178 // create and truncate | | X | X | | |
2179 // create_new | | X | X | X | X |
2181 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2184 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2185 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2186 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2187 check!(c(&w).create(true).open(&tmpdir.join("a")));
2188 check!(c(&w).open(&tmpdir.join("a")));
2191 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2192 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2193 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2194 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2195 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2198 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2199 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2200 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2201 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2202 check!(c(&rw).open(&tmpdir.join("c")));
2205 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2206 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2207 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2208 check!(c(&a).create(true).open(&tmpdir.join("d")));
2209 check!(c(&a).open(&tmpdir.join("d")));
2212 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2213 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2214 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2215 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2216 check!(c(&ra).open(&tmpdir.join("e")));
2218 // Test opening a file without setting an access mode
2219 let mut blank = OO::new();
2220 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2223 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2225 // Test write fails for read-only
2226 check!(r.open(&tmpdir.join("h")));
2228 let mut f = check!(r.open(&tmpdir.join("h")));
2229 assert!(f.write("wut".as_bytes()).is_err());
2232 // Test write overwrites
2234 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2235 check!(f.write("baz".as_bytes()));
2238 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2239 let mut b = vec![0; 6];
2240 check!(f.read(&mut b));
2241 assert_eq!(b, "bazbar".as_bytes());
2244 // Test truncate works
2246 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2247 check!(f.write("foo".as_bytes()));
2249 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2251 // Test append works
2252 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2254 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2255 check!(f.write("bar".as_bytes()));
2257 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2259 // Test .append(true) equals .write(true).append(true)
2261 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2262 check!(f.write("baz".as_bytes()));
2264 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2268 fn _assert_send_sync() {
2269 fn _assert_send_sync<T: Send + Sync>() {}
2270 _assert_send_sync::<OpenOptions>();
2275 let mut bytes = [0; 1024];
2276 StdRng::new().unwrap().fill_bytes(&mut bytes);
2278 let tmpdir = tmpdir();
2280 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2281 let mut v = Vec::new();
2282 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2283 assert!(v == &bytes[..]);
2287 #[cfg(not(windows))]
2288 fn unlink_readonly() {
2289 let tmpdir = tmpdir();
2290 let path = tmpdir.join("file");
2291 check!(File::create(&path));
2292 let mut perm = check!(fs::metadata(&path)).permissions();
2293 perm.set_readonly(true);
2294 check!(fs::set_permissions(&path, perm));
2295 check!(fs::remove_file(&path));
2299 fn mkdir_trailing_slash() {
2300 let tmpdir = tmpdir();
2301 let path = tmpdir.join("file");
2302 check!(fs::create_dir_all(&path.join("a/")));
2306 fn canonicalize_works_simple() {
2307 let tmpdir = tmpdir();
2308 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2309 let file = tmpdir.join("test");
2310 File::create(&file).unwrap();
2311 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2315 #[cfg(not(windows))]
2316 fn realpath_works() {
2317 let tmpdir = tmpdir();
2318 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2319 let file = tmpdir.join("test");
2320 let dir = tmpdir.join("test2");
2321 let link = dir.join("link");
2322 let linkdir = tmpdir.join("test3");
2324 File::create(&file).unwrap();
2325 fs::create_dir(&dir).unwrap();
2326 fs::soft_link(&file, &link).unwrap();
2327 fs::soft_link(&dir, &linkdir).unwrap();
2329 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2331 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2332 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2333 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2334 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2335 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2339 #[cfg(not(windows))]
2340 fn realpath_works_tricky() {
2341 let tmpdir = tmpdir();
2342 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2344 let a = tmpdir.join("a");
2345 let b = a.join("b");
2346 let c = b.join("c");
2347 let d = a.join("d");
2348 let e = d.join("e");
2349 let f = a.join("f");
2351 fs::create_dir_all(&b).unwrap();
2352 fs::create_dir_all(&d).unwrap();
2353 File::create(&f).unwrap();
2354 fs::soft_link("../d/e", &c).unwrap();
2355 fs::soft_link("../f", &e).unwrap();
2357 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2358 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2362 fn dir_entry_methods() {
2363 let tmpdir = tmpdir();
2365 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2366 File::create(&tmpdir.join("b")).unwrap();
2368 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2369 let fname = file.file_name();
2370 match fname.to_str() {
2372 assert!(file.file_type().unwrap().is_dir());
2373 assert!(file.metadata().unwrap().is_dir());
2376 assert!(file.file_type().unwrap().is_file());
2377 assert!(file.metadata().unwrap().is_file());
2379 f => panic!("unknown file name: {:?}", f),
2385 fn read_dir_not_found() {
2386 let res = fs::read_dir("/path/that/does/not/exist");
2387 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);