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",
96 stack: Vec<io::Result<ReadDir>>,
99 /// Options and flags which can be used to configure how a file is opened.
101 /// This builder exposes the ability to configure how a `File` is opened and
102 /// what operations are permitted on the open file. The `File::open` and
103 /// `File::create` methods are aliases for commonly used options using this
106 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
107 /// then chain calls to methods to set each option, then call `open()`, passing
108 /// the path of the file you're trying to open. This will give you a
109 /// [`io::Result`][result] with a [`File`][file] inside that you can further
112 /// [result]: ../io/type.Result.html
113 /// [file]: struct.File.html
117 /// Opening a file to read:
120 /// use std::fs::OpenOptions;
122 /// let file = OpenOptions::new().read(true).open("foo.txt");
125 /// Opening a file for both reading and writing, as well as creating it if it
129 /// use std::fs::OpenOptions;
131 /// let file = OpenOptions::new()
135 /// .open("foo.txt");
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct OpenOptions(fs_imp::OpenOptions);
141 /// Representation of the various permissions on a file.
143 /// This module only currently provides one bit of information, `readonly`,
144 /// which is exposed on all currently supported platforms. Unix-specific
145 /// functionality, such as mode bits, is available through the
146 /// `os::unix::PermissionsExt` trait.
147 #[derive(Clone, PartialEq, Eq, Debug)]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub struct Permissions(fs_imp::FilePermissions);
151 /// An structure representing a type of file with accessors for each file type.
152 #[stable(feature = "file_type", since = "1.1.0")]
153 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
154 pub struct FileType(fs_imp::FileType);
156 /// A builder used to create directories in various manners.
158 /// This builder also supports platform-specific options.
159 #[unstable(feature = "dir_builder", reason = "recently added API",
161 pub struct DirBuilder {
162 inner: fs_imp::DirBuilder,
167 /// Attempts to open a file in read-only mode.
169 /// See the `OpenOptions::open` method for more details.
173 /// This function will return an error if `path` does not already exist.
174 /// Other errors may also be returned according to `OpenOptions::open`.
179 /// use std::fs::File;
181 /// # fn foo() -> std::io::Result<()> {
182 /// let mut f = try!(File::open("foo.txt"));
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
188 OpenOptions::new().read(true).open(path.as_ref())
191 /// Opens a file in write-only mode.
193 /// This function will create a file if it does not exist,
194 /// and will truncate it if it does.
196 /// See the `OpenOptions::open` function for more details.
201 /// use std::fs::File;
203 /// # fn foo() -> std::io::Result<()> {
204 /// let mut f = try!(File::create("foo.txt"));
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
210 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
213 /// Attempts to sync all OS-internal metadata to disk.
215 /// This function will attempt to ensure that all in-core data reaches the
216 /// filesystem before returning.
221 /// use std::fs::File;
222 /// use std::io::prelude::*;
224 /// # fn foo() -> std::io::Result<()> {
225 /// let mut f = try!(File::create("foo.txt"));
226 /// try!(f.write_all(b"Hello, world!"));
228 /// try!(f.sync_all());
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn sync_all(&self) -> io::Result<()> {
237 /// This function is similar to `sync_all`, except that it may not
238 /// synchronize file metadata to the filesystem.
240 /// This is intended for use cases that must synchronize content, but don't
241 /// need the metadata on disk. The goal of this method is to reduce disk
244 /// Note that some platforms may simply implement this in terms of
250 /// use std::fs::File;
251 /// use std::io::prelude::*;
253 /// # fn foo() -> std::io::Result<()> {
254 /// let mut f = try!(File::create("foo.txt"));
255 /// try!(f.write_all(b"Hello, world!"));
257 /// try!(f.sync_data());
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn sync_data(&self) -> io::Result<()> {
263 self.inner.datasync()
266 /// Truncates or extends the underlying file, updating the size of
267 /// this file to become `size`.
269 /// If the `size` is less than the current file's size, then the file will
270 /// be shrunk. If it is greater than the current file's size, then the file
271 /// will be extended to `size` and have all of the intermediate data filled
276 /// This function will return an error if the file is not opened for writing.
281 /// use std::fs::File;
283 /// # fn foo() -> std::io::Result<()> {
284 /// let mut f = try!(File::create("foo.txt"));
285 /// try!(f.set_len(10));
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn set_len(&self, size: u64) -> io::Result<()> {
291 self.inner.truncate(size)
294 /// Queries metadata about the underlying file.
299 /// use std::fs::File;
301 /// # fn foo() -> std::io::Result<()> {
302 /// let mut f = try!(File::open("foo.txt"));
303 /// let metadata = try!(f.metadata());
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn metadata(&self) -> io::Result<Metadata> {
309 self.inner.file_attr().map(Metadata)
313 impl AsInner<fs_imp::File> for File {
314 fn as_inner(&self) -> &fs_imp::File { &self.inner }
316 impl FromInner<fs_imp::File> for File {
317 fn from_inner(f: fs_imp::File) -> File {
321 impl IntoInner<fs_imp::File> for File {
322 fn into_inner(self) -> fs_imp::File {
327 impl fmt::Debug for File {
328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333 #[stable(feature = "rust1", since = "1.0.0")]
335 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
338 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
339 unsafe { read_to_end_uninitialized(self, buf) }
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl Write for File {
344 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
345 self.inner.write(buf)
347 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
349 #[stable(feature = "rust1", since = "1.0.0")]
351 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl<'a> Read for &'a File {
357 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<'a> Write for &'a File {
363 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
364 self.inner.write(buf)
366 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
368 #[stable(feature = "rust1", since = "1.0.0")]
369 impl<'a> Seek for &'a File {
370 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
376 /// Creates a blank net set of options ready for configuration.
378 /// All options are initially set to `false`.
383 /// use std::fs::OpenOptions;
385 /// let file = OpenOptions::new().open("foo.txt");
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn new() -> OpenOptions {
389 OpenOptions(fs_imp::OpenOptions::new())
392 /// Sets the option for read access.
394 /// This option, when true, will indicate that the file should be
395 /// `read`-able if opened.
400 /// use std::fs::OpenOptions;
402 /// let file = OpenOptions::new().read(true).open("foo.txt");
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
406 self.0.read(read); self
409 /// Sets the option for write access.
411 /// This option, when true, will indicate that the file should be
412 /// `write`-able if opened.
417 /// use std::fs::OpenOptions;
419 /// let file = OpenOptions::new().write(true).open("foo.txt");
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
423 self.0.write(write); self
426 /// Sets the option for the append mode.
428 /// This option, when true, means that writes will append to a file instead
429 /// of overwriting previous contents.
434 /// use std::fs::OpenOptions;
436 /// let file = OpenOptions::new().write(true).append(true).open("foo.txt");
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
440 self.0.append(append); self
443 /// Sets the option for truncating a previous file.
445 /// If a file is successfully opened with this option set it will truncate
446 /// the file to 0 length if it already exists.
451 /// use std::fs::OpenOptions;
453 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
457 self.0.truncate(truncate); self
460 /// Sets the option for creating a new file.
462 /// This option indicates whether a new file will be created if the file
463 /// does not yet already exist.
468 /// use std::fs::OpenOptions;
470 /// let file = OpenOptions::new().create(true).open("foo.txt");
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
474 self.0.create(create); self
477 /// Opens a file at `path` with the options specified by `self`.
481 /// This function will return an error under a number of different
482 /// circumstances, to include but not limited to:
484 /// * Opening a file that does not exist with read access.
485 /// * Attempting to open a file with access that the user lacks
487 /// * Filesystem-level errors (full disk, etc)
492 /// use std::fs::OpenOptions;
494 /// let file = OpenOptions::new().open("foo.txt");
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
498 self._open(path.as_ref())
501 fn _open(&self, path: &Path) -> io::Result<File> {
502 let inner = try!(fs_imp::File::open(path, &self.0));
503 Ok(File { inner: inner })
507 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
508 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
512 /// Returns the file type for this metadata.
513 #[stable(feature = "file_type", since = "1.1.0")]
514 pub fn file_type(&self) -> FileType {
515 FileType(self.0.file_type())
518 /// Returns whether this metadata is for a directory.
523 /// # fn foo() -> std::io::Result<()> {
526 /// let metadata = try!(fs::metadata("foo.txt"));
528 /// assert!(!metadata.is_dir());
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
535 /// Returns whether this metadata is for a regular file.
540 /// # fn foo() -> std::io::Result<()> {
543 /// let metadata = try!(fs::metadata("foo.txt"));
545 /// assert!(metadata.is_file());
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn is_file(&self) -> bool { self.file_type().is_file() }
552 /// Returns the size of the file, in bytes, this metadata is for.
557 /// # fn foo() -> std::io::Result<()> {
560 /// let metadata = try!(fs::metadata("foo.txt"));
562 /// assert_eq!(0, metadata.len());
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn len(&self) -> u64 { self.0.size() }
569 /// Returns the permissions of the file this metadata is for.
574 /// # fn foo() -> std::io::Result<()> {
577 /// let metadata = try!(fs::metadata("foo.txt"));
579 /// assert!(!metadata.permissions().readonly());
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn permissions(&self) -> Permissions {
585 Permissions(self.0.perm())
589 impl AsInner<fs_imp::FileAttr> for Metadata {
590 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
594 /// Returns whether these permissions describe a readonly file.
599 /// use std::fs::File;
601 /// # fn foo() -> std::io::Result<()> {
602 /// let mut f = try!(File::create("foo.txt"));
603 /// let metadata = try!(f.metadata());
605 /// assert_eq!(false, metadata.permissions().readonly());
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn readonly(&self) -> bool { self.0.readonly() }
612 /// Modifies the readonly flag for this set of permissions.
614 /// This operation does **not** modify the filesystem. To modify the
615 /// filesystem use the `fs::set_permissions` function.
620 /// use std::fs::File;
622 /// # fn foo() -> std::io::Result<()> {
623 /// let f = try!(File::create("foo.txt"));
624 /// let metadata = try!(f.metadata());
625 /// let mut permissions = metadata.permissions();
627 /// permissions.set_readonly(true);
629 /// // filesystem doesn't change
630 /// assert_eq!(false, metadata.permissions().readonly());
632 /// // just this particular `permissions`.
633 /// assert_eq!(true, permissions.readonly());
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn set_readonly(&mut self, readonly: bool) {
639 self.0.set_readonly(readonly)
644 /// Test whether this file type represents a directory.
645 #[stable(feature = "file_type", since = "1.1.0")]
646 pub fn is_dir(&self) -> bool { self.0.is_dir() }
648 /// Test whether this file type represents a regular file.
649 #[stable(feature = "file_type", since = "1.1.0")]
650 pub fn is_file(&self) -> bool { self.0.is_file() }
652 /// Test whether this file type represents a symbolic link.
653 #[stable(feature = "file_type", since = "1.1.0")]
654 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
657 impl AsInner<fs_imp::FileType> for FileType {
658 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
661 impl FromInner<fs_imp::FilePermissions> for Permissions {
662 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
667 impl AsInner<fs_imp::FilePermissions> for Permissions {
668 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl Iterator for ReadDir {
673 type Item = io::Result<DirEntry>;
675 fn next(&mut self) -> Option<io::Result<DirEntry>> {
676 self.0.next().map(|entry| entry.map(DirEntry))
680 #[stable(feature = "rust1", since = "1.0.0")]
682 /// Returns the full path to the file that this entry represents.
684 /// The full path is created by joining the original path to `read_dir` or
685 /// `walk_dir` with the filename of this entry.
691 /// # fn foo() -> std::io::Result<()> {
692 /// for entry in try!(fs::read_dir(".")) {
693 /// let dir = try!(entry);
694 /// println!("{:?}", dir.path());
700 /// This prints output like:
705 /// "./hello_world.rs"
708 /// The exact text, of course, depends on what files you have in `.`.
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn path(&self) -> PathBuf { self.0.path() }
712 /// Return the metadata for the file that this entry points at.
714 /// This function will not traverse symlinks if this entry points at a
717 /// # Platform behavior
719 /// On Windows this function is cheap to call (no extra system calls
720 /// needed), but on Unix platforms this function is the equivalent of
721 /// calling `symlink_metadata` on the path.
722 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
723 pub fn metadata(&self) -> io::Result<Metadata> {
724 self.0.metadata().map(Metadata)
727 /// Return the file type for the file that this entry points at.
729 /// This function will not traverse symlinks if this entry points at a
732 /// # Platform behavior
734 /// On Windows and most Unix platforms this function is free (no extra
735 /// system calls needed), but some Unix platforms may require the equivalent
736 /// call to `symlink_metadata` to learn about the target file type.
737 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
738 pub fn file_type(&self) -> io::Result<FileType> {
739 self.0.file_type().map(FileType)
742 /// Returns the bare file name of this directory entry without any other
743 /// leading path component.
744 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
745 pub fn file_name(&self) -> OsString {
750 impl AsInner<fs_imp::DirEntry> for DirEntry {
751 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
754 /// Removes a file from the filesystem.
756 /// Note that there is no
757 /// guarantee that the file is immediately deleted (e.g. depending on
758 /// platform, other open file descriptors may prevent immediate removal).
762 /// This function will return an error if `path` points to a directory, if the
763 /// user lacks permissions to remove the file, or if some other filesystem-level
771 /// # fn foo() -> std::io::Result<()> {
772 /// try!(fs::remove_file("a.txt"));
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
778 fs_imp::unlink(path.as_ref())
781 /// Given a path, query the file system to get information about a file,
784 /// This function will traverse symbolic links to query information about the
785 /// destination file.
790 /// # fn foo() -> std::io::Result<()> {
793 /// let attr = try!(fs::metadata("/some/file/path.txt"));
794 /// // inspect attr ...
801 /// This function will return an error if the user lacks the requisite
802 /// permissions to perform a `metadata` call on the given `path` or if there
803 /// is no entry in the filesystem at the provided path.
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
806 fs_imp::stat(path.as_ref()).map(Metadata)
809 /// Query the metadata about a file without following symlinks.
814 /// # fn foo() -> std::io::Result<()> {
817 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
818 /// // inspect attr ...
822 #[stable(feature = "symlink_metadata", since = "1.1.0")]
823 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
824 fs_imp::lstat(path.as_ref()).map(Metadata)
827 /// Rename a file or directory to a new name.
829 /// This will not work if the new name is on a different mount point.
833 /// This function will return an error if the provided `from` doesn't exist, if
834 /// the process lacks permissions to view the contents, if `from` and `to`
835 /// reside on separate filesystems, or if some other intermittent I/O error
843 /// # fn foo() -> std::io::Result<()> {
844 /// try!(fs::rename("a.txt", "b.txt"));
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
850 fs_imp::rename(from.as_ref(), to.as_ref())
853 /// Copies the contents of one file to another. This function will also
854 /// copy the permission bits of the original file to the destination file.
856 /// This function will **overwrite** the contents of `to`.
858 /// Note that if `from` and `to` both point to the same file, then the file
859 /// will likely get truncated by this operation.
861 /// On success, the total number of bytes copied is returned.
865 /// This function will return an error in the following situations, but is not
866 /// limited to just these cases:
868 /// * The `from` path is not a file
869 /// * The `from` file does not exist
870 /// * The current process does not have the permission rights to access
871 /// `from` or write `to`
878 /// # fn foo() -> std::io::Result<()> {
879 /// try!(fs::copy("foo.txt", "bar.txt"));
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
884 fs_imp::copy(from.as_ref(), to.as_ref())
887 /// Creates a new hard link on the filesystem.
889 /// The `dst` path will be a link pointing to the `src` path. Note that systems
890 /// often require these two paths to both be located on the same filesystem.
897 /// # fn foo() -> std::io::Result<()> {
898 /// try!(fs::hard_link("a.txt", "b.txt"));
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
904 fs_imp::link(src.as_ref(), dst.as_ref())
907 /// Creates a new symbolic link on the filesystem.
909 /// The `dst` path will be a symbolic link pointing to the `src` path.
910 /// On Windows, this will be a file symlink, not a directory symlink;
911 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
912 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
913 /// used instead to make the intent explicit.
920 /// # fn foo() -> std::io::Result<()> {
921 /// try!(fs::soft_link("a.txt", "b.txt"));
925 #[deprecated(since = "1.1.0",
926 reason = "replaced with std::os::unix::fs::symlink and \
927 std::os::windows::fs::{symlink_file, symlink_dir}")]
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
930 fs_imp::symlink(src.as_ref(), dst.as_ref())
933 /// Reads a symbolic link, returning the file that the link points to.
937 /// This function will return an error on failure. Failure conditions include
938 /// reading a file that does not exist or reading a file that is not a symbolic
946 /// # fn foo() -> std::io::Result<()> {
947 /// let path = try!(fs::read_link("a.txt"));
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
953 fs_imp::readlink(path.as_ref())
956 /// Returns the canonical form of a path with all intermediate components
957 /// normalized and symbolic links resolved.
958 #[unstable(feature = "fs_canonicalize", reason = "recently added API",
960 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
961 fs_imp::canonicalize(path.as_ref())
964 /// Creates a new, empty directory at the provided path
968 /// This function will return an error if the user lacks permissions to make a
969 /// new directory at the provided `path`, or if the directory already exists.
976 /// # fn foo() -> std::io::Result<()> {
977 /// try!(fs::create_dir("/some/dir"));
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
983 DirBuilder::new().create(path.as_ref())
986 /// Recursively create a directory and all of its parent components if they
991 /// This function will fail if any directory in the path specified by `path`
992 /// does not already exist and it could not be created otherwise. The specific
993 /// error conditions for when a directory is being created (after it is
994 /// determined to not exist) are outlined by `fs::create_dir`.
1001 /// # fn foo() -> std::io::Result<()> {
1002 /// try!(fs::create_dir_all("/some/dir"));
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1008 DirBuilder::new().recursive(true).create(path.as_ref())
1011 /// Removes an existing, empty directory.
1015 /// This function will return an error if the user lacks permissions to remove
1016 /// the directory at the provided `path`, or if the directory isn't empty.
1023 /// # fn foo() -> std::io::Result<()> {
1024 /// try!(fs::remove_dir("/some/dir"));
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1030 fs_imp::rmdir(path.as_ref())
1033 /// Removes a directory at this path, after removing all its contents. Use
1036 /// This function does **not** follow symbolic links and it will simply remove the
1037 /// symbolic link itself.
1041 /// See `file::remove_file` and `fs::remove_dir`.
1048 /// # fn foo() -> std::io::Result<()> {
1049 /// try!(fs::remove_dir_all("/some/dir"));
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1055 _remove_dir_all(path.as_ref())
1058 fn _remove_dir_all(path: &Path) -> io::Result<()> {
1059 for child in try!(read_dir(path)) {
1060 let child = try!(child).path();
1061 let stat = try!(symlink_metadata(&*child));
1063 try!(remove_dir_all(&*child));
1065 try!(remove_file(&*child));
1071 /// Returns an iterator over the entries within a directory.
1073 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1074 /// be encountered after an iterator is initially constructed.
1080 /// use std::fs::{self, DirEntry};
1081 /// use std::path::Path;
1083 /// // one possible implementation of fs::walk_dir only visiting files
1084 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1085 /// if try!(fs::metadata(dir)).is_dir() {
1086 /// for entry in try!(fs::read_dir(dir)) {
1087 /// let entry = try!(entry);
1088 /// if try!(fs::metadata(entry.path())).is_dir() {
1089 /// try!(visit_dirs(&entry.path(), cb));
1101 /// This function will return an error if the provided `path` doesn't exist, if
1102 /// the process lacks permissions to view the contents or if the `path` points
1103 /// at a non-directory file
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1106 fs_imp::readdir(path.as_ref()).map(ReadDir)
1109 /// Returns an iterator that will recursively walk the directory structure
1110 /// rooted at `path`.
1112 /// The path given will not be iterated over, and this will perform iteration in
1113 /// some top-down order. The contents of unreadable subdirectories are ignored.
1115 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1116 /// be encountered after an iterator is initially constructed.
1117 #[unstable(feature = "fs_walk",
1118 reason = "the precise semantics and defaults for a recursive walk \
1119 may change and this may end up accounting for files such \
1120 as symlinks differently",
1122 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1123 _walk_dir(path.as_ref())
1126 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1127 let start = try!(read_dir(path));
1128 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1131 #[unstable(feature = "fs_walk", issue = "27707")]
1132 impl Iterator for WalkDir {
1133 type Item = io::Result<DirEntry>;
1135 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1137 if let Some(ref mut cur) = self.cur {
1139 Some(Err(e)) => return Some(Err(e)),
1141 let path = next.path();
1143 self.stack.push(read_dir(&*path));
1145 return Some(Ok(next))
1151 match self.stack.pop() {
1152 Some(Err(e)) => return Some(Err(e)),
1153 Some(Ok(next)) => self.cur = Some(next),
1154 None => return None,
1160 /// Utility methods for paths.
1161 #[unstable(feature = "path_ext",
1162 reason = "The precise set of methods exposed on this trait may \
1163 change and some methods may be removed. For stable code, \
1164 see the std::fs::metadata function.",
1167 /// Gets information on the file, directory, etc at this path.
1169 /// Consult the `fs::metadata` documentation for more info.
1171 /// This call preserves identical runtime/error semantics with
1173 fn metadata(&self) -> io::Result<Metadata>;
1175 /// Gets information on the file, directory, etc at this path.
1177 /// Consult the `fs::symlink_metadata` documentation for more info.
1179 /// This call preserves identical runtime/error semantics with
1180 /// `fs::symlink_metadata`.
1181 fn symlink_metadata(&self) -> io::Result<Metadata>;
1183 /// Returns the canonical form of a path, normalizing all components and
1184 /// eliminate all symlinks.
1186 /// This call preserves identical runtime/error semantics with
1187 /// `fs::canonicalize`.
1188 fn canonicalize(&self) -> io::Result<PathBuf>;
1190 /// Reads the symlink at this path.
1192 /// For more information see `fs::read_link`.
1193 fn read_link(&self) -> io::Result<PathBuf>;
1195 /// Reads the directory at this path.
1197 /// For more information see `fs::read_dir`.
1198 fn read_dir(&self) -> io::Result<ReadDir>;
1200 /// Boolean value indicator whether the underlying file exists on the local
1201 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1202 fn exists(&self) -> bool;
1204 /// Whether the underlying implementation (be it a file path, or something
1205 /// else) points at a "regular file" on the FS. Will return false for paths
1206 /// to non-existent locations or directories or other non-regular files
1207 /// (named pipes, etc). Follows links when making this determination.
1208 fn is_file(&self) -> bool;
1210 /// Whether the underlying implementation (be it a file path, or something
1211 /// else) is pointing at a directory in the underlying FS. Will return
1212 /// false for paths to non-existent locations or if the item is not a
1213 /// directory (eg files, named pipes, etc). Follows links when making this
1215 fn is_dir(&self) -> bool;
1218 impl PathExt for Path {
1219 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1220 fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1221 fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1222 fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1223 fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1224 fn exists(&self) -> bool { metadata(self).is_ok() }
1226 fn is_file(&self) -> bool {
1227 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1230 fn is_dir(&self) -> bool {
1231 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1235 /// Changes the permissions found on a file or a directory.
1240 /// # fn foo() -> std::io::Result<()> {
1243 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1244 /// perms.set_readonly(true);
1245 /// try!(fs::set_permissions("foo.txt", perms));
1252 /// This function will return an error if the provided `path` doesn't exist, if
1253 /// the process lacks permissions to change the attributes of the file, or if
1254 /// some other I/O error is encountered.
1255 #[stable(feature = "set_permissions", since = "1.1.0")]
1256 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1258 fs_imp::set_perm(path.as_ref(), perm.0)
1261 #[unstable(feature = "dir_builder", reason = "recently added API",
1264 /// Creates a new set of options with default mode/security settings for all
1265 /// platforms and also non-recursive.
1266 pub fn new() -> DirBuilder {
1268 inner: fs_imp::DirBuilder::new(),
1273 /// Indicate that directories create should be created recursively, creating
1274 /// all parent directories if they do not exist with the same security and
1275 /// permissions settings.
1277 /// This option defaults to `false`
1278 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1279 self.recursive = recursive;
1283 /// Create the specified directory with the options configured in this
1285 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1286 self._create(path.as_ref())
1289 fn _create(&self, path: &Path) -> io::Result<()> {
1291 self.create_dir_all(path)
1293 self.inner.mkdir(path)
1297 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1298 if path == Path::new("") || path.is_dir() { return Ok(()) }
1299 if let Some(p) = path.parent() {
1300 try!(self.create_dir_all(p))
1302 self.inner.mkdir(path)
1306 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1307 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1314 #![allow(deprecated)] //rand
1320 use fs::{self, File, OpenOptions};
1321 use io::{ErrorKind, SeekFrom};
1323 use path::Path as Path2;
1325 use rand::{self, StdRng, Rng};
1328 macro_rules! check { ($e:expr) => (
1331 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1335 macro_rules! error { ($e:expr, $s:expr) => (
1337 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1338 Err(ref err) => assert!(err.to_string().contains($s),
1339 format!("`{}` did not contain `{}`", err, $s))
1343 pub struct TempDir(PathBuf);
1346 fn join(&self, path: &str) -> PathBuf {
1347 let TempDir(ref p) = *self;
1351 fn path<'a>(&'a self) -> &'a Path2 {
1352 let TempDir(ref p) = *self;
1357 impl Drop for TempDir {
1358 fn drop(&mut self) {
1359 // Gee, seeing how we're testing the fs module I sure hope that we
1360 // at least implement this correctly!
1361 let TempDir(ref p) = *self;
1362 check!(fs::remove_dir_all(p));
1366 pub fn tmpdir() -> TempDir {
1367 let p = env::temp_dir();
1368 let mut r = rand::thread_rng();
1369 let ret = p.join(&format!("rust-{}", r.next_u32()));
1370 check!(fs::create_dir(&ret));
1375 fn file_test_io_smoke_test() {
1376 let message = "it's alright. have a good time";
1377 let tmpdir = tmpdir();
1378 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1380 let mut write_stream = check!(File::create(filename));
1381 check!(write_stream.write(message.as_bytes()));
1384 let mut read_stream = check!(File::open(filename));
1385 let mut read_buf = [0; 1028];
1386 let read_str = match check!(read_stream.read(&mut read_buf)) {
1387 0 => panic!("shouldn't happen"),
1388 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1390 assert_eq!(read_str, message);
1392 check!(fs::remove_file(filename));
1396 fn invalid_path_raises() {
1397 let tmpdir = tmpdir();
1398 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1399 let result = File::open(filename);
1402 error!(result, "o such file or directory");
1404 // error!(result, "couldn't open path as file");
1405 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1409 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1410 let tmpdir = tmpdir();
1411 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1413 let result = fs::remove_file(filename);
1416 error!(result, "o such file or directory");
1418 // error!(result, "couldn't unlink path");
1419 // error!(result, format!("path={}", filename.display()));
1423 fn file_test_io_non_positional_read() {
1424 let message: &str = "ten-four";
1425 let mut read_mem = [0; 8];
1426 let tmpdir = tmpdir();
1427 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1429 let mut rw_stream = check!(File::create(filename));
1430 check!(rw_stream.write(message.as_bytes()));
1433 let mut read_stream = check!(File::open(filename));
1435 let read_buf = &mut read_mem[0..4];
1436 check!(read_stream.read(read_buf));
1439 let read_buf = &mut read_mem[4..8];
1440 check!(read_stream.read(read_buf));
1443 check!(fs::remove_file(filename));
1444 let read_str = str::from_utf8(&read_mem).unwrap();
1445 assert_eq!(read_str, message);
1449 fn file_test_io_seek_and_tell_smoke_test() {
1450 let message = "ten-four";
1451 let mut read_mem = [0; 4];
1452 let set_cursor = 4 as u64;
1453 let mut tell_pos_pre_read;
1454 let mut tell_pos_post_read;
1455 let tmpdir = tmpdir();
1456 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1458 let mut rw_stream = check!(File::create(filename));
1459 check!(rw_stream.write(message.as_bytes()));
1462 let mut read_stream = check!(File::open(filename));
1463 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1464 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1465 check!(read_stream.read(&mut read_mem));
1466 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1468 check!(fs::remove_file(filename));
1469 let read_str = str::from_utf8(&read_mem).unwrap();
1470 assert_eq!(read_str, &message[4..8]);
1471 assert_eq!(tell_pos_pre_read, set_cursor);
1472 assert_eq!(tell_pos_post_read, message.len() as u64);
1476 fn file_test_io_seek_and_write() {
1477 let initial_msg = "food-is-yummy";
1478 let overwrite_msg = "-the-bar!!";
1479 let final_msg = "foo-the-bar!!";
1481 let mut read_mem = [0; 13];
1482 let tmpdir = tmpdir();
1483 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1485 let mut rw_stream = check!(File::create(filename));
1486 check!(rw_stream.write(initial_msg.as_bytes()));
1487 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1488 check!(rw_stream.write(overwrite_msg.as_bytes()));
1491 let mut read_stream = check!(File::open(filename));
1492 check!(read_stream.read(&mut read_mem));
1494 check!(fs::remove_file(filename));
1495 let read_str = str::from_utf8(&read_mem).unwrap();
1496 assert!(read_str == final_msg);
1500 fn file_test_io_seek_shakedown() {
1502 let initial_msg = "qwer-asdf-zxcv";
1503 let chunk_one: &str = "qwer";
1504 let chunk_two: &str = "asdf";
1505 let chunk_three: &str = "zxcv";
1506 let mut read_mem = [0; 4];
1507 let tmpdir = tmpdir();
1508 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1510 let mut rw_stream = check!(File::create(filename));
1511 check!(rw_stream.write(initial_msg.as_bytes()));
1514 let mut read_stream = check!(File::open(filename));
1516 check!(read_stream.seek(SeekFrom::End(-4)));
1517 check!(read_stream.read(&mut read_mem));
1518 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1520 check!(read_stream.seek(SeekFrom::Current(-9)));
1521 check!(read_stream.read(&mut read_mem));
1522 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1524 check!(read_stream.seek(SeekFrom::Start(0)));
1525 check!(read_stream.read(&mut read_mem));
1526 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1528 check!(fs::remove_file(filename));
1532 fn file_test_stat_is_correct_on_is_file() {
1533 let tmpdir = tmpdir();
1534 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1536 let mut opts = OpenOptions::new();
1537 let mut fs = check!(opts.read(true).write(true)
1538 .create(true).open(filename));
1540 fs.write(msg.as_bytes()).unwrap();
1542 let fstat_res = check!(fs.metadata());
1543 assert!(fstat_res.is_file());
1545 let stat_res_fn = check!(fs::metadata(filename));
1546 assert!(stat_res_fn.is_file());
1547 let stat_res_meth = check!(filename.metadata());
1548 assert!(stat_res_meth.is_file());
1549 check!(fs::remove_file(filename));
1553 fn file_test_stat_is_correct_on_is_dir() {
1554 let tmpdir = tmpdir();
1555 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1556 check!(fs::create_dir(filename));
1557 let stat_res_fn = check!(fs::metadata(filename));
1558 assert!(stat_res_fn.is_dir());
1559 let stat_res_meth = check!(filename.metadata());
1560 assert!(stat_res_meth.is_dir());
1561 check!(fs::remove_dir(filename));
1565 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1566 let tmpdir = tmpdir();
1567 let dir = &tmpdir.join("fileinfo_false_on_dir");
1568 check!(fs::create_dir(dir));
1569 assert!(dir.is_file() == false);
1570 check!(fs::remove_dir(dir));
1574 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1575 let tmpdir = tmpdir();
1576 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1577 check!(check!(File::create(file)).write(b"foo"));
1578 assert!(file.exists());
1579 check!(fs::remove_file(file));
1580 assert!(!file.exists());
1584 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1585 let tmpdir = tmpdir();
1586 let dir = &tmpdir.join("before_and_after_dir");
1587 assert!(!dir.exists());
1588 check!(fs::create_dir(dir));
1589 assert!(dir.exists());
1590 assert!(dir.is_dir());
1591 check!(fs::remove_dir(dir));
1592 assert!(!dir.exists());
1596 fn file_test_directoryinfo_readdir() {
1597 let tmpdir = tmpdir();
1598 let dir = &tmpdir.join("di_readdir");
1599 check!(fs::create_dir(dir));
1602 let f = dir.join(&format!("{}.txt", n));
1603 let mut w = check!(File::create(&f));
1604 let msg_str = format!("{}{}", prefix, n.to_string());
1605 let msg = msg_str.as_bytes();
1606 check!(w.write(msg));
1608 let files = check!(fs::read_dir(dir));
1609 let mut mem = [0; 4];
1611 let f = f.unwrap().path();
1613 let n = f.file_stem().unwrap();
1614 check!(check!(File::open(&f)).read(&mut mem));
1615 let read_str = str::from_utf8(&mem).unwrap();
1616 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1617 assert_eq!(expected, read_str);
1619 check!(fs::remove_file(&f));
1621 check!(fs::remove_dir(dir));
1625 fn file_test_walk_dir() {
1626 let tmpdir = tmpdir();
1627 let dir = &tmpdir.join("walk_dir");
1628 check!(fs::create_dir(dir));
1630 let dir1 = &dir.join("01/02/03");
1631 check!(fs::create_dir_all(dir1));
1632 check!(File::create(&dir1.join("04")));
1634 let dir2 = &dir.join("11/12/13");
1635 check!(fs::create_dir_all(dir2));
1636 check!(File::create(&dir2.join("14")));
1638 let files = check!(fs::walk_dir(dir));
1639 let mut cur = [0; 2];
1641 let f = f.unwrap().path();
1642 let stem = f.file_stem().unwrap().to_str().unwrap();
1643 let root = stem.as_bytes()[0] - b'0';
1644 let name = stem.as_bytes()[1] - b'0';
1645 assert!(cur[root as usize] < name);
1646 cur[root as usize] = name;
1649 check!(fs::remove_dir_all(dir));
1653 fn mkdir_path_already_exists_error() {
1654 let tmpdir = tmpdir();
1655 let dir = &tmpdir.join("mkdir_error_twice");
1656 check!(fs::create_dir(dir));
1657 let e = fs::create_dir(dir).err().unwrap();
1658 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1662 fn recursive_mkdir() {
1663 let tmpdir = tmpdir();
1664 let dir = tmpdir.join("d1/d2");
1665 check!(fs::create_dir_all(&dir));
1666 assert!(dir.is_dir())
1670 fn recursive_mkdir_failure() {
1671 let tmpdir = tmpdir();
1672 let dir = tmpdir.join("d1");
1673 let file = dir.join("f1");
1675 check!(fs::create_dir_all(&dir));
1676 check!(File::create(&file));
1678 let result = fs::create_dir_all(&file);
1680 assert!(result.is_err());
1681 // error!(result, "couldn't recursively mkdir");
1682 // error!(result, "couldn't create directory");
1683 // error!(result, "mode=0700");
1684 // error!(result, format!("path={}", file.display()));
1688 fn recursive_mkdir_slash() {
1689 check!(fs::create_dir_all(&Path2::new("/")));
1692 // FIXME(#12795) depends on lstat to work on windows
1693 #[cfg(not(windows))]
1695 fn recursive_rmdir() {
1696 let tmpdir = tmpdir();
1697 let d1 = tmpdir.join("d1");
1698 let dt = d1.join("t");
1699 let dtt = dt.join("t");
1700 let d2 = tmpdir.join("d2");
1701 let canary = d2.join("do_not_delete");
1702 check!(fs::create_dir_all(&dtt));
1703 check!(fs::create_dir_all(&d2));
1704 check!(check!(File::create(&canary)).write(b"foo"));
1705 check!(fs::soft_link(&d2, &dt.join("d2")));
1706 check!(fs::remove_dir_all(&d1));
1708 assert!(!d1.is_dir());
1709 assert!(canary.exists());
1713 fn unicode_path_is_dir() {
1714 assert!(Path2::new(".").is_dir());
1715 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1717 let tmpdir = tmpdir();
1719 let mut dirpath = tmpdir.path().to_path_buf();
1720 dirpath.push(&format!("test-가一ー你好"));
1721 check!(fs::create_dir(&dirpath));
1722 assert!(dirpath.is_dir());
1724 let mut filepath = dirpath;
1725 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1726 check!(File::create(&filepath)); // ignore return; touch only
1727 assert!(!filepath.is_dir());
1728 assert!(filepath.exists());
1732 fn unicode_path_exists() {
1733 assert!(Path2::new(".").exists());
1734 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1736 let tmpdir = tmpdir();
1737 let unicode = tmpdir.path();
1738 let unicode = unicode.join(&format!("test-각丁ー再见"));
1739 check!(fs::create_dir(&unicode));
1740 assert!(unicode.exists());
1741 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1745 fn copy_file_does_not_exist() {
1746 let from = Path2::new("test/nonexistent-bogus-path");
1747 let to = Path2::new("test/other-bogus-path");
1749 match fs::copy(&from, &to) {
1752 assert!(!from.exists());
1753 assert!(!to.exists());
1759 fn copy_src_does_not_exist() {
1760 let tmpdir = tmpdir();
1761 let from = Path2::new("test/nonexistent-bogus-path");
1762 let to = tmpdir.join("out.txt");
1763 check!(check!(File::create(&to)).write(b"hello"));
1764 assert!(fs::copy(&from, &to).is_err());
1765 assert!(!from.exists());
1766 let mut v = Vec::new();
1767 check!(check!(File::open(&to)).read_to_end(&mut v));
1768 assert_eq!(v, b"hello");
1773 let tmpdir = tmpdir();
1774 let input = tmpdir.join("in.txt");
1775 let out = tmpdir.join("out.txt");
1777 check!(check!(File::create(&input)).write(b"hello"));
1778 check!(fs::copy(&input, &out));
1779 let mut v = Vec::new();
1780 check!(check!(File::open(&out)).read_to_end(&mut v));
1781 assert_eq!(v, b"hello");
1783 assert_eq!(check!(input.metadata()).permissions(),
1784 check!(out.metadata()).permissions());
1788 fn copy_file_dst_dir() {
1789 let tmpdir = tmpdir();
1790 let out = tmpdir.join("out");
1792 check!(File::create(&out));
1793 match fs::copy(&*out, tmpdir.path()) {
1794 Ok(..) => panic!(), Err(..) => {}
1799 fn copy_file_dst_exists() {
1800 let tmpdir = tmpdir();
1801 let input = tmpdir.join("in");
1802 let output = tmpdir.join("out");
1804 check!(check!(File::create(&input)).write("foo".as_bytes()));
1805 check!(check!(File::create(&output)).write("bar".as_bytes()));
1806 check!(fs::copy(&input, &output));
1808 let mut v = Vec::new();
1809 check!(check!(File::open(&output)).read_to_end(&mut v));
1810 assert_eq!(v, b"foo".to_vec());
1814 fn copy_file_src_dir() {
1815 let tmpdir = tmpdir();
1816 let out = tmpdir.join("out");
1818 match fs::copy(tmpdir.path(), &out) {
1819 Ok(..) => panic!(), Err(..) => {}
1821 assert!(!out.exists());
1825 fn copy_file_preserves_perm_bits() {
1826 let tmpdir = tmpdir();
1827 let input = tmpdir.join("in.txt");
1828 let out = tmpdir.join("out.txt");
1830 let attr = check!(check!(File::create(&input)).metadata());
1831 let mut p = attr.permissions();
1832 p.set_readonly(true);
1833 check!(fs::set_permissions(&input, p));
1834 check!(fs::copy(&input, &out));
1835 assert!(check!(out.metadata()).permissions().readonly());
1836 check!(fs::set_permissions(&input, attr.permissions()));
1837 check!(fs::set_permissions(&out, attr.permissions()));
1842 fn copy_file_preserves_streams() {
1844 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
1845 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
1846 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
1847 let mut v = Vec::new();
1848 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
1849 assert_eq!(v, b"carrot".to_vec());
1852 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1854 fn symlinks_work() {
1855 let tmpdir = tmpdir();
1856 let input = tmpdir.join("in.txt");
1857 let out = tmpdir.join("out.txt");
1859 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1860 check!(fs::soft_link(&input, &out));
1861 // if cfg!(not(windows)) {
1862 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1863 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1865 assert_eq!(check!(fs::metadata(&out)).len(),
1866 check!(fs::metadata(&input)).len());
1867 let mut v = Vec::new();
1868 check!(check!(File::open(&out)).read_to_end(&mut v));
1869 assert_eq!(v, b"foobar".to_vec());
1872 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1874 fn symlink_noexist() {
1875 let tmpdir = tmpdir();
1876 // symlinks can point to things that don't exist
1877 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1878 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1879 tmpdir.join("foo"));
1883 fn readlink_not_symlink() {
1884 let tmpdir = tmpdir();
1885 match fs::read_link(tmpdir.path()) {
1886 Ok(..) => panic!("wanted a failure"),
1893 let tmpdir = tmpdir();
1894 let input = tmpdir.join("in.txt");
1895 let out = tmpdir.join("out.txt");
1897 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1898 check!(fs::hard_link(&input, &out));
1899 assert_eq!(check!(fs::metadata(&out)).len(),
1900 check!(fs::metadata(&input)).len());
1901 assert_eq!(check!(fs::metadata(&out)).len(),
1902 check!(input.metadata()).len());
1903 let mut v = Vec::new();
1904 check!(check!(File::open(&out)).read_to_end(&mut v));
1905 assert_eq!(v, b"foobar".to_vec());
1907 // can't link to yourself
1908 match fs::hard_link(&input, &input) {
1909 Ok(..) => panic!("wanted a failure"),
1912 // can't link to something that doesn't exist
1913 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1914 Ok(..) => panic!("wanted a failure"),
1921 let tmpdir = tmpdir();
1922 let file = tmpdir.join("in.txt");
1924 check!(File::create(&file));
1925 let attr = check!(fs::metadata(&file));
1926 assert!(!attr.permissions().readonly());
1927 let mut p = attr.permissions();
1928 p.set_readonly(true);
1929 check!(fs::set_permissions(&file, p.clone()));
1930 let attr = check!(fs::metadata(&file));
1931 assert!(attr.permissions().readonly());
1933 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1934 Ok(..) => panic!("wanted an error"),
1938 p.set_readonly(false);
1939 check!(fs::set_permissions(&file, p));
1943 fn sync_doesnt_kill_anything() {
1944 let tmpdir = tmpdir();
1945 let path = tmpdir.join("in.txt");
1947 let mut file = check!(File::create(&path));
1948 check!(file.sync_all());
1949 check!(file.sync_data());
1950 check!(file.write(b"foo"));
1951 check!(file.sync_all());
1952 check!(file.sync_data());
1956 fn truncate_works() {
1957 let tmpdir = tmpdir();
1958 let path = tmpdir.join("in.txt");
1960 let mut file = check!(File::create(&path));
1961 check!(file.write(b"foo"));
1962 check!(file.sync_all());
1964 // Do some simple things with truncation
1965 assert_eq!(check!(file.metadata()).len(), 3);
1966 check!(file.set_len(10));
1967 assert_eq!(check!(file.metadata()).len(), 10);
1968 check!(file.write(b"bar"));
1969 check!(file.sync_all());
1970 assert_eq!(check!(file.metadata()).len(), 10);
1972 let mut v = Vec::new();
1973 check!(check!(File::open(&path)).read_to_end(&mut v));
1974 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1976 // Truncate to a smaller length, don't seek, and then write something.
1977 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1978 // past the end of the file).
1979 check!(file.set_len(2));
1980 assert_eq!(check!(file.metadata()).len(), 2);
1981 check!(file.write(b"wut"));
1982 check!(file.sync_all());
1983 assert_eq!(check!(file.metadata()).len(), 9);
1984 let mut v = Vec::new();
1985 check!(check!(File::open(&path)).read_to_end(&mut v));
1986 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1991 use fs::OpenOptions as OO;
1992 fn c<T: Clone>(t: &T) -> T { t.clone() }
1994 let tmpdir = tmpdir();
1996 let mut r = OO::new(); r.read(true);
1997 let mut w = OO::new(); w.write(true);
1998 let mut rw = OO::new(); rw.write(true).read(true);
2000 match r.open(&tmpdir.join("a")) {
2001 Ok(..) => panic!(), Err(..) => {}
2004 // Perform each one twice to make sure that it succeeds the second time
2005 // (where the file exists)
2006 check!(c(&w).create(true).open(&tmpdir.join("b")));
2007 assert!(tmpdir.join("b").exists());
2008 check!(c(&w).create(true).open(&tmpdir.join("b")));
2009 check!(w.open(&tmpdir.join("b")));
2011 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2012 assert!(tmpdir.join("c").exists());
2013 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2014 check!(rw.open(&tmpdir.join("c")));
2016 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2017 assert!(tmpdir.join("d").exists());
2018 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2019 check!(c(&w).append(true).open(&tmpdir.join("d")));
2021 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2022 assert!(tmpdir.join("e").exists());
2023 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2024 check!(c(&rw).append(true).open(&tmpdir.join("e")));
2026 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2027 assert!(tmpdir.join("f").exists());
2028 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2029 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2031 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2032 assert!(tmpdir.join("g").exists());
2033 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2034 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2036 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2037 check!(r.open(&tmpdir.join("h")));
2039 let mut f = check!(r.open(&tmpdir.join("h")));
2040 assert!(f.write("wut".as_bytes()).is_err());
2042 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2044 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2045 check!(f.write("bar".as_bytes()));
2047 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2049 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2050 check!(f.write("bar".as_bytes()));
2052 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2057 let mut bytes = [0; 1024];
2058 StdRng::new().unwrap().fill_bytes(&mut bytes);
2060 let tmpdir = tmpdir();
2062 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2063 let mut v = Vec::new();
2064 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2065 assert!(v == &bytes[..]);
2069 #[cfg(not(windows))]
2070 fn unlink_readonly() {
2071 let tmpdir = tmpdir();
2072 let path = tmpdir.join("file");
2073 check!(File::create(&path));
2074 let mut perm = check!(fs::metadata(&path)).permissions();
2075 perm.set_readonly(true);
2076 check!(fs::set_permissions(&path, perm));
2077 check!(fs::remove_file(&path));
2081 fn mkdir_trailing_slash() {
2082 let tmpdir = tmpdir();
2083 let path = tmpdir.join("file");
2084 check!(fs::create_dir_all(&path.join("a/")));
2088 fn canonicalize_works_simple() {
2089 let tmpdir = tmpdir();
2090 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2091 let file = tmpdir.join("test");
2092 File::create(&file).unwrap();
2093 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2097 #[cfg(not(windows))]
2098 fn realpath_works() {
2099 let tmpdir = tmpdir();
2100 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2101 let file = tmpdir.join("test");
2102 let dir = tmpdir.join("test2");
2103 let link = dir.join("link");
2104 let linkdir = tmpdir.join("test3");
2106 File::create(&file).unwrap();
2107 fs::create_dir(&dir).unwrap();
2108 fs::soft_link(&file, &link).unwrap();
2109 fs::soft_link(&dir, &linkdir).unwrap();
2111 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2113 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2114 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2115 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2116 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2117 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2121 #[cfg(not(windows))]
2122 fn realpath_works_tricky() {
2123 let tmpdir = tmpdir();
2124 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2126 let a = tmpdir.join("a");
2127 let b = a.join("b");
2128 let c = b.join("c");
2129 let d = a.join("d");
2130 let e = d.join("e");
2131 let f = a.join("f");
2133 fs::create_dir_all(&b).unwrap();
2134 fs::create_dir_all(&d).unwrap();
2135 File::create(&f).unwrap();
2136 fs::soft_link("../d/e", &c).unwrap();
2137 fs::soft_link("../f", &e).unwrap();
2139 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2140 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2144 fn dir_entry_methods() {
2145 let tmpdir = tmpdir();
2147 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2148 File::create(&tmpdir.join("b")).unwrap();
2150 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2151 let fname = file.file_name();
2152 match fname.to_str() {
2154 assert!(file.file_type().unwrap().is_dir());
2155 assert!(file.metadata().unwrap().is_dir());
2158 assert!(file.file_type().unwrap().is_file());
2159 assert!(file.metadata().unwrap().is_file());
2161 f => panic!("unknown file name: {:?}", f),
2167 fn read_dir_not_found() {
2168 let res = fs::read_dir("/path/that/does/not/exist");
2169 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);