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")]
63 pub struct Metadata(fs_imp::FileAttr);
65 /// Iterator over the entries in a directory.
67 /// This iterator is returned from the `read_dir` function of this module and
68 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
69 /// information like the entry's path and possibly other metadata can be
74 /// This `io::Result` will be an `Err` if there's some sort of intermittent
75 /// IO error during iteration.
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct ReadDir(fs_imp::ReadDir);
79 /// Entries returned by the `ReadDir` iterator.
81 /// An instance of `DirEntry` represents an entry inside of a directory on the
82 /// filesystem. Each entry can be inspected via methods to learn about the full
83 /// path or possibly other metadata through per-platform extension traits.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct DirEntry(fs_imp::DirEntry);
87 /// An iterator that recursively walks over the contents of a directory.
88 #[unstable(feature = "fs_walk",
89 reason = "the precise semantics and defaults for a recursive walk \
90 may change and this may end up accounting for files such \
91 as symlinks differently",
95 stack: Vec<io::Result<ReadDir>>,
98 /// Options and flags which can be used to configure how a file is opened.
100 /// This builder exposes the ability to configure how a `File` is opened and
101 /// what operations are permitted on the open file. The `File::open` and
102 /// `File::create` methods are aliases for commonly used options using this
105 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
106 /// then chain calls to methods to set each option, then call `open()`, passing
107 /// the path of the file you're trying to open. This will give you a
108 /// [`io::Result`][result] with a [`File`][file] inside that you can further
111 /// [result]: ../io/type.Result.html
112 /// [file]: struct.File.html
116 /// Opening a file to read:
119 /// use std::fs::OpenOptions;
121 /// let file = OpenOptions::new().read(true).open("foo.txt");
124 /// Opening a file for both reading and writing, as well as creating it if it
128 /// use std::fs::OpenOptions;
130 /// let file = OpenOptions::new()
134 /// .open("foo.txt");
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub struct OpenOptions(fs_imp::OpenOptions);
140 /// Representation of the various permissions on a file.
142 /// This module only currently provides one bit of information, `readonly`,
143 /// which is exposed on all currently supported platforms. Unix-specific
144 /// functionality, such as mode bits, is available through the
145 /// `os::unix::PermissionsExt` trait.
146 #[derive(Clone, PartialEq, Eq, Debug)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct Permissions(fs_imp::FilePermissions);
150 /// An structure representing a type of file with accessors for each file type.
151 #[stable(feature = "file_type", since = "1.1.0")]
152 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
153 pub struct FileType(fs_imp::FileType);
155 /// A builder used to create directories in various manners.
157 /// This builder also supports platform-specific options.
158 #[unstable(feature = "dir_builder", reason = "recently added API",
160 pub struct DirBuilder {
161 inner: fs_imp::DirBuilder,
166 /// Attempts to open a file in read-only mode.
168 /// See the `OpenOptions::open` method for more details.
172 /// This function will return an error if `path` does not already exist.
173 /// Other errors may also be returned according to `OpenOptions::open`.
178 /// use std::fs::File;
180 /// # fn foo() -> std::io::Result<()> {
181 /// let mut f = try!(File::open("foo.txt"));
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
187 OpenOptions::new().read(true).open(path)
190 /// Opens a file in write-only mode.
192 /// This function will create a file if it does not exist,
193 /// and will truncate it if it does.
195 /// See the `OpenOptions::open` function for more details.
200 /// use std::fs::File;
202 /// # fn foo() -> std::io::Result<()> {
203 /// let mut f = try!(File::create("foo.txt"));
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
209 OpenOptions::new().write(true).create(true).truncate(true).open(path)
212 /// Attempts to sync all OS-internal metadata to disk.
214 /// This function will attempt to ensure that all in-core data reaches the
215 /// filesystem before returning.
220 /// use std::fs::File;
221 /// use std::io::prelude::*;
223 /// # fn foo() -> std::io::Result<()> {
224 /// let mut f = try!(File::create("foo.txt"));
225 /// try!(f.write_all(b"Hello, world!"));
227 /// try!(f.sync_all());
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn sync_all(&self) -> io::Result<()> {
236 /// This function is similar to `sync_all`, except that it may not
237 /// synchronize file metadata to the filesystem.
239 /// This is intended for use cases that must synchronize content, but don't
240 /// need the metadata on disk. The goal of this method is to reduce disk
243 /// Note that some platforms may simply implement this in terms of
249 /// use std::fs::File;
250 /// use std::io::prelude::*;
252 /// # fn foo() -> std::io::Result<()> {
253 /// let mut f = try!(File::create("foo.txt"));
254 /// try!(f.write_all(b"Hello, world!"));
256 /// try!(f.sync_data());
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn sync_data(&self) -> io::Result<()> {
262 self.inner.datasync()
265 /// Truncates or extends the underlying file, updating the size of
266 /// this file to become `size`.
268 /// If the `size` is less than the current file's size, then the file will
269 /// be shrunk. If it is greater than the current file's size, then the file
270 /// will be extended to `size` and have all of the intermediate data filled
275 /// This function will return an error if the file is not opened for writing.
280 /// use std::fs::File;
282 /// # fn foo() -> std::io::Result<()> {
283 /// let mut f = try!(File::create("foo.txt"));
284 /// try!(f.set_len(10));
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn set_len(&self, size: u64) -> io::Result<()> {
290 self.inner.truncate(size)
293 /// Queries metadata about the underlying file.
298 /// use std::fs::File;
300 /// # fn foo() -> std::io::Result<()> {
301 /// let mut f = try!(File::open("foo.txt"));
302 /// let metadata = try!(f.metadata());
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn metadata(&self) -> io::Result<Metadata> {
308 self.inner.file_attr().map(Metadata)
312 impl AsInner<fs_imp::File> for File {
313 fn as_inner(&self) -> &fs_imp::File { &self.inner }
315 impl FromInner<fs_imp::File> for File {
316 fn from_inner(f: fs_imp::File) -> File {
320 impl IntoInner<fs_imp::File> for File {
321 fn into_inner(self) -> fs_imp::File {
326 impl fmt::Debug for File {
327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
332 #[stable(feature = "rust1", since = "1.0.0")]
334 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
337 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
338 unsafe { read_to_end_uninitialized(self, buf) }
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl Write for File {
343 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
344 self.inner.write(buf)
346 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
348 #[stable(feature = "rust1", since = "1.0.0")]
350 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<'a> Read for &'a File {
356 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<'a> Write for &'a File {
362 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
363 self.inner.write(buf)
365 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<'a> Seek for &'a File {
369 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
375 /// Creates a blank net set of options ready for configuration.
377 /// All options are initially set to `false`.
382 /// use std::fs::OpenOptions;
384 /// let file = OpenOptions::new().open("foo.txt");
386 #[stable(feature = "rust1", since = "1.0.0")]
387 pub fn new() -> OpenOptions {
388 OpenOptions(fs_imp::OpenOptions::new())
391 /// Sets the option for read access.
393 /// This option, when true, will indicate that the file should be
394 /// `read`-able if opened.
399 /// use std::fs::OpenOptions;
401 /// let file = OpenOptions::new().read(true).open("foo.txt");
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
405 self.0.read(read); self
408 /// Sets the option for write access.
410 /// This option, when true, will indicate that the file should be
411 /// `write`-able if opened.
416 /// use std::fs::OpenOptions;
418 /// let file = OpenOptions::new().write(true).open("foo.txt");
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
422 self.0.write(write); self
425 /// Sets the option for the append mode.
427 /// This option, when true, means that writes will append to a file instead
428 /// of overwriting previous contents.
433 /// use std::fs::OpenOptions;
435 /// let file = OpenOptions::new().write(true).append(true).open("foo.txt");
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
439 self.0.append(append); self
442 /// Sets the option for truncating a previous file.
444 /// If a file is successfully opened with this option set it will truncate
445 /// the file to 0 length if it already exists.
450 /// use std::fs::OpenOptions;
452 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
456 self.0.truncate(truncate); self
459 /// Sets the option for creating a new file.
461 /// This option indicates whether a new file will be created if the file
462 /// does not yet already exist.
467 /// use std::fs::OpenOptions;
469 /// let file = OpenOptions::new().create(true).open("foo.txt");
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
473 self.0.create(create); self
476 /// Opens a file at `path` with the options specified by `self`.
480 /// This function will return an error under a number of different
481 /// circumstances, to include but not limited to:
483 /// * Opening a file that does not exist with read access.
484 /// * Attempting to open a file with access that the user lacks
486 /// * Filesystem-level errors (full disk, etc)
491 /// use std::fs::OpenOptions;
493 /// let file = OpenOptions::new().open("foo.txt");
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
497 let path = path.as_ref();
498 let inner = try!(fs_imp::File::open(path, &self.0));
499 Ok(File { inner: inner })
503 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
504 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
508 /// Returns the file type for this metadata.
509 #[stable(feature = "file_type", since = "1.1.0")]
510 pub fn file_type(&self) -> FileType {
511 FileType(self.0.file_type())
514 /// Returns whether this metadata is for a directory.
519 /// # fn foo() -> std::io::Result<()> {
522 /// let metadata = try!(fs::metadata("foo.txt"));
524 /// assert!(!metadata.is_dir());
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
531 /// Returns whether this metadata is for a regular file.
536 /// # fn foo() -> std::io::Result<()> {
539 /// let metadata = try!(fs::metadata("foo.txt"));
541 /// assert!(metadata.is_file());
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn is_file(&self) -> bool { self.file_type().is_file() }
548 /// Returns the size of the file, in bytes, this metadata is for.
553 /// # fn foo() -> std::io::Result<()> {
556 /// let metadata = try!(fs::metadata("foo.txt"));
558 /// assert_eq!(0, metadata.len());
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub fn len(&self) -> u64 { self.0.size() }
565 /// Returns the permissions of the file this metadata is for.
570 /// # fn foo() -> std::io::Result<()> {
573 /// let metadata = try!(fs::metadata("foo.txt"));
575 /// assert!(!metadata.permissions().readonly());
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn permissions(&self) -> Permissions {
581 Permissions(self.0.perm())
585 impl AsInner<fs_imp::FileAttr> for Metadata {
586 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
590 /// Returns whether these permissions describe a readonly file.
595 /// use std::fs::File;
597 /// # fn foo() -> std::io::Result<()> {
598 /// let mut f = try!(File::create("foo.txt"));
599 /// let metadata = try!(f.metadata());
601 /// assert_eq!(false, metadata.permissions().readonly());
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn readonly(&self) -> bool { self.0.readonly() }
608 /// Modifies the readonly flag for this set of permissions.
610 /// This operation does **not** modify the filesystem. To modify the
611 /// filesystem use the `fs::set_permissions` function.
616 /// use std::fs::File;
618 /// # fn foo() -> std::io::Result<()> {
619 /// let f = try!(File::create("foo.txt"));
620 /// let metadata = try!(f.metadata());
621 /// let mut permissions = metadata.permissions();
623 /// permissions.set_readonly(true);
625 /// // filesystem doesn't change
626 /// assert_eq!(false, metadata.permissions().readonly());
628 /// // just this particular `permissions`.
629 /// assert_eq!(true, permissions.readonly());
633 #[stable(feature = "rust1", since = "1.0.0")]
634 pub fn set_readonly(&mut self, readonly: bool) {
635 self.0.set_readonly(readonly)
640 /// Test whether this file type represents a directory.
641 #[stable(feature = "file_type", since = "1.1.0")]
642 pub fn is_dir(&self) -> bool { self.0.is_dir() }
644 /// Test whether this file type represents a regular file.
645 #[stable(feature = "file_type", since = "1.1.0")]
646 pub fn is_file(&self) -> bool { self.0.is_file() }
648 /// Test whether this file type represents a symbolic link.
649 #[stable(feature = "file_type", since = "1.1.0")]
650 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
653 impl AsInner<fs_imp::FileType> for FileType {
654 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
657 impl FromInner<fs_imp::FilePermissions> for Permissions {
658 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
663 impl AsInner<fs_imp::FilePermissions> for Permissions {
664 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl Iterator for ReadDir {
669 type Item = io::Result<DirEntry>;
671 fn next(&mut self) -> Option<io::Result<DirEntry>> {
672 self.0.next().map(|entry| entry.map(DirEntry))
676 #[stable(feature = "rust1", since = "1.0.0")]
678 /// Returns the full path to the file that this entry represents.
680 /// The full path is created by joining the original path to `read_dir` or
681 /// `walk_dir` with the filename of this entry.
687 /// # fn foo() -> std::io::Result<()> {
688 /// for entry in try!(fs::read_dir(".")) {
689 /// let dir = try!(entry);
690 /// println!("{:?}", dir.path());
696 /// This prints output like:
701 /// "./hello_world.rs"
704 /// The exact text, of course, depends on what files you have in `.`.
705 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn path(&self) -> PathBuf { self.0.path() }
708 /// Return the metadata for the file that this entry points at.
710 /// This function will not traverse symlinks if this entry points at a
713 /// # Platform behavior
715 /// On Windows this function is cheap to call (no extra system calls
716 /// needed), but on Unix platforms this function is the equivalent of
717 /// calling `symlink_metadata` on the path.
718 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
719 pub fn metadata(&self) -> io::Result<Metadata> {
720 self.0.metadata().map(Metadata)
723 /// Return the file type for the file that this entry points at.
725 /// This function will not traverse symlinks if this entry points at a
728 /// # Platform behavior
730 /// On Windows and most Unix platforms this function is free (no extra
731 /// system calls needed), but some Unix platforms may require the equivalent
732 /// call to `symlink_metadata` to learn about the target file type.
733 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
734 pub fn file_type(&self) -> io::Result<FileType> {
735 self.0.file_type().map(FileType)
738 /// Returns the bare file name of this directory entry without any other
739 /// leading path component.
740 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
741 pub fn file_name(&self) -> OsString {
746 impl AsInner<fs_imp::DirEntry> for DirEntry {
747 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
750 /// Removes a file from the filesystem.
752 /// Note that there is no
753 /// guarantee that the file is immediately deleted (e.g. depending on
754 /// platform, other open file descriptors may prevent immediate removal).
758 /// This function will return an error if `path` points to a directory, if the
759 /// user lacks permissions to remove the file, or if some other filesystem-level
767 /// # fn foo() -> std::io::Result<()> {
768 /// try!(fs::remove_file("a.txt"));
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
774 fs_imp::unlink(path.as_ref())
777 /// Given a path, query the file system to get information about a file,
780 /// This function will traverse symbolic links to query information about the
781 /// destination file.
786 /// # fn foo() -> std::io::Result<()> {
789 /// let attr = try!(fs::metadata("/some/file/path.txt"));
790 /// // inspect attr ...
797 /// This function will return an error if the user lacks the requisite
798 /// permissions to perform a `metadata` call on the given `path` or if there
799 /// is no entry in the filesystem at the provided path.
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
802 fs_imp::stat(path.as_ref()).map(Metadata)
805 /// Query the metadata about a file without following symlinks.
810 /// # fn foo() -> std::io::Result<()> {
813 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
814 /// // inspect attr ...
818 #[stable(feature = "symlink_metadata", since = "1.1.0")]
819 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
820 fs_imp::lstat(path.as_ref()).map(Metadata)
823 /// Rename a file or directory to a new name.
825 /// This will not work if the new name is on a different mount point.
829 /// This function will return an error if the provided `from` doesn't exist, if
830 /// the process lacks permissions to view the contents, if `from` and `to`
831 /// reside on separate filesystems, or if some other intermittent I/O error
839 /// # fn foo() -> std::io::Result<()> {
840 /// try!(fs::rename("a.txt", "b.txt"));
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
846 fs_imp::rename(from.as_ref(), to.as_ref())
849 /// Copies the contents of one file to another. This function will also
850 /// copy the permission bits of the original file to the destination file.
852 /// This function will **overwrite** the contents of `to`.
854 /// Note that if `from` and `to` both point to the same file, then the file
855 /// will likely get truncated by this operation.
857 /// On success, the total number of bytes copied is returned.
861 /// This function will return an error in the following situations, but is not
862 /// limited to just these cases:
864 /// * The `from` path is not a file
865 /// * The `from` file does not exist
866 /// * The current process does not have the permission rights to access
867 /// `from` or write `to`
874 /// # fn foo() -> std::io::Result<()> {
875 /// try!(fs::copy("foo.txt", "bar.txt"));
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
880 fs_imp::copy(from.as_ref(), to.as_ref())
883 /// Creates a new hard link on the filesystem.
885 /// The `dst` path will be a link pointing to the `src` path. Note that systems
886 /// often require these two paths to both be located on the same filesystem.
893 /// # fn foo() -> std::io::Result<()> {
894 /// try!(fs::hard_link("a.txt", "b.txt"));
898 #[stable(feature = "rust1", since = "1.0.0")]
899 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
900 fs_imp::link(src.as_ref(), dst.as_ref())
903 /// Creates a new symbolic link on the filesystem.
905 /// The `dst` path will be a symbolic link pointing to the `src` path.
906 /// On Windows, this will be a file symlink, not a directory symlink;
907 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
908 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
909 /// used instead to make the intent explicit.
916 /// # fn foo() -> std::io::Result<()> {
917 /// try!(fs::soft_link("a.txt", "b.txt"));
921 #[deprecated(since = "1.1.0",
922 reason = "replaced with std::os::unix::fs::symlink and \
923 std::os::windows::fs::{symlink_file, symlink_dir}")]
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
926 fs_imp::symlink(src.as_ref(), dst.as_ref())
929 /// Reads a symbolic link, returning the file that the link points to.
933 /// This function will return an error on failure. Failure conditions include
934 /// reading a file that does not exist or reading a file that is not a symbolic
942 /// # fn foo() -> std::io::Result<()> {
943 /// let path = try!(fs::read_link("a.txt"));
947 #[stable(feature = "rust1", since = "1.0.0")]
948 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
949 fs_imp::readlink(path.as_ref())
952 /// Returns the canonical form of a path with all intermediate components
953 /// normalized and symbolic links resolved.
954 #[unstable(feature = "fs_canonicalize", reason = "recently added API",
956 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
957 fs_imp::canonicalize(path.as_ref())
960 /// Creates a new, empty directory at the provided path
964 /// This function will return an error if the user lacks permissions to make a
965 /// new directory at the provided `path`, or if the directory already exists.
972 /// # fn foo() -> std::io::Result<()> {
973 /// try!(fs::create_dir("/some/dir"));
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
979 DirBuilder::new().create(path.as_ref())
982 /// Recursively create a directory and all of its parent components if they
987 /// This function will fail if any directory in the path specified by `path`
988 /// does not already exist and it could not be created otherwise. The specific
989 /// error conditions for when a directory is being created (after it is
990 /// determined to not exist) are outlined by `fs::create_dir`.
997 /// # fn foo() -> std::io::Result<()> {
998 /// try!(fs::create_dir_all("/some/dir"));
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1004 DirBuilder::new().recursive(true).create(path.as_ref())
1007 /// Removes an existing, empty directory.
1011 /// This function will return an error if the user lacks permissions to remove
1012 /// the directory at the provided `path`, or if the directory isn't empty.
1019 /// # fn foo() -> std::io::Result<()> {
1020 /// try!(fs::remove_dir("/some/dir"));
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1026 fs_imp::rmdir(path.as_ref())
1029 /// Removes a directory at this path, after removing all its contents. Use
1032 /// This function does **not** follow symbolic links and it will simply remove the
1033 /// symbolic link itself.
1037 /// See `file::remove_file` and `fs::remove_dir`.
1044 /// # fn foo() -> std::io::Result<()> {
1045 /// try!(fs::remove_dir_all("/some/dir"));
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1051 let path = path.as_ref();
1052 for child in try!(read_dir(path)) {
1053 let child = try!(child).path();
1054 let stat = try!(symlink_metadata(&*child));
1056 try!(remove_dir_all(&*child));
1058 try!(remove_file(&*child));
1064 /// Returns an iterator over the entries within a directory.
1066 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1067 /// be encountered after an iterator is initially constructed.
1073 /// use std::fs::{self, DirEntry};
1074 /// use std::path::Path;
1076 /// // one possible implementation of fs::walk_dir only visiting files
1077 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1078 /// if try!(fs::metadata(dir)).is_dir() {
1079 /// for entry in try!(fs::read_dir(dir)) {
1080 /// let entry = try!(entry);
1081 /// if try!(fs::metadata(entry.path())).is_dir() {
1082 /// try!(visit_dirs(&entry.path(), cb));
1094 /// This function will return an error if the provided `path` doesn't exist, if
1095 /// the process lacks permissions to view the contents or if the `path` points
1096 /// at a non-directory file
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1099 fs_imp::readdir(path.as_ref()).map(ReadDir)
1102 /// Returns an iterator that will recursively walk the directory structure
1103 /// rooted at `path`.
1105 /// The path given will not be iterated over, and this will perform iteration in
1106 /// some top-down order. The contents of unreadable subdirectories are ignored.
1108 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1109 /// be encountered after an iterator is initially constructed.
1110 #[unstable(feature = "fs_walk",
1111 reason = "the precise semantics and defaults for a recursive walk \
1112 may change and this may end up accounting for files such \
1113 as symlinks differently",
1115 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1116 let start = try!(read_dir(path));
1117 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1120 #[unstable(feature = "fs_walk", issue = "27707")]
1121 impl Iterator for WalkDir {
1122 type Item = io::Result<DirEntry>;
1124 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1126 if let Some(ref mut cur) = self.cur {
1128 Some(Err(e)) => return Some(Err(e)),
1130 let path = next.path();
1132 self.stack.push(read_dir(&*path));
1134 return Some(Ok(next))
1140 match self.stack.pop() {
1141 Some(Err(e)) => return Some(Err(e)),
1142 Some(Ok(next)) => self.cur = Some(next),
1143 None => return None,
1149 /// Utility methods for paths.
1150 #[unstable(feature = "path_ext",
1151 reason = "The precise set of methods exposed on this trait may \
1152 change and some methods may be removed. For stable code, \
1153 see the std::fs::metadata function.",
1156 /// Gets information on the file, directory, etc at this path.
1158 /// Consult the `fs::metadata` documentation for more info.
1160 /// This call preserves identical runtime/error semantics with
1162 fn metadata(&self) -> io::Result<Metadata>;
1164 /// Gets information on the file, directory, etc at this path.
1166 /// Consult the `fs::symlink_metadata` documentation for more info.
1168 /// This call preserves identical runtime/error semantics with
1169 /// `fs::symlink_metadata`.
1170 fn symlink_metadata(&self) -> io::Result<Metadata>;
1172 /// Returns the canonical form of a path, normalizing all components and
1173 /// eliminate all symlinks.
1175 /// This call preserves identical runtime/error semantics with
1176 /// `fs::canonicalize`.
1177 fn canonicalize(&self) -> io::Result<PathBuf>;
1179 /// Reads the symlink at this path.
1181 /// For more information see `fs::read_link`.
1182 fn read_link(&self) -> io::Result<PathBuf>;
1184 /// Reads the directory at this path.
1186 /// For more information see `fs::read_dir`.
1187 fn read_dir(&self) -> io::Result<ReadDir>;
1189 /// Boolean value indicator whether the underlying file exists on the local
1190 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1191 fn exists(&self) -> bool;
1193 /// Whether the underlying implementation (be it a file path, or something
1194 /// else) points at a "regular file" on the FS. Will return false for paths
1195 /// to non-existent locations or directories or other non-regular files
1196 /// (named pipes, etc). Follows links when making this determination.
1197 fn is_file(&self) -> bool;
1199 /// Whether the underlying implementation (be it a file path, or something
1200 /// else) is pointing at a directory in the underlying FS. Will return
1201 /// false for paths to non-existent locations or if the item is not a
1202 /// directory (eg files, named pipes, etc). Follows links when making this
1204 fn is_dir(&self) -> bool;
1207 impl PathExt for Path {
1208 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1209 fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1210 fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1211 fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1212 fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1213 fn exists(&self) -> bool { metadata(self).is_ok() }
1215 fn is_file(&self) -> bool {
1216 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1219 fn is_dir(&self) -> bool {
1220 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1224 /// Changes the permissions found on a file or a directory.
1229 /// # fn foo() -> std::io::Result<()> {
1232 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1233 /// perms.set_readonly(true);
1234 /// try!(fs::set_permissions("foo.txt", perms));
1241 /// This function will return an error if the provided `path` doesn't exist, if
1242 /// the process lacks permissions to change the attributes of the file, or if
1243 /// some other I/O error is encountered.
1244 #[stable(feature = "set_permissions", since = "1.1.0")]
1245 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1247 fs_imp::set_perm(path.as_ref(), perm.0)
1250 #[unstable(feature = "dir_builder", reason = "recently added API",
1253 /// Creates a new set of options with default mode/security settings for all
1254 /// platforms and also non-recursive.
1255 pub fn new() -> DirBuilder {
1257 inner: fs_imp::DirBuilder::new(),
1262 /// Indicate that directories create should be created recursively, creating
1263 /// all parent directories if they do not exist with the same security and
1264 /// permissions settings.
1266 /// This option defaults to `false`
1267 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1268 self.recursive = recursive;
1272 /// Create the specified directory with the options configured in this
1274 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1275 let path = path.as_ref();
1277 self.create_dir_all(path)
1279 self.inner.mkdir(path)
1283 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1284 if path == Path::new("") || path.is_dir() { return Ok(()) }
1285 if let Some(p) = path.parent() {
1286 try!(self.create_dir_all(p))
1288 self.inner.mkdir(path)
1292 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1293 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1300 #![allow(deprecated)] //rand
1306 use fs::{self, File, OpenOptions};
1307 use io::{ErrorKind, SeekFrom};
1309 use path::Path as Path2;
1311 use rand::{self, StdRng, Rng};
1314 macro_rules! check { ($e:expr) => (
1317 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1321 macro_rules! error { ($e:expr, $s:expr) => (
1323 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1324 Err(ref err) => assert!(err.to_string().contains($s),
1325 format!("`{}` did not contain `{}`", err, $s))
1329 pub struct TempDir(PathBuf);
1332 fn join(&self, path: &str) -> PathBuf {
1333 let TempDir(ref p) = *self;
1337 fn path<'a>(&'a self) -> &'a Path2 {
1338 let TempDir(ref p) = *self;
1343 impl Drop for TempDir {
1344 fn drop(&mut self) {
1345 // Gee, seeing how we're testing the fs module I sure hope that we
1346 // at least implement this correctly!
1347 let TempDir(ref p) = *self;
1348 check!(fs::remove_dir_all(p));
1352 pub fn tmpdir() -> TempDir {
1353 let p = env::temp_dir();
1354 let mut r = rand::thread_rng();
1355 let ret = p.join(&format!("rust-{}", r.next_u32()));
1356 check!(fs::create_dir(&ret));
1361 fn file_test_io_smoke_test() {
1362 let message = "it's alright. have a good time";
1363 let tmpdir = tmpdir();
1364 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1366 let mut write_stream = check!(File::create(filename));
1367 check!(write_stream.write(message.as_bytes()));
1370 let mut read_stream = check!(File::open(filename));
1371 let mut read_buf = [0; 1028];
1372 let read_str = match check!(read_stream.read(&mut read_buf)) {
1373 0 => panic!("shouldn't happen"),
1374 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1376 assert_eq!(read_str, message);
1378 check!(fs::remove_file(filename));
1382 fn invalid_path_raises() {
1383 let tmpdir = tmpdir();
1384 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1385 let result = File::open(filename);
1388 error!(result, "o such file or directory");
1390 // error!(result, "couldn't open path as file");
1391 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1395 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1396 let tmpdir = tmpdir();
1397 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1399 let result = fs::remove_file(filename);
1402 error!(result, "o such file or directory");
1404 // error!(result, "couldn't unlink path");
1405 // error!(result, format!("path={}", filename.display()));
1409 fn file_test_io_non_positional_read() {
1410 let message: &str = "ten-four";
1411 let mut read_mem = [0; 8];
1412 let tmpdir = tmpdir();
1413 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1415 let mut rw_stream = check!(File::create(filename));
1416 check!(rw_stream.write(message.as_bytes()));
1419 let mut read_stream = check!(File::open(filename));
1421 let read_buf = &mut read_mem[0..4];
1422 check!(read_stream.read(read_buf));
1425 let read_buf = &mut read_mem[4..8];
1426 check!(read_stream.read(read_buf));
1429 check!(fs::remove_file(filename));
1430 let read_str = str::from_utf8(&read_mem).unwrap();
1431 assert_eq!(read_str, message);
1435 fn file_test_io_seek_and_tell_smoke_test() {
1436 let message = "ten-four";
1437 let mut read_mem = [0; 4];
1438 let set_cursor = 4 as u64;
1439 let mut tell_pos_pre_read;
1440 let mut tell_pos_post_read;
1441 let tmpdir = tmpdir();
1442 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1444 let mut rw_stream = check!(File::create(filename));
1445 check!(rw_stream.write(message.as_bytes()));
1448 let mut read_stream = check!(File::open(filename));
1449 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1450 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1451 check!(read_stream.read(&mut read_mem));
1452 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1454 check!(fs::remove_file(filename));
1455 let read_str = str::from_utf8(&read_mem).unwrap();
1456 assert_eq!(read_str, &message[4..8]);
1457 assert_eq!(tell_pos_pre_read, set_cursor);
1458 assert_eq!(tell_pos_post_read, message.len() as u64);
1462 fn file_test_io_seek_and_write() {
1463 let initial_msg = "food-is-yummy";
1464 let overwrite_msg = "-the-bar!!";
1465 let final_msg = "foo-the-bar!!";
1467 let mut read_mem = [0; 13];
1468 let tmpdir = tmpdir();
1469 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1471 let mut rw_stream = check!(File::create(filename));
1472 check!(rw_stream.write(initial_msg.as_bytes()));
1473 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1474 check!(rw_stream.write(overwrite_msg.as_bytes()));
1477 let mut read_stream = check!(File::open(filename));
1478 check!(read_stream.read(&mut read_mem));
1480 check!(fs::remove_file(filename));
1481 let read_str = str::from_utf8(&read_mem).unwrap();
1482 assert!(read_str == final_msg);
1486 fn file_test_io_seek_shakedown() {
1488 let initial_msg = "qwer-asdf-zxcv";
1489 let chunk_one: &str = "qwer";
1490 let chunk_two: &str = "asdf";
1491 let chunk_three: &str = "zxcv";
1492 let mut read_mem = [0; 4];
1493 let tmpdir = tmpdir();
1494 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1496 let mut rw_stream = check!(File::create(filename));
1497 check!(rw_stream.write(initial_msg.as_bytes()));
1500 let mut read_stream = check!(File::open(filename));
1502 check!(read_stream.seek(SeekFrom::End(-4)));
1503 check!(read_stream.read(&mut read_mem));
1504 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1506 check!(read_stream.seek(SeekFrom::Current(-9)));
1507 check!(read_stream.read(&mut read_mem));
1508 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1510 check!(read_stream.seek(SeekFrom::Start(0)));
1511 check!(read_stream.read(&mut read_mem));
1512 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1514 check!(fs::remove_file(filename));
1518 fn file_test_stat_is_correct_on_is_file() {
1519 let tmpdir = tmpdir();
1520 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1522 let mut opts = OpenOptions::new();
1523 let mut fs = check!(opts.read(true).write(true)
1524 .create(true).open(filename));
1526 fs.write(msg.as_bytes()).unwrap();
1528 let fstat_res = check!(fs.metadata());
1529 assert!(fstat_res.is_file());
1531 let stat_res_fn = check!(fs::metadata(filename));
1532 assert!(stat_res_fn.is_file());
1533 let stat_res_meth = check!(filename.metadata());
1534 assert!(stat_res_meth.is_file());
1535 check!(fs::remove_file(filename));
1539 fn file_test_stat_is_correct_on_is_dir() {
1540 let tmpdir = tmpdir();
1541 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1542 check!(fs::create_dir(filename));
1543 let stat_res_fn = check!(fs::metadata(filename));
1544 assert!(stat_res_fn.is_dir());
1545 let stat_res_meth = check!(filename.metadata());
1546 assert!(stat_res_meth.is_dir());
1547 check!(fs::remove_dir(filename));
1551 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1552 let tmpdir = tmpdir();
1553 let dir = &tmpdir.join("fileinfo_false_on_dir");
1554 check!(fs::create_dir(dir));
1555 assert!(dir.is_file() == false);
1556 check!(fs::remove_dir(dir));
1560 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1561 let tmpdir = tmpdir();
1562 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1563 check!(check!(File::create(file)).write(b"foo"));
1564 assert!(file.exists());
1565 check!(fs::remove_file(file));
1566 assert!(!file.exists());
1570 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1571 let tmpdir = tmpdir();
1572 let dir = &tmpdir.join("before_and_after_dir");
1573 assert!(!dir.exists());
1574 check!(fs::create_dir(dir));
1575 assert!(dir.exists());
1576 assert!(dir.is_dir());
1577 check!(fs::remove_dir(dir));
1578 assert!(!dir.exists());
1582 fn file_test_directoryinfo_readdir() {
1583 let tmpdir = tmpdir();
1584 let dir = &tmpdir.join("di_readdir");
1585 check!(fs::create_dir(dir));
1588 let f = dir.join(&format!("{}.txt", n));
1589 let mut w = check!(File::create(&f));
1590 let msg_str = format!("{}{}", prefix, n.to_string());
1591 let msg = msg_str.as_bytes();
1592 check!(w.write(msg));
1594 let files = check!(fs::read_dir(dir));
1595 let mut mem = [0; 4];
1597 let f = f.unwrap().path();
1599 let n = f.file_stem().unwrap();
1600 check!(check!(File::open(&f)).read(&mut mem));
1601 let read_str = str::from_utf8(&mem).unwrap();
1602 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1603 assert_eq!(expected, read_str);
1605 check!(fs::remove_file(&f));
1607 check!(fs::remove_dir(dir));
1611 fn file_test_walk_dir() {
1612 let tmpdir = tmpdir();
1613 let dir = &tmpdir.join("walk_dir");
1614 check!(fs::create_dir(dir));
1616 let dir1 = &dir.join("01/02/03");
1617 check!(fs::create_dir_all(dir1));
1618 check!(File::create(&dir1.join("04")));
1620 let dir2 = &dir.join("11/12/13");
1621 check!(fs::create_dir_all(dir2));
1622 check!(File::create(&dir2.join("14")));
1624 let files = check!(fs::walk_dir(dir));
1625 let mut cur = [0; 2];
1627 let f = f.unwrap().path();
1628 let stem = f.file_stem().unwrap().to_str().unwrap();
1629 let root = stem.as_bytes()[0] - b'0';
1630 let name = stem.as_bytes()[1] - b'0';
1631 assert!(cur[root as usize] < name);
1632 cur[root as usize] = name;
1635 check!(fs::remove_dir_all(dir));
1639 fn mkdir_path_already_exists_error() {
1640 let tmpdir = tmpdir();
1641 let dir = &tmpdir.join("mkdir_error_twice");
1642 check!(fs::create_dir(dir));
1643 let e = fs::create_dir(dir).err().unwrap();
1644 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1648 fn recursive_mkdir() {
1649 let tmpdir = tmpdir();
1650 let dir = tmpdir.join("d1/d2");
1651 check!(fs::create_dir_all(&dir));
1652 assert!(dir.is_dir())
1656 fn recursive_mkdir_failure() {
1657 let tmpdir = tmpdir();
1658 let dir = tmpdir.join("d1");
1659 let file = dir.join("f1");
1661 check!(fs::create_dir_all(&dir));
1662 check!(File::create(&file));
1664 let result = fs::create_dir_all(&file);
1666 assert!(result.is_err());
1667 // error!(result, "couldn't recursively mkdir");
1668 // error!(result, "couldn't create directory");
1669 // error!(result, "mode=0700");
1670 // error!(result, format!("path={}", file.display()));
1674 fn recursive_mkdir_slash() {
1675 check!(fs::create_dir_all(&Path2::new("/")));
1678 // FIXME(#12795) depends on lstat to work on windows
1679 #[cfg(not(windows))]
1681 fn recursive_rmdir() {
1682 let tmpdir = tmpdir();
1683 let d1 = tmpdir.join("d1");
1684 let dt = d1.join("t");
1685 let dtt = dt.join("t");
1686 let d2 = tmpdir.join("d2");
1687 let canary = d2.join("do_not_delete");
1688 check!(fs::create_dir_all(&dtt));
1689 check!(fs::create_dir_all(&d2));
1690 check!(check!(File::create(&canary)).write(b"foo"));
1691 check!(fs::soft_link(&d2, &dt.join("d2")));
1692 check!(fs::remove_dir_all(&d1));
1694 assert!(!d1.is_dir());
1695 assert!(canary.exists());
1699 fn unicode_path_is_dir() {
1700 assert!(Path2::new(".").is_dir());
1701 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1703 let tmpdir = tmpdir();
1705 let mut dirpath = tmpdir.path().to_path_buf();
1706 dirpath.push(&format!("test-가一ー你好"));
1707 check!(fs::create_dir(&dirpath));
1708 assert!(dirpath.is_dir());
1710 let mut filepath = dirpath;
1711 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1712 check!(File::create(&filepath)); // ignore return; touch only
1713 assert!(!filepath.is_dir());
1714 assert!(filepath.exists());
1718 fn unicode_path_exists() {
1719 assert!(Path2::new(".").exists());
1720 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1722 let tmpdir = tmpdir();
1723 let unicode = tmpdir.path();
1724 let unicode = unicode.join(&format!("test-각丁ー再见"));
1725 check!(fs::create_dir(&unicode));
1726 assert!(unicode.exists());
1727 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1731 fn copy_file_does_not_exist() {
1732 let from = Path2::new("test/nonexistent-bogus-path");
1733 let to = Path2::new("test/other-bogus-path");
1735 match fs::copy(&from, &to) {
1738 assert!(!from.exists());
1739 assert!(!to.exists());
1745 fn copy_src_does_not_exist() {
1746 let tmpdir = tmpdir();
1747 let from = Path2::new("test/nonexistent-bogus-path");
1748 let to = tmpdir.join("out.txt");
1749 check!(check!(File::create(&to)).write(b"hello"));
1750 assert!(fs::copy(&from, &to).is_err());
1751 assert!(!from.exists());
1752 let mut v = Vec::new();
1753 check!(check!(File::open(&to)).read_to_end(&mut v));
1754 assert_eq!(v, b"hello");
1759 let tmpdir = tmpdir();
1760 let input = tmpdir.join("in.txt");
1761 let out = tmpdir.join("out.txt");
1763 check!(check!(File::create(&input)).write(b"hello"));
1764 check!(fs::copy(&input, &out));
1765 let mut v = Vec::new();
1766 check!(check!(File::open(&out)).read_to_end(&mut v));
1767 assert_eq!(v, b"hello");
1769 assert_eq!(check!(input.metadata()).permissions(),
1770 check!(out.metadata()).permissions());
1774 fn copy_file_dst_dir() {
1775 let tmpdir = tmpdir();
1776 let out = tmpdir.join("out");
1778 check!(File::create(&out));
1779 match fs::copy(&*out, tmpdir.path()) {
1780 Ok(..) => panic!(), Err(..) => {}
1785 fn copy_file_dst_exists() {
1786 let tmpdir = tmpdir();
1787 let input = tmpdir.join("in");
1788 let output = tmpdir.join("out");
1790 check!(check!(File::create(&input)).write("foo".as_bytes()));
1791 check!(check!(File::create(&output)).write("bar".as_bytes()));
1792 check!(fs::copy(&input, &output));
1794 let mut v = Vec::new();
1795 check!(check!(File::open(&output)).read_to_end(&mut v));
1796 assert_eq!(v, b"foo".to_vec());
1800 fn copy_file_src_dir() {
1801 let tmpdir = tmpdir();
1802 let out = tmpdir.join("out");
1804 match fs::copy(tmpdir.path(), &out) {
1805 Ok(..) => panic!(), Err(..) => {}
1807 assert!(!out.exists());
1811 fn copy_file_preserves_perm_bits() {
1812 let tmpdir = tmpdir();
1813 let input = tmpdir.join("in.txt");
1814 let out = tmpdir.join("out.txt");
1816 let attr = check!(check!(File::create(&input)).metadata());
1817 let mut p = attr.permissions();
1818 p.set_readonly(true);
1819 check!(fs::set_permissions(&input, p));
1820 check!(fs::copy(&input, &out));
1821 assert!(check!(out.metadata()).permissions().readonly());
1822 check!(fs::set_permissions(&input, attr.permissions()));
1823 check!(fs::set_permissions(&out, attr.permissions()));
1828 fn copy_file_preserves_streams() {
1830 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
1831 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
1832 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
1833 let mut v = Vec::new();
1834 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
1835 assert_eq!(v, b"carrot".to_vec());
1838 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1840 fn symlinks_work() {
1841 let tmpdir = tmpdir();
1842 let input = tmpdir.join("in.txt");
1843 let out = tmpdir.join("out.txt");
1845 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1846 check!(fs::soft_link(&input, &out));
1847 // if cfg!(not(windows)) {
1848 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1849 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1851 assert_eq!(check!(fs::metadata(&out)).len(),
1852 check!(fs::metadata(&input)).len());
1853 let mut v = Vec::new();
1854 check!(check!(File::open(&out)).read_to_end(&mut v));
1855 assert_eq!(v, b"foobar".to_vec());
1858 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1860 fn symlink_noexist() {
1861 let tmpdir = tmpdir();
1862 // symlinks can point to things that don't exist
1863 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1864 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1865 tmpdir.join("foo"));
1869 fn readlink_not_symlink() {
1870 let tmpdir = tmpdir();
1871 match fs::read_link(tmpdir.path()) {
1872 Ok(..) => panic!("wanted a failure"),
1879 let tmpdir = tmpdir();
1880 let input = tmpdir.join("in.txt");
1881 let out = tmpdir.join("out.txt");
1883 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1884 check!(fs::hard_link(&input, &out));
1885 assert_eq!(check!(fs::metadata(&out)).len(),
1886 check!(fs::metadata(&input)).len());
1887 assert_eq!(check!(fs::metadata(&out)).len(),
1888 check!(input.metadata()).len());
1889 let mut v = Vec::new();
1890 check!(check!(File::open(&out)).read_to_end(&mut v));
1891 assert_eq!(v, b"foobar".to_vec());
1893 // can't link to yourself
1894 match fs::hard_link(&input, &input) {
1895 Ok(..) => panic!("wanted a failure"),
1898 // can't link to something that doesn't exist
1899 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1900 Ok(..) => panic!("wanted a failure"),
1907 let tmpdir = tmpdir();
1908 let file = tmpdir.join("in.txt");
1910 check!(File::create(&file));
1911 let attr = check!(fs::metadata(&file));
1912 assert!(!attr.permissions().readonly());
1913 let mut p = attr.permissions();
1914 p.set_readonly(true);
1915 check!(fs::set_permissions(&file, p.clone()));
1916 let attr = check!(fs::metadata(&file));
1917 assert!(attr.permissions().readonly());
1919 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1920 Ok(..) => panic!("wanted an error"),
1924 p.set_readonly(false);
1925 check!(fs::set_permissions(&file, p));
1929 fn sync_doesnt_kill_anything() {
1930 let tmpdir = tmpdir();
1931 let path = tmpdir.join("in.txt");
1933 let mut file = check!(File::create(&path));
1934 check!(file.sync_all());
1935 check!(file.sync_data());
1936 check!(file.write(b"foo"));
1937 check!(file.sync_all());
1938 check!(file.sync_data());
1942 fn truncate_works() {
1943 let tmpdir = tmpdir();
1944 let path = tmpdir.join("in.txt");
1946 let mut file = check!(File::create(&path));
1947 check!(file.write(b"foo"));
1948 check!(file.sync_all());
1950 // Do some simple things with truncation
1951 assert_eq!(check!(file.metadata()).len(), 3);
1952 check!(file.set_len(10));
1953 assert_eq!(check!(file.metadata()).len(), 10);
1954 check!(file.write(b"bar"));
1955 check!(file.sync_all());
1956 assert_eq!(check!(file.metadata()).len(), 10);
1958 let mut v = Vec::new();
1959 check!(check!(File::open(&path)).read_to_end(&mut v));
1960 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1962 // Truncate to a smaller length, don't seek, and then write something.
1963 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1964 // past the end of the file).
1965 check!(file.set_len(2));
1966 assert_eq!(check!(file.metadata()).len(), 2);
1967 check!(file.write(b"wut"));
1968 check!(file.sync_all());
1969 assert_eq!(check!(file.metadata()).len(), 9);
1970 let mut v = Vec::new();
1971 check!(check!(File::open(&path)).read_to_end(&mut v));
1972 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1977 use fs::OpenOptions as OO;
1978 fn c<T: Clone>(t: &T) -> T { t.clone() }
1980 let tmpdir = tmpdir();
1982 let mut r = OO::new(); r.read(true);
1983 let mut w = OO::new(); w.write(true);
1984 let mut rw = OO::new(); rw.write(true).read(true);
1986 match r.open(&tmpdir.join("a")) {
1987 Ok(..) => panic!(), Err(..) => {}
1990 // Perform each one twice to make sure that it succeeds the second time
1991 // (where the file exists)
1992 check!(c(&w).create(true).open(&tmpdir.join("b")));
1993 assert!(tmpdir.join("b").exists());
1994 check!(c(&w).create(true).open(&tmpdir.join("b")));
1995 check!(w.open(&tmpdir.join("b")));
1997 check!(c(&rw).create(true).open(&tmpdir.join("c")));
1998 assert!(tmpdir.join("c").exists());
1999 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2000 check!(rw.open(&tmpdir.join("c")));
2002 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2003 assert!(tmpdir.join("d").exists());
2004 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2005 check!(c(&w).append(true).open(&tmpdir.join("d")));
2007 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2008 assert!(tmpdir.join("e").exists());
2009 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2010 check!(c(&rw).append(true).open(&tmpdir.join("e")));
2012 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2013 assert!(tmpdir.join("f").exists());
2014 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2015 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2017 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2018 assert!(tmpdir.join("g").exists());
2019 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2020 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2022 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2023 check!(r.open(&tmpdir.join("h")));
2025 let mut f = check!(r.open(&tmpdir.join("h")));
2026 assert!(f.write("wut".as_bytes()).is_err());
2028 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2030 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2031 check!(f.write("bar".as_bytes()));
2033 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2035 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2036 check!(f.write("bar".as_bytes()));
2038 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2043 let mut bytes = [0; 1024];
2044 StdRng::new().unwrap().fill_bytes(&mut bytes);
2046 let tmpdir = tmpdir();
2048 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2049 let mut v = Vec::new();
2050 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2051 assert!(v == &bytes[..]);
2055 #[cfg(not(windows))]
2056 fn unlink_readonly() {
2057 let tmpdir = tmpdir();
2058 let path = tmpdir.join("file");
2059 check!(File::create(&path));
2060 let mut perm = check!(fs::metadata(&path)).permissions();
2061 perm.set_readonly(true);
2062 check!(fs::set_permissions(&path, perm));
2063 check!(fs::remove_file(&path));
2067 fn mkdir_trailing_slash() {
2068 let tmpdir = tmpdir();
2069 let path = tmpdir.join("file");
2070 check!(fs::create_dir_all(&path.join("a/")));
2074 #[cfg(not(windows))]
2075 fn realpath_works() {
2076 let tmpdir = tmpdir();
2077 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2078 let file = tmpdir.join("test");
2079 let dir = tmpdir.join("test2");
2080 let link = dir.join("link");
2081 let linkdir = tmpdir.join("test3");
2083 File::create(&file).unwrap();
2084 fs::create_dir(&dir).unwrap();
2085 fs::soft_link(&file, &link).unwrap();
2086 fs::soft_link(&dir, &linkdir).unwrap();
2088 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2090 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2091 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2092 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2093 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2094 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2098 #[cfg(not(windows))]
2099 fn realpath_works_tricky() {
2100 let tmpdir = tmpdir();
2101 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2103 let a = tmpdir.join("a");
2104 let b = a.join("b");
2105 let c = b.join("c");
2106 let d = a.join("d");
2107 let e = d.join("e");
2108 let f = a.join("f");
2110 fs::create_dir_all(&b).unwrap();
2111 fs::create_dir_all(&d).unwrap();
2112 File::create(&f).unwrap();
2113 fs::soft_link("../d/e", &c).unwrap();
2114 fs::soft_link("../f", &e).unwrap();
2116 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2117 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2121 fn dir_entry_methods() {
2122 let tmpdir = tmpdir();
2124 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2125 File::create(&tmpdir.join("b")).unwrap();
2127 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2128 let fname = file.file_name();
2129 match fname.to_str() {
2131 assert!(file.file_type().unwrap().is_dir());
2132 assert!(file.metadata().unwrap().is_dir());
2135 assert!(file.file_type().unwrap().is_file());
2136 assert!(file.metadata().unwrap().is_file());
2138 f => panic!("unknown file name: {:?}", f),