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 net set of options ready for configuration.
380 /// All options are initially set to `false`.
385 /// use std::fs::OpenOptions;
387 /// let file = OpenOptions::new().open("foo.txt");
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn new() -> OpenOptions {
391 OpenOptions(fs_imp::OpenOptions::new())
394 /// Sets the option for read access.
396 /// This option, when true, will indicate that the file should be
397 /// `read`-able if opened.
402 /// use std::fs::OpenOptions;
404 /// let file = OpenOptions::new().read(true).open("foo.txt");
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
408 self.0.read(read); self
411 /// Sets the option for write access.
413 /// This option, when true, will indicate that the file should be
414 /// `write`-able if opened.
419 /// use std::fs::OpenOptions;
421 /// let file = OpenOptions::new().write(true).open("foo.txt");
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
425 self.0.write(write); self
428 /// Sets the option for the append mode.
430 /// This option, when true, means that writes will append to a file instead
431 /// of overwriting previous contents.
436 /// use std::fs::OpenOptions;
438 /// let file = OpenOptions::new().write(true).append(true).open("foo.txt");
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
442 self.0.append(append); self
445 /// Sets the option for truncating a previous file.
447 /// If a file is successfully opened with this option set it will truncate
448 /// the file to 0 length if it already exists.
453 /// use std::fs::OpenOptions;
455 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
459 self.0.truncate(truncate); self
462 /// Sets the option for creating a new file.
464 /// This option indicates whether a new file will be created if the file
465 /// does not yet already exist.
470 /// use std::fs::OpenOptions;
472 /// let file = OpenOptions::new().create(true).open("foo.txt");
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
476 self.0.create(create); self
479 /// Opens a file at `path` with the options specified by `self`.
483 /// This function will return an error under a number of different
484 /// circumstances, to include but not limited to:
486 /// * Opening a file that does not exist with read access.
487 /// * Attempting to open a file with access that the user lacks
489 /// * Filesystem-level errors (full disk, etc)
494 /// use std::fs::OpenOptions;
496 /// let file = OpenOptions::new().open("foo.txt");
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
500 self._open(path.as_ref())
503 fn _open(&self, path: &Path) -> io::Result<File> {
504 let inner = try!(fs_imp::File::open(path, &self.0));
505 Ok(File { inner: inner })
509 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
510 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
514 /// Returns the file type for this metadata.
515 #[stable(feature = "file_type", since = "1.1.0")]
516 pub fn file_type(&self) -> FileType {
517 FileType(self.0.file_type())
520 /// Returns whether this metadata is for a directory.
525 /// # fn foo() -> std::io::Result<()> {
528 /// let metadata = try!(fs::metadata("foo.txt"));
530 /// assert!(!metadata.is_dir());
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
537 /// Returns whether this metadata is for a regular file.
542 /// # fn foo() -> std::io::Result<()> {
545 /// let metadata = try!(fs::metadata("foo.txt"));
547 /// assert!(metadata.is_file());
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn is_file(&self) -> bool { self.file_type().is_file() }
554 /// Returns the size of the file, in bytes, this metadata is for.
559 /// # fn foo() -> std::io::Result<()> {
562 /// let metadata = try!(fs::metadata("foo.txt"));
564 /// assert_eq!(0, metadata.len());
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn len(&self) -> u64 { self.0.size() }
571 /// Returns the permissions of the file this metadata is for.
576 /// # fn foo() -> std::io::Result<()> {
579 /// let metadata = try!(fs::metadata("foo.txt"));
581 /// assert!(!metadata.permissions().readonly());
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn permissions(&self) -> Permissions {
587 Permissions(self.0.perm())
591 impl AsInner<fs_imp::FileAttr> for Metadata {
592 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
596 /// Returns whether these permissions describe a readonly file.
601 /// use std::fs::File;
603 /// # fn foo() -> std::io::Result<()> {
604 /// let mut f = try!(File::create("foo.txt"));
605 /// let metadata = try!(f.metadata());
607 /// assert_eq!(false, metadata.permissions().readonly());
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn readonly(&self) -> bool { self.0.readonly() }
614 /// Modifies the readonly flag for this set of permissions.
616 /// This operation does **not** modify the filesystem. To modify the
617 /// filesystem use the `fs::set_permissions` function.
622 /// use std::fs::File;
624 /// # fn foo() -> std::io::Result<()> {
625 /// let f = try!(File::create("foo.txt"));
626 /// let metadata = try!(f.metadata());
627 /// let mut permissions = metadata.permissions();
629 /// permissions.set_readonly(true);
631 /// // filesystem doesn't change
632 /// assert_eq!(false, metadata.permissions().readonly());
634 /// // just this particular `permissions`.
635 /// assert_eq!(true, permissions.readonly());
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub fn set_readonly(&mut self, readonly: bool) {
641 self.0.set_readonly(readonly)
646 /// Test whether this file type represents a directory.
647 #[stable(feature = "file_type", since = "1.1.0")]
648 pub fn is_dir(&self) -> bool { self.0.is_dir() }
650 /// Test whether this file type represents a regular file.
651 #[stable(feature = "file_type", since = "1.1.0")]
652 pub fn is_file(&self) -> bool { self.0.is_file() }
654 /// Test whether this file type represents a symbolic link.
655 #[stable(feature = "file_type", since = "1.1.0")]
656 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
659 impl AsInner<fs_imp::FileType> for FileType {
660 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
663 impl FromInner<fs_imp::FilePermissions> for Permissions {
664 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
669 impl AsInner<fs_imp::FilePermissions> for Permissions {
670 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl Iterator for ReadDir {
675 type Item = io::Result<DirEntry>;
677 fn next(&mut self) -> Option<io::Result<DirEntry>> {
678 self.0.next().map(|entry| entry.map(DirEntry))
683 /// Returns the full path to the file that this entry represents.
685 /// The full path is created by joining the original path to `read_dir` or
686 /// `walk_dir` with the filename of this entry.
692 /// # fn foo() -> std::io::Result<()> {
693 /// for entry in try!(fs::read_dir(".")) {
694 /// let dir = try!(entry);
695 /// println!("{:?}", dir.path());
701 /// This prints output like:
706 /// "./hello_world.rs"
709 /// The exact text, of course, depends on what files you have in `.`.
710 #[stable(feature = "rust1", since = "1.0.0")]
711 pub fn path(&self) -> PathBuf { self.0.path() }
713 /// Return the metadata for the file that this entry points at.
715 /// This function will not traverse symlinks if this entry points at a
718 /// # Platform behavior
720 /// On Windows this function is cheap to call (no extra system calls
721 /// needed), but on Unix platforms this function is the equivalent of
722 /// calling `symlink_metadata` on the path.
723 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
724 pub fn metadata(&self) -> io::Result<Metadata> {
725 self.0.metadata().map(Metadata)
728 /// Return the file type for the file that this entry points at.
730 /// This function will not traverse symlinks if this entry points at a
733 /// # Platform behavior
735 /// On Windows and most Unix platforms this function is free (no extra
736 /// system calls needed), but some Unix platforms may require the equivalent
737 /// call to `symlink_metadata` to learn about the target file type.
738 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
739 pub fn file_type(&self) -> io::Result<FileType> {
740 self.0.file_type().map(FileType)
743 /// Returns the bare file name of this directory entry without any other
744 /// leading path component.
745 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
746 pub fn file_name(&self) -> OsString {
751 impl AsInner<fs_imp::DirEntry> for DirEntry {
752 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
755 /// Removes a file from the filesystem.
757 /// Note that there is no
758 /// guarantee that the file is immediately deleted (e.g. depending on
759 /// platform, other open file descriptors may prevent immediate removal).
763 /// This function will return an error if `path` points to a directory, if the
764 /// user lacks permissions to remove the file, or if some other filesystem-level
772 /// # fn foo() -> std::io::Result<()> {
773 /// try!(fs::remove_file("a.txt"));
777 #[stable(feature = "rust1", since = "1.0.0")]
778 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
779 fs_imp::unlink(path.as_ref())
782 /// Given a path, query the file system to get information about a file,
785 /// This function will traverse symbolic links to query information about the
786 /// destination file.
791 /// # fn foo() -> std::io::Result<()> {
794 /// let attr = try!(fs::metadata("/some/file/path.txt"));
795 /// // inspect attr ...
802 /// This function will return an error if the user lacks the requisite
803 /// permissions to perform a `metadata` call on the given `path` or if there
804 /// is no entry in the filesystem at the provided path.
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
807 fs_imp::stat(path.as_ref()).map(Metadata)
810 /// Query the metadata about a file without following symlinks.
815 /// # fn foo() -> std::io::Result<()> {
818 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
819 /// // inspect attr ...
823 #[stable(feature = "symlink_metadata", since = "1.1.0")]
824 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
825 fs_imp::lstat(path.as_ref()).map(Metadata)
828 /// Rename a file or directory to a new name.
830 /// This will not work if the new name is on a different mount point.
834 /// This function will return an error if the provided `from` doesn't exist, if
835 /// the process lacks permissions to view the contents, if `from` and `to`
836 /// reside on separate filesystems, or if some other intermittent I/O error
844 /// # fn foo() -> std::io::Result<()> {
845 /// try!(fs::rename("a.txt", "b.txt"));
849 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
851 fs_imp::rename(from.as_ref(), to.as_ref())
854 /// Copies the contents of one file to another. This function will also
855 /// copy the permission bits of the original file to the destination file.
857 /// This function will **overwrite** the contents of `to`.
859 /// Note that if `from` and `to` both point to the same file, then the file
860 /// will likely get truncated by this operation.
862 /// On success, the total number of bytes copied is returned.
866 /// This function will return an error in the following situations, but is not
867 /// limited to just these cases:
869 /// * The `from` path is not a file
870 /// * The `from` file does not exist
871 /// * The current process does not have the permission rights to access
872 /// `from` or write `to`
879 /// # fn foo() -> std::io::Result<()> {
880 /// try!(fs::copy("foo.txt", "bar.txt"));
883 #[stable(feature = "rust1", since = "1.0.0")]
884 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
885 fs_imp::copy(from.as_ref(), to.as_ref())
888 /// Creates a new hard link on the filesystem.
890 /// The `dst` path will be a link pointing to the `src` path. Note that systems
891 /// often require these two paths to both be located on the same filesystem.
898 /// # fn foo() -> std::io::Result<()> {
899 /// try!(fs::hard_link("a.txt", "b.txt"));
903 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
905 fs_imp::link(src.as_ref(), dst.as_ref())
908 /// Creates a new symbolic link on the filesystem.
910 /// The `dst` path will be a symbolic link pointing to the `src` path.
911 /// On Windows, this will be a file symlink, not a directory symlink;
912 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
913 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
914 /// used instead to make the intent explicit.
921 /// # fn foo() -> std::io::Result<()> {
922 /// try!(fs::soft_link("a.txt", "b.txt"));
926 #[rustc_deprecated(since = "1.1.0",
927 reason = "replaced with std::os::unix::fs::symlink and \
928 std::os::windows::fs::{symlink_file, symlink_dir}")]
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
931 fs_imp::symlink(src.as_ref(), dst.as_ref())
934 /// Reads a symbolic link, returning the file that the link points to.
938 /// This function will return an error on failure. Failure conditions include
939 /// reading a file that does not exist or reading a file that is not a symbolic
947 /// # fn foo() -> std::io::Result<()> {
948 /// let path = try!(fs::read_link("a.txt"));
952 #[stable(feature = "rust1", since = "1.0.0")]
953 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
954 fs_imp::readlink(path.as_ref())
957 /// Returns the canonical form of a path with all intermediate components
958 /// normalized and symbolic links resolved.
960 /// This function may return an error in situations like where the path does not
961 /// exist, a component in the path is not a directory, or an I/O error happens.
968 /// # fn foo() -> std::io::Result<()> {
969 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
973 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
974 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
975 fs_imp::canonicalize(path.as_ref())
978 /// Creates a new, empty directory at the provided path
982 /// This function will return an error if the user lacks permissions to make a
983 /// new directory at the provided `path`, or if the directory already exists.
990 /// # fn foo() -> std::io::Result<()> {
991 /// try!(fs::create_dir("/some/dir"));
995 #[stable(feature = "rust1", since = "1.0.0")]
996 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
997 DirBuilder::new().create(path.as_ref())
1000 /// Recursively create a directory and all of its parent components if they
1005 /// This function will fail if any directory in the path specified by `path`
1006 /// does not already exist and it could not be created otherwise. The specific
1007 /// error conditions for when a directory is being created (after it is
1008 /// determined to not exist) are outlined by `fs::create_dir`.
1015 /// # fn foo() -> std::io::Result<()> {
1016 /// try!(fs::create_dir_all("/some/dir"));
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1022 DirBuilder::new().recursive(true).create(path.as_ref())
1025 /// Removes an existing, empty directory.
1029 /// This function will return an error if the user lacks permissions to remove
1030 /// the directory at the provided `path`, or if the directory isn't empty.
1037 /// # fn foo() -> std::io::Result<()> {
1038 /// try!(fs::remove_dir("/some/dir"));
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1044 fs_imp::rmdir(path.as_ref())
1047 /// Removes a directory at this path, after removing all its contents. Use
1050 /// This function does **not** follow symbolic links and it will simply remove the
1051 /// symbolic link itself.
1055 /// See `file::remove_file` and `fs::remove_dir`.
1062 /// # fn foo() -> std::io::Result<()> {
1063 /// try!(fs::remove_dir_all("/some/dir"));
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1069 _remove_dir_all(path.as_ref())
1072 fn _remove_dir_all(path: &Path) -> io::Result<()> {
1073 for child in try!(read_dir(path)) {
1074 let child = try!(child).path();
1075 let stat = try!(symlink_metadata(&*child));
1077 try!(remove_dir_all(&*child));
1079 try!(remove_file(&*child));
1085 /// Returns an iterator over the entries within a directory.
1087 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1088 /// be encountered after an iterator is initially constructed.
1094 /// use std::fs::{self, DirEntry};
1095 /// use std::path::Path;
1097 /// // one possible implementation of fs::walk_dir only visiting files
1098 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1099 /// if try!(fs::metadata(dir)).is_dir() {
1100 /// for entry in try!(fs::read_dir(dir)) {
1101 /// let entry = try!(entry);
1102 /// if try!(fs::metadata(entry.path())).is_dir() {
1103 /// try!(visit_dirs(&entry.path(), cb));
1115 /// This function will return an error if the provided `path` doesn't exist, if
1116 /// the process lacks permissions to view the contents or if the `path` points
1117 /// at a non-directory file
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1120 fs_imp::readdir(path.as_ref()).map(ReadDir)
1123 /// Returns an iterator that will recursively walk the directory structure
1124 /// rooted at `path`.
1126 /// The path given will not be iterated over, and this will perform iteration in
1127 /// some top-down order. The contents of unreadable subdirectories are ignored.
1129 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1130 /// be encountered after an iterator is initially constructed.
1131 #[unstable(feature = "fs_walk",
1132 reason = "the precise semantics and defaults for a recursive walk \
1133 may change and this may end up accounting for files such \
1134 as symlinks differently",
1136 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1138 #[allow(deprecated)]
1139 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1140 _walk_dir(path.as_ref())
1143 #[allow(deprecated)]
1144 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1145 let start = try!(read_dir(path));
1146 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1149 #[unstable(feature = "fs_walk", issue = "27707")]
1150 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1152 #[allow(deprecated)]
1153 impl Iterator for WalkDir {
1154 type Item = io::Result<DirEntry>;
1156 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1158 if let Some(ref mut cur) = self.cur {
1160 Some(Err(e)) => return Some(Err(e)),
1162 let path = next.path();
1164 self.stack.push(read_dir(&*path));
1166 return Some(Ok(next))
1172 match self.stack.pop() {
1173 Some(Err(e)) => return Some(Err(e)),
1174 Some(Ok(next)) => self.cur = Some(next),
1175 None => return None,
1181 /// Utility methods for paths.
1182 #[unstable(feature = "path_ext_deprecated",
1183 reason = "The precise set of methods exposed on this trait may \
1184 change and some methods may be removed. For stable code, \
1185 see the std::fs::metadata function.",
1187 #[rustc_deprecated(since = "1.5.0", reason = "replaced with inherent methods")]
1189 /// Gets information on the file, directory, etc at this path.
1191 /// Consult the `fs::metadata` documentation for more info.
1193 /// This call preserves identical runtime/error semantics with
1195 fn metadata(&self) -> io::Result<Metadata>;
1197 /// Gets information on the file, directory, etc at this path.
1199 /// Consult the `fs::symlink_metadata` documentation for more info.
1201 /// This call preserves identical runtime/error semantics with
1202 /// `fs::symlink_metadata`.
1203 fn symlink_metadata(&self) -> io::Result<Metadata>;
1205 /// Returns the canonical form of a path, normalizing all components and
1206 /// eliminate all symlinks.
1208 /// This call preserves identical runtime/error semantics with
1209 /// `fs::canonicalize`.
1210 fn canonicalize(&self) -> io::Result<PathBuf>;
1212 /// Reads the symlink at this path.
1214 /// For more information see `fs::read_link`.
1215 fn read_link(&self) -> io::Result<PathBuf>;
1217 /// Reads the directory at this path.
1219 /// For more information see `fs::read_dir`.
1220 fn read_dir(&self) -> io::Result<ReadDir>;
1222 /// Boolean value indicator whether the underlying file exists on the local
1223 /// filesystem. Returns false in exactly the cases where `fs::metadata`
1225 fn exists(&self) -> bool;
1227 /// Whether the underlying implementation (be it a file path, or something
1228 /// else) points at a "regular file" on the FS. Will return false for paths
1229 /// to non-existent locations or directories or other non-regular files
1230 /// (named pipes, etc). Follows links when making this determination.
1231 fn is_file(&self) -> bool;
1233 /// Whether the underlying implementation (be it a file path, or something
1234 /// else) is pointing at a directory in the underlying FS. Will return
1235 /// false for paths to non-existent locations or if the item is not a
1236 /// directory (eg files, named pipes, etc). Follows links when making this
1238 fn is_dir(&self) -> bool;
1241 #[allow(deprecated)]
1242 #[unstable(feature = "path_ext_deprecated", issue = "27725")]
1243 impl PathExt for Path {
1244 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1245 fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1246 fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1247 fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1248 fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1249 fn exists(&self) -> bool { metadata(self).is_ok() }
1251 fn is_file(&self) -> bool {
1252 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1255 fn is_dir(&self) -> bool {
1256 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1260 /// Changes the permissions found on a file or a directory.
1265 /// # fn foo() -> std::io::Result<()> {
1268 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1269 /// perms.set_readonly(true);
1270 /// try!(fs::set_permissions("foo.txt", perms));
1277 /// This function will return an error if the provided `path` doesn't exist, if
1278 /// the process lacks permissions to change the attributes of the file, or if
1279 /// some other I/O error is encountered.
1280 #[stable(feature = "set_permissions", since = "1.1.0")]
1281 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1283 fs_imp::set_perm(path.as_ref(), perm.0)
1287 /// Creates a new set of options with default mode/security settings for all
1288 /// platforms and also non-recursive.
1289 #[stable(feature = "dir_builder", since = "1.6.0")]
1290 pub fn new() -> DirBuilder {
1292 inner: fs_imp::DirBuilder::new(),
1297 /// Indicate that directories create should be created recursively, creating
1298 /// all parent directories if they do not exist with the same security and
1299 /// permissions settings.
1301 /// This option defaults to `false`
1302 #[stable(feature = "dir_builder", since = "1.6.0")]
1303 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1304 self.recursive = recursive;
1308 /// Create the specified directory with the options configured in this
1314 /// use std::fs::{self, DirBuilder};
1316 /// let path = "/tmp/foo/bar/baz";
1317 /// DirBuilder::new()
1318 /// .recursive(true)
1319 /// .create(path).unwrap();
1321 /// assert!(fs::metadata(path).unwrap().is_dir());
1323 #[stable(feature = "dir_builder", since = "1.6.0")]
1324 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1325 self._create(path.as_ref())
1328 fn _create(&self, path: &Path) -> io::Result<()> {
1330 self.create_dir_all(path)
1332 self.inner.mkdir(path)
1336 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1337 if path == Path::new("") || path.is_dir() { return Ok(()) }
1338 if let Some(p) = path.parent() {
1339 try!(self.create_dir_all(p))
1341 self.inner.mkdir(path)
1345 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1346 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1353 #![allow(deprecated)] //rand
1359 use fs::{self, File, OpenOptions};
1360 use io::{ErrorKind, SeekFrom};
1362 use path::Path as Path2;
1364 use rand::{self, StdRng, Rng};
1367 macro_rules! check { ($e:expr) => (
1370 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1374 macro_rules! error { ($e:expr, $s:expr) => (
1376 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1377 Err(ref err) => assert!(err.to_string().contains($s),
1378 format!("`{}` did not contain `{}`", err, $s))
1382 pub struct TempDir(PathBuf);
1385 fn join(&self, path: &str) -> PathBuf {
1386 let TempDir(ref p) = *self;
1390 fn path<'a>(&'a self) -> &'a Path2 {
1391 let TempDir(ref p) = *self;
1396 impl Drop for TempDir {
1397 fn drop(&mut self) {
1398 // Gee, seeing how we're testing the fs module I sure hope that we
1399 // at least implement this correctly!
1400 let TempDir(ref p) = *self;
1401 check!(fs::remove_dir_all(p));
1405 pub fn tmpdir() -> TempDir {
1406 let p = env::temp_dir();
1407 let mut r = rand::thread_rng();
1408 let ret = p.join(&format!("rust-{}", r.next_u32()));
1409 check!(fs::create_dir(&ret));
1414 fn file_test_io_smoke_test() {
1415 let message = "it's alright. have a good time";
1416 let tmpdir = tmpdir();
1417 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1419 let mut write_stream = check!(File::create(filename));
1420 check!(write_stream.write(message.as_bytes()));
1423 let mut read_stream = check!(File::open(filename));
1424 let mut read_buf = [0; 1028];
1425 let read_str = match check!(read_stream.read(&mut read_buf)) {
1426 0 => panic!("shouldn't happen"),
1427 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1429 assert_eq!(read_str, message);
1431 check!(fs::remove_file(filename));
1435 fn invalid_path_raises() {
1436 let tmpdir = tmpdir();
1437 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1438 let result = File::open(filename);
1441 error!(result, "o such file or directory");
1443 // error!(result, "couldn't open path as file");
1444 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1448 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1449 let tmpdir = tmpdir();
1450 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1452 let result = fs::remove_file(filename);
1455 error!(result, "o such file or directory");
1457 // error!(result, "couldn't unlink path");
1458 // error!(result, format!("path={}", filename.display()));
1462 fn file_test_io_non_positional_read() {
1463 let message: &str = "ten-four";
1464 let mut read_mem = [0; 8];
1465 let tmpdir = tmpdir();
1466 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1468 let mut rw_stream = check!(File::create(filename));
1469 check!(rw_stream.write(message.as_bytes()));
1472 let mut read_stream = check!(File::open(filename));
1474 let read_buf = &mut read_mem[0..4];
1475 check!(read_stream.read(read_buf));
1478 let read_buf = &mut read_mem[4..8];
1479 check!(read_stream.read(read_buf));
1482 check!(fs::remove_file(filename));
1483 let read_str = str::from_utf8(&read_mem).unwrap();
1484 assert_eq!(read_str, message);
1488 fn file_test_io_seek_and_tell_smoke_test() {
1489 let message = "ten-four";
1490 let mut read_mem = [0; 4];
1491 let set_cursor = 4 as u64;
1492 let mut tell_pos_pre_read;
1493 let mut tell_pos_post_read;
1494 let tmpdir = tmpdir();
1495 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1497 let mut rw_stream = check!(File::create(filename));
1498 check!(rw_stream.write(message.as_bytes()));
1501 let mut read_stream = check!(File::open(filename));
1502 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1503 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1504 check!(read_stream.read(&mut read_mem));
1505 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1507 check!(fs::remove_file(filename));
1508 let read_str = str::from_utf8(&read_mem).unwrap();
1509 assert_eq!(read_str, &message[4..8]);
1510 assert_eq!(tell_pos_pre_read, set_cursor);
1511 assert_eq!(tell_pos_post_read, message.len() as u64);
1515 fn file_test_io_seek_and_write() {
1516 let initial_msg = "food-is-yummy";
1517 let overwrite_msg = "-the-bar!!";
1518 let final_msg = "foo-the-bar!!";
1520 let mut read_mem = [0; 13];
1521 let tmpdir = tmpdir();
1522 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1524 let mut rw_stream = check!(File::create(filename));
1525 check!(rw_stream.write(initial_msg.as_bytes()));
1526 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1527 check!(rw_stream.write(overwrite_msg.as_bytes()));
1530 let mut read_stream = check!(File::open(filename));
1531 check!(read_stream.read(&mut read_mem));
1533 check!(fs::remove_file(filename));
1534 let read_str = str::from_utf8(&read_mem).unwrap();
1535 assert!(read_str == final_msg);
1539 fn file_test_io_seek_shakedown() {
1541 let initial_msg = "qwer-asdf-zxcv";
1542 let chunk_one: &str = "qwer";
1543 let chunk_two: &str = "asdf";
1544 let chunk_three: &str = "zxcv";
1545 let mut read_mem = [0; 4];
1546 let tmpdir = tmpdir();
1547 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1549 let mut rw_stream = check!(File::create(filename));
1550 check!(rw_stream.write(initial_msg.as_bytes()));
1553 let mut read_stream = check!(File::open(filename));
1555 check!(read_stream.seek(SeekFrom::End(-4)));
1556 check!(read_stream.read(&mut read_mem));
1557 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1559 check!(read_stream.seek(SeekFrom::Current(-9)));
1560 check!(read_stream.read(&mut read_mem));
1561 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1563 check!(read_stream.seek(SeekFrom::Start(0)));
1564 check!(read_stream.read(&mut read_mem));
1565 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1567 check!(fs::remove_file(filename));
1571 fn file_test_stat_is_correct_on_is_file() {
1572 let tmpdir = tmpdir();
1573 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1575 let mut opts = OpenOptions::new();
1576 let mut fs = check!(opts.read(true).write(true)
1577 .create(true).open(filename));
1579 fs.write(msg.as_bytes()).unwrap();
1581 let fstat_res = check!(fs.metadata());
1582 assert!(fstat_res.is_file());
1584 let stat_res_fn = check!(fs::metadata(filename));
1585 assert!(stat_res_fn.is_file());
1586 let stat_res_meth = check!(filename.metadata());
1587 assert!(stat_res_meth.is_file());
1588 check!(fs::remove_file(filename));
1592 fn file_test_stat_is_correct_on_is_dir() {
1593 let tmpdir = tmpdir();
1594 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1595 check!(fs::create_dir(filename));
1596 let stat_res_fn = check!(fs::metadata(filename));
1597 assert!(stat_res_fn.is_dir());
1598 let stat_res_meth = check!(filename.metadata());
1599 assert!(stat_res_meth.is_dir());
1600 check!(fs::remove_dir(filename));
1604 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1605 let tmpdir = tmpdir();
1606 let dir = &tmpdir.join("fileinfo_false_on_dir");
1607 check!(fs::create_dir(dir));
1608 assert!(dir.is_file() == false);
1609 check!(fs::remove_dir(dir));
1613 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1614 let tmpdir = tmpdir();
1615 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1616 check!(check!(File::create(file)).write(b"foo"));
1617 assert!(file.exists());
1618 check!(fs::remove_file(file));
1619 assert!(!file.exists());
1623 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1624 let tmpdir = tmpdir();
1625 let dir = &tmpdir.join("before_and_after_dir");
1626 assert!(!dir.exists());
1627 check!(fs::create_dir(dir));
1628 assert!(dir.exists());
1629 assert!(dir.is_dir());
1630 check!(fs::remove_dir(dir));
1631 assert!(!dir.exists());
1635 fn file_test_directoryinfo_readdir() {
1636 let tmpdir = tmpdir();
1637 let dir = &tmpdir.join("di_readdir");
1638 check!(fs::create_dir(dir));
1641 let f = dir.join(&format!("{}.txt", n));
1642 let mut w = check!(File::create(&f));
1643 let msg_str = format!("{}{}", prefix, n.to_string());
1644 let msg = msg_str.as_bytes();
1645 check!(w.write(msg));
1647 let files = check!(fs::read_dir(dir));
1648 let mut mem = [0; 4];
1650 let f = f.unwrap().path();
1652 let n = f.file_stem().unwrap();
1653 check!(check!(File::open(&f)).read(&mut mem));
1654 let read_str = str::from_utf8(&mem).unwrap();
1655 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1656 assert_eq!(expected, read_str);
1658 check!(fs::remove_file(&f));
1660 check!(fs::remove_dir(dir));
1664 fn file_test_walk_dir() {
1665 let tmpdir = tmpdir();
1666 let dir = &tmpdir.join("walk_dir");
1667 check!(fs::create_dir(dir));
1669 let dir1 = &dir.join("01/02/03");
1670 check!(fs::create_dir_all(dir1));
1671 check!(File::create(&dir1.join("04")));
1673 let dir2 = &dir.join("11/12/13");
1674 check!(fs::create_dir_all(dir2));
1675 check!(File::create(&dir2.join("14")));
1677 let files = check!(fs::walk_dir(dir));
1678 let mut cur = [0; 2];
1680 let f = f.unwrap().path();
1681 let stem = f.file_stem().unwrap().to_str().unwrap();
1682 let root = stem.as_bytes()[0] - b'0';
1683 let name = stem.as_bytes()[1] - b'0';
1684 assert!(cur[root as usize] < name);
1685 cur[root as usize] = name;
1688 check!(fs::remove_dir_all(dir));
1692 fn mkdir_path_already_exists_error() {
1693 let tmpdir = tmpdir();
1694 let dir = &tmpdir.join("mkdir_error_twice");
1695 check!(fs::create_dir(dir));
1696 let e = fs::create_dir(dir).err().unwrap();
1697 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1701 fn recursive_mkdir() {
1702 let tmpdir = tmpdir();
1703 let dir = tmpdir.join("d1/d2");
1704 check!(fs::create_dir_all(&dir));
1705 assert!(dir.is_dir())
1709 fn recursive_mkdir_failure() {
1710 let tmpdir = tmpdir();
1711 let dir = tmpdir.join("d1");
1712 let file = dir.join("f1");
1714 check!(fs::create_dir_all(&dir));
1715 check!(File::create(&file));
1717 let result = fs::create_dir_all(&file);
1719 assert!(result.is_err());
1720 // error!(result, "couldn't recursively mkdir");
1721 // error!(result, "couldn't create directory");
1722 // error!(result, "mode=0700");
1723 // error!(result, format!("path={}", file.display()));
1727 fn recursive_mkdir_slash() {
1728 check!(fs::create_dir_all(&Path2::new("/")));
1731 // FIXME(#12795) depends on lstat to work on windows
1732 #[cfg(not(windows))]
1734 fn recursive_rmdir() {
1735 let tmpdir = tmpdir();
1736 let d1 = tmpdir.join("d1");
1737 let dt = d1.join("t");
1738 let dtt = dt.join("t");
1739 let d2 = tmpdir.join("d2");
1740 let canary = d2.join("do_not_delete");
1741 check!(fs::create_dir_all(&dtt));
1742 check!(fs::create_dir_all(&d2));
1743 check!(check!(File::create(&canary)).write(b"foo"));
1744 check!(fs::soft_link(&d2, &dt.join("d2")));
1745 check!(fs::remove_dir_all(&d1));
1747 assert!(!d1.is_dir());
1748 assert!(canary.exists());
1752 fn unicode_path_is_dir() {
1753 assert!(Path2::new(".").is_dir());
1754 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1756 let tmpdir = tmpdir();
1758 let mut dirpath = tmpdir.path().to_path_buf();
1759 dirpath.push("test-가一ー你好");
1760 check!(fs::create_dir(&dirpath));
1761 assert!(dirpath.is_dir());
1763 let mut filepath = dirpath;
1764 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1765 check!(File::create(&filepath)); // ignore return; touch only
1766 assert!(!filepath.is_dir());
1767 assert!(filepath.exists());
1771 fn unicode_path_exists() {
1772 assert!(Path2::new(".").exists());
1773 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1775 let tmpdir = tmpdir();
1776 let unicode = tmpdir.path();
1777 let unicode = unicode.join(&format!("test-각丁ー再见"));
1778 check!(fs::create_dir(&unicode));
1779 assert!(unicode.exists());
1780 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1784 fn copy_file_does_not_exist() {
1785 let from = Path2::new("test/nonexistent-bogus-path");
1786 let to = Path2::new("test/other-bogus-path");
1788 match fs::copy(&from, &to) {
1791 assert!(!from.exists());
1792 assert!(!to.exists());
1798 fn copy_src_does_not_exist() {
1799 let tmpdir = tmpdir();
1800 let from = Path2::new("test/nonexistent-bogus-path");
1801 let to = tmpdir.join("out.txt");
1802 check!(check!(File::create(&to)).write(b"hello"));
1803 assert!(fs::copy(&from, &to).is_err());
1804 assert!(!from.exists());
1805 let mut v = Vec::new();
1806 check!(check!(File::open(&to)).read_to_end(&mut v));
1807 assert_eq!(v, b"hello");
1812 let tmpdir = tmpdir();
1813 let input = tmpdir.join("in.txt");
1814 let out = tmpdir.join("out.txt");
1816 check!(check!(File::create(&input)).write(b"hello"));
1817 check!(fs::copy(&input, &out));
1818 let mut v = Vec::new();
1819 check!(check!(File::open(&out)).read_to_end(&mut v));
1820 assert_eq!(v, b"hello");
1822 assert_eq!(check!(input.metadata()).permissions(),
1823 check!(out.metadata()).permissions());
1827 fn copy_file_dst_dir() {
1828 let tmpdir = tmpdir();
1829 let out = tmpdir.join("out");
1831 check!(File::create(&out));
1832 match fs::copy(&*out, tmpdir.path()) {
1833 Ok(..) => panic!(), Err(..) => {}
1838 fn copy_file_dst_exists() {
1839 let tmpdir = tmpdir();
1840 let input = tmpdir.join("in");
1841 let output = tmpdir.join("out");
1843 check!(check!(File::create(&input)).write("foo".as_bytes()));
1844 check!(check!(File::create(&output)).write("bar".as_bytes()));
1845 check!(fs::copy(&input, &output));
1847 let mut v = Vec::new();
1848 check!(check!(File::open(&output)).read_to_end(&mut v));
1849 assert_eq!(v, b"foo".to_vec());
1853 fn copy_file_src_dir() {
1854 let tmpdir = tmpdir();
1855 let out = tmpdir.join("out");
1857 match fs::copy(tmpdir.path(), &out) {
1858 Ok(..) => panic!(), Err(..) => {}
1860 assert!(!out.exists());
1864 fn copy_file_preserves_perm_bits() {
1865 let tmpdir = tmpdir();
1866 let input = tmpdir.join("in.txt");
1867 let out = tmpdir.join("out.txt");
1869 let attr = check!(check!(File::create(&input)).metadata());
1870 let mut p = attr.permissions();
1871 p.set_readonly(true);
1872 check!(fs::set_permissions(&input, p));
1873 check!(fs::copy(&input, &out));
1874 assert!(check!(out.metadata()).permissions().readonly());
1875 check!(fs::set_permissions(&input, attr.permissions()));
1876 check!(fs::set_permissions(&out, attr.permissions()));
1881 fn copy_file_preserves_streams() {
1883 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
1884 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
1885 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
1886 let mut v = Vec::new();
1887 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
1888 assert_eq!(v, b"carrot".to_vec());
1891 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1893 fn symlinks_work() {
1894 let tmpdir = tmpdir();
1895 let input = tmpdir.join("in.txt");
1896 let out = tmpdir.join("out.txt");
1898 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1899 check!(fs::soft_link(&input, &out));
1900 // if cfg!(not(windows)) {
1901 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1902 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1904 assert_eq!(check!(fs::metadata(&out)).len(),
1905 check!(fs::metadata(&input)).len());
1906 let mut v = Vec::new();
1907 check!(check!(File::open(&out)).read_to_end(&mut v));
1908 assert_eq!(v, b"foobar".to_vec());
1911 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1913 fn symlink_noexist() {
1914 let tmpdir = tmpdir();
1915 // symlinks can point to things that don't exist
1916 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1917 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1918 tmpdir.join("foo"));
1922 fn readlink_not_symlink() {
1923 let tmpdir = tmpdir();
1924 match fs::read_link(tmpdir.path()) {
1925 Ok(..) => panic!("wanted a failure"),
1932 let tmpdir = tmpdir();
1933 let input = tmpdir.join("in.txt");
1934 let out = tmpdir.join("out.txt");
1936 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1937 check!(fs::hard_link(&input, &out));
1938 assert_eq!(check!(fs::metadata(&out)).len(),
1939 check!(fs::metadata(&input)).len());
1940 assert_eq!(check!(fs::metadata(&out)).len(),
1941 check!(input.metadata()).len());
1942 let mut v = Vec::new();
1943 check!(check!(File::open(&out)).read_to_end(&mut v));
1944 assert_eq!(v, b"foobar".to_vec());
1946 // can't link to yourself
1947 match fs::hard_link(&input, &input) {
1948 Ok(..) => panic!("wanted a failure"),
1951 // can't link to something that doesn't exist
1952 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1953 Ok(..) => panic!("wanted a failure"),
1960 let tmpdir = tmpdir();
1961 let file = tmpdir.join("in.txt");
1963 check!(File::create(&file));
1964 let attr = check!(fs::metadata(&file));
1965 assert!(!attr.permissions().readonly());
1966 let mut p = attr.permissions();
1967 p.set_readonly(true);
1968 check!(fs::set_permissions(&file, p.clone()));
1969 let attr = check!(fs::metadata(&file));
1970 assert!(attr.permissions().readonly());
1972 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1973 Ok(..) => panic!("wanted an error"),
1977 p.set_readonly(false);
1978 check!(fs::set_permissions(&file, p));
1982 fn sync_doesnt_kill_anything() {
1983 let tmpdir = tmpdir();
1984 let path = tmpdir.join("in.txt");
1986 let mut file = check!(File::create(&path));
1987 check!(file.sync_all());
1988 check!(file.sync_data());
1989 check!(file.write(b"foo"));
1990 check!(file.sync_all());
1991 check!(file.sync_data());
1995 fn truncate_works() {
1996 let tmpdir = tmpdir();
1997 let path = tmpdir.join("in.txt");
1999 let mut file = check!(File::create(&path));
2000 check!(file.write(b"foo"));
2001 check!(file.sync_all());
2003 // Do some simple things with truncation
2004 assert_eq!(check!(file.metadata()).len(), 3);
2005 check!(file.set_len(10));
2006 assert_eq!(check!(file.metadata()).len(), 10);
2007 check!(file.write(b"bar"));
2008 check!(file.sync_all());
2009 assert_eq!(check!(file.metadata()).len(), 10);
2011 let mut v = Vec::new();
2012 check!(check!(File::open(&path)).read_to_end(&mut v));
2013 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2015 // Truncate to a smaller length, don't seek, and then write something.
2016 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2017 // past the end of the file).
2018 check!(file.set_len(2));
2019 assert_eq!(check!(file.metadata()).len(), 2);
2020 check!(file.write(b"wut"));
2021 check!(file.sync_all());
2022 assert_eq!(check!(file.metadata()).len(), 9);
2023 let mut v = Vec::new();
2024 check!(check!(File::open(&path)).read_to_end(&mut v));
2025 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2030 use fs::OpenOptions as OO;
2031 fn c<T: Clone>(t: &T) -> T { t.clone() }
2033 let tmpdir = tmpdir();
2035 let mut r = OO::new(); r.read(true);
2036 let mut w = OO::new(); w.write(true);
2037 let mut rw = OO::new(); rw.write(true).read(true);
2039 match r.open(&tmpdir.join("a")) {
2040 Ok(..) => panic!(), Err(..) => {}
2043 // Perform each one twice to make sure that it succeeds the second time
2044 // (where the file exists)
2045 check!(c(&w).create(true).open(&tmpdir.join("b")));
2046 assert!(tmpdir.join("b").exists());
2047 check!(c(&w).create(true).open(&tmpdir.join("b")));
2048 check!(w.open(&tmpdir.join("b")));
2050 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2051 assert!(tmpdir.join("c").exists());
2052 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2053 check!(rw.open(&tmpdir.join("c")));
2055 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2056 assert!(tmpdir.join("d").exists());
2057 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2058 check!(c(&w).append(true).open(&tmpdir.join("d")));
2060 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2061 assert!(tmpdir.join("e").exists());
2062 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2063 check!(c(&rw).append(true).open(&tmpdir.join("e")));
2065 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2066 assert!(tmpdir.join("f").exists());
2067 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2068 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2070 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2071 assert!(tmpdir.join("g").exists());
2072 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2073 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2075 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2076 check!(r.open(&tmpdir.join("h")));
2078 let mut f = check!(r.open(&tmpdir.join("h")));
2079 assert!(f.write("wut".as_bytes()).is_err());
2081 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2083 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2084 check!(f.write("bar".as_bytes()));
2086 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2088 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2089 check!(f.write("bar".as_bytes()));
2091 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2096 let mut bytes = [0; 1024];
2097 StdRng::new().unwrap().fill_bytes(&mut bytes);
2099 let tmpdir = tmpdir();
2101 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2102 let mut v = Vec::new();
2103 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2104 assert!(v == &bytes[..]);
2108 #[cfg(not(windows))]
2109 fn unlink_readonly() {
2110 let tmpdir = tmpdir();
2111 let path = tmpdir.join("file");
2112 check!(File::create(&path));
2113 let mut perm = check!(fs::metadata(&path)).permissions();
2114 perm.set_readonly(true);
2115 check!(fs::set_permissions(&path, perm));
2116 check!(fs::remove_file(&path));
2120 fn mkdir_trailing_slash() {
2121 let tmpdir = tmpdir();
2122 let path = tmpdir.join("file");
2123 check!(fs::create_dir_all(&path.join("a/")));
2127 fn canonicalize_works_simple() {
2128 let tmpdir = tmpdir();
2129 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2130 let file = tmpdir.join("test");
2131 File::create(&file).unwrap();
2132 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2136 #[cfg(not(windows))]
2137 fn realpath_works() {
2138 let tmpdir = tmpdir();
2139 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2140 let file = tmpdir.join("test");
2141 let dir = tmpdir.join("test2");
2142 let link = dir.join("link");
2143 let linkdir = tmpdir.join("test3");
2145 File::create(&file).unwrap();
2146 fs::create_dir(&dir).unwrap();
2147 fs::soft_link(&file, &link).unwrap();
2148 fs::soft_link(&dir, &linkdir).unwrap();
2150 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2152 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2153 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2154 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2155 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2156 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2160 #[cfg(not(windows))]
2161 fn realpath_works_tricky() {
2162 let tmpdir = tmpdir();
2163 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2165 let a = tmpdir.join("a");
2166 let b = a.join("b");
2167 let c = b.join("c");
2168 let d = a.join("d");
2169 let e = d.join("e");
2170 let f = a.join("f");
2172 fs::create_dir_all(&b).unwrap();
2173 fs::create_dir_all(&d).unwrap();
2174 File::create(&f).unwrap();
2175 fs::soft_link("../d/e", &c).unwrap();
2176 fs::soft_link("../f", &e).unwrap();
2178 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2179 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2183 fn dir_entry_methods() {
2184 let tmpdir = tmpdir();
2186 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2187 File::create(&tmpdir.join("b")).unwrap();
2189 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2190 let fname = file.file_name();
2191 match fname.to_str() {
2193 assert!(file.file_type().unwrap().is_dir());
2194 assert!(file.metadata().unwrap().is_dir());
2197 assert!(file.file_type().unwrap().is_file());
2198 assert!(file.metadata().unwrap().is_file());
2200 f => panic!("unknown file name: {:?}", f),
2206 fn read_dir_not_found() {
2207 let res = fs::read_dir("/path/that/does/not/exist");
2208 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);