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")]
23 use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
24 use path::{Path, PathBuf};
25 use sys::fs2 as fs_imp;
26 use sys_common::{AsInnerMut, FromInner, AsInner};
29 /// A reference to an open file on the filesystem.
31 /// An instance of a `File` can be read and/or written depending on what options
32 /// it was opened with. Files also implement `Seek` to alter the logical cursor
33 /// that the file contains internally.
38 /// use std::io::prelude::*;
39 /// use std::fs::File;
41 /// # fn foo() -> std::io::Result<()> {
42 /// let mut f = try!(File::create("foo.txt"));
43 /// try!(f.write_all(b"Hello, world!"));
45 /// let mut f = try!(File::open("foo.txt"));
46 /// let mut s = String::new();
47 /// try!(f.read_to_string(&mut s));
48 /// assert_eq!(s, "Hello, world!");
52 #[stable(feature = "rust1", since = "1.0.0")]
57 /// Metadata information about a file.
59 /// This structure is returned from the `metadata` function or method and
60 /// represents known metadata about a file such as its permissions, size,
61 /// modification times, etc.
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub struct Metadata(fs_imp::FileAttr);
65 /// Iterator over the entries in a directory.
67 /// This iterator is returned from the `read_dir` function of this module and
68 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
69 /// information like the entry's path and possibly other metadata can be
74 /// This `io::Result` will be an `Err` if there's some sort of intermittent
75 /// IO error during iteration.
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct ReadDir(fs_imp::ReadDir);
79 /// Entries returned by the `ReadDir` iterator.
81 /// An instance of `DirEntry` represents an entry inside of a directory on the
82 /// filesystem. Each entry can be inspected via methods to learn about the full
83 /// path or possibly other metadata through per-platform extension traits.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct DirEntry(fs_imp::DirEntry);
87 /// An iterator that recursively walks over the contents of a directory.
88 #[unstable(feature = "fs_walk",
89 reason = "the precise semantics and defaults for a recursive walk \
90 may change and this may end up accounting for files such \
91 as symlinks differently")]
94 stack: Vec<io::Result<ReadDir>>,
97 /// Options and flags which can be used to configure how a file is opened.
99 /// This builder exposes the ability to configure how a `File` is opened and
100 /// what operations are permitted on the open file. The `File::open` and
101 /// `File::create` methods are aliases for commonly used options using this
104 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
105 /// then chain calls to methods to set each option, then call `open()`, passing
106 /// the path of the file you're trying to open. This will give you a
107 /// [`io::Result`][result] with a [`File`][file] inside that you can further
110 /// [result]: ../io/type.Result.html
111 /// [file]: struct.File.html
115 /// Opening a file to read:
118 /// use std::fs::OpenOptions;
120 /// let file = OpenOptions::new().read(true).open("foo.txt");
123 /// Opening a file for both reading and writing, as well as creating it if it
127 /// use std::fs::OpenOptions;
129 /// let file = OpenOptions::new()
133 /// .open("foo.txt");
136 #[stable(feature = "rust1", since = "1.0.0")]
137 pub struct OpenOptions(fs_imp::OpenOptions);
139 /// Representation of the various permissions on a file.
141 /// This module only currently provides one bit of information, `readonly`,
142 /// which is exposed on all currently supported platforms. Unix-specific
143 /// functionality, such as mode bits, is available through the
144 /// `os::unix::PermissionsExt` trait.
145 #[derive(Clone, PartialEq, Eq, Debug)]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub struct Permissions(fs_imp::FilePermissions);
150 /// Attempts to open a file in read-only mode.
152 /// See the `OpenOptions::open` method for more details.
156 /// This function will return an error if `path` does not already exist.
157 /// Other errors may also be returned according to `OpenOptions::open`.
162 /// use std::fs::File;
164 /// # fn foo() -> std::io::Result<()> {
165 /// let mut f = try!(File::open("foo.txt"));
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
171 OpenOptions::new().read(true).open(path)
174 /// Opens a file in write-only mode.
176 /// This function will create a file if it does not exist,
177 /// and will truncate it if it does.
179 /// See the `OpenOptions::open` function for more details.
184 /// use std::fs::File;
186 /// # fn foo() -> std::io::Result<()> {
187 /// let mut f = try!(File::create("foo.txt"));
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
193 OpenOptions::new().write(true).create(true).truncate(true).open(path)
197 #[unstable(feature = "file_path",
198 reason = "this abstraction was imposed by this library and was removed")]
199 #[deprecated(since = "1.0.0", reason = "abstraction was removed")]
200 pub fn path(&self) -> Option<&Path> {
204 /// Attempts to sync all OS-internal metadata to disk.
206 /// This function will attempt to ensure that all in-core data reaches the
207 /// filesystem before returning.
212 /// use std::fs::File;
213 /// use std::io::prelude::*;
215 /// # fn foo() -> std::io::Result<()> {
216 /// let mut f = try!(File::create("foo.txt"));
217 /// try!(f.write_all(b"Hello, world!"));
219 /// try!(f.sync_all());
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn sync_all(&self) -> io::Result<()> {
228 /// This function is similar to `sync_all`, except that it may not
229 /// synchronize file metadata to the filesystem.
231 /// This is intended for use cases that must synchronize content, but don't
232 /// need the metadata on disk. The goal of this method is to reduce disk
235 /// Note that some platforms may simply implement this in terms of
241 /// use std::fs::File;
242 /// use std::io::prelude::*;
244 /// # fn foo() -> std::io::Result<()> {
245 /// let mut f = try!(File::create("foo.txt"));
246 /// try!(f.write_all(b"Hello, world!"));
248 /// try!(f.sync_data());
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn sync_data(&self) -> io::Result<()> {
254 self.inner.datasync()
257 /// Truncates or extends the underlying file, updating the size of
258 /// this file to become `size`.
260 /// If the `size` is less than the current file's size, then the file will
261 /// be shrunk. If it is greater than the current file's size, then the file
262 /// will be extended to `size` and have all of the intermediate data filled
268 /// use std::fs::File;
270 /// # fn foo() -> std::io::Result<()> {
271 /// let mut f = try!(File::open("foo.txt"));
272 /// try!(f.set_len(0));
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn set_len(&self, size: u64) -> io::Result<()> {
278 self.inner.truncate(size)
281 /// Queries metadata about the underlying file.
286 /// use std::fs::File;
288 /// # fn foo() -> std::io::Result<()> {
289 /// let mut f = try!(File::open("foo.txt"));
290 /// let metadata = try!(f.metadata());
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn metadata(&self) -> io::Result<Metadata> {
296 self.inner.file_attr().map(Metadata)
300 impl AsInner<fs_imp::File> for File {
301 fn as_inner(&self) -> &fs_imp::File { &self.inner }
303 impl FromInner<fs_imp::File> for File {
304 fn from_inner(f: fs_imp::File) -> File {
309 impl fmt::Debug for File {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315 #[stable(feature = "rust1", since = "1.0.0")]
317 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl Write for File {
323 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
324 self.inner.write(buf)
326 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
328 #[stable(feature = "rust1", since = "1.0.0")]
330 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl<'a> Read for &'a File {
336 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<'a> Write for &'a File {
342 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
343 self.inner.write(buf)
345 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<'a> Seek for &'a File {
349 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
355 /// Creates a blank net set of options ready for configuration.
357 /// All options are initially set to `false`.
362 /// use std::fs::OpenOptions;
364 /// let file = OpenOptions::new().open("foo.txt");
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn new() -> OpenOptions {
368 OpenOptions(fs_imp::OpenOptions::new())
371 /// Sets the option for read access.
373 /// This option, when true, will indicate that the file should be
374 /// `read`-able if opened.
379 /// use std::fs::OpenOptions;
381 /// let file = OpenOptions::new().read(true).open("foo.txt");
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
385 self.0.read(read); self
388 /// Sets the option for write access.
390 /// This option, when true, will indicate that the file should be
391 /// `write`-able if opened.
396 /// use std::fs::OpenOptions;
398 /// let file = OpenOptions::new().write(true).open("foo.txt");
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
402 self.0.write(write); self
405 /// Sets the option for the append mode.
407 /// This option, when true, means that writes will append to a file instead
408 /// of overwriting previous contents.
413 /// use std::fs::OpenOptions;
415 /// let file = OpenOptions::new().append(true).open("foo.txt");
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
419 self.0.append(append); self
422 /// Sets the option for truncating a previous file.
424 /// If a file is successfully opened with this option set it will truncate
425 /// the file to 0 length if it already exists.
430 /// use std::fs::OpenOptions;
432 /// let file = OpenOptions::new().truncate(true).open("foo.txt");
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
436 self.0.truncate(truncate); self
439 /// Sets the option for creating a new file.
441 /// This option indicates whether a new file will be created if the file
442 /// does not yet already exist.
447 /// use std::fs::OpenOptions;
449 /// let file = OpenOptions::new().create(true).open("foo.txt");
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
453 self.0.create(create); self
456 /// Opens a file at `path` with the options specified by `self`.
460 /// This function will return an error under a number of different
461 /// circumstances, to include but not limited to:
463 /// * Opening a file that does not exist with read access.
464 /// * Attempting to open a file with access that the user lacks
466 /// * Filesystem-level errors (full disk, etc)
471 /// use std::fs::OpenOptions;
473 /// let file = OpenOptions::new().open("foo.txt");
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
477 let path = path.as_ref();
478 let inner = try!(fs_imp::File::open(path, &self.0));
479 Ok(File { inner: inner })
483 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
484 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
488 /// Returns whether this metadata is for a directory.
493 /// # fn foo() -> std::io::Result<()> {
496 /// let metadata = try!(fs::metadata("foo.txt"));
498 /// assert!(!metadata.is_dir());
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn is_dir(&self) -> bool { self.0.is_dir() }
505 /// Returns whether this metadata is for a regular file.
510 /// # fn foo() -> std::io::Result<()> {
513 /// let metadata = try!(fs::metadata("foo.txt"));
515 /// assert!(metadata.is_file());
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn is_file(&self) -> bool { self.0.is_file() }
522 /// Returns the size of the file, in bytes, this metadata is for.
527 /// # fn foo() -> std::io::Result<()> {
530 /// let metadata = try!(fs::metadata("foo.txt"));
532 /// assert_eq!(0, metadata.len());
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn len(&self) -> u64 { self.0.size() }
539 /// Returns the permissions of the file this metadata is for.
544 /// # fn foo() -> std::io::Result<()> {
547 /// let metadata = try!(fs::metadata("foo.txt"));
549 /// assert!(!metadata.permissions().readonly());
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn permissions(&self) -> Permissions {
555 Permissions(self.0.perm())
558 /// Returns the most recent access time for a file.
560 /// The return value is in milliseconds since the epoch.
561 #[unstable(feature = "fs_time",
562 reason = "the return type of u64 is not quite appropriate for \
563 this method and may change if the standard library \
564 gains a type to represent a moment in time")]
565 pub fn accessed(&self) -> u64 { self.0.accessed() }
567 /// Returns the most recent modification time for a file.
569 /// The return value is in milliseconds since the epoch.
570 #[unstable(feature = "fs_time",
571 reason = "the return type of u64 is not quite appropriate for \
572 this method and may change if the standard library \
573 gains a type to represent a moment in time")]
574 pub fn modified(&self) -> u64 { self.0.modified() }
578 /// Returns whether these permissions describe a readonly file.
583 /// use std::fs::File;
585 /// # fn foo() -> std::io::Result<()> {
586 /// let mut f = try!(File::create("foo.txt"));
587 /// let metadata = try!(f.metadata());
589 /// assert_eq!(false, metadata.permissions().readonly());
593 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn readonly(&self) -> bool { self.0.readonly() }
596 /// Modifies the readonly flag for this set of permissions.
598 /// This operation does **not** modify the filesystem. To modify the
599 /// filesystem use the `fs::set_permissions` function.
604 /// use std::fs::File;
606 /// # fn foo() -> std::io::Result<()> {
607 /// let mut f = try!(File::create("foo.txt"));
608 /// let metadata = try!(f.metadata());
609 /// let mut permissions = metadata.permissions();
611 /// permissions.set_readonly(true);
613 /// // filesystem doesn't change
614 /// assert_eq!(false, metadata.permissions().readonly());
616 /// // just this particular `permissions`.
617 /// assert_eq!(true, permissions.readonly());
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn set_readonly(&mut self, readonly: bool) {
623 self.0.set_readonly(readonly)
627 impl FromInner<fs_imp::FilePermissions> for Permissions {
628 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
633 impl AsInner<fs_imp::FilePermissions> for Permissions {
634 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl Iterator for ReadDir {
639 type Item = io::Result<DirEntry>;
641 fn next(&mut self) -> Option<io::Result<DirEntry>> {
642 self.0.next().map(|entry| entry.map(DirEntry))
646 #[stable(feature = "rust1", since = "1.0.0")]
648 /// Returns the full path to the file that this entry represents.
650 /// The full path is created by joining the original path to `read_dir` or
651 /// `walk_dir` with the filename of this entry.
657 /// # fn foo() -> std::io::Result<()> {
658 /// for entry in try!(fs::read_dir(".")) {
659 /// let dir = try!(entry);
660 /// println!("{:?}", dir.path());
666 /// This prints output like:
671 /// "./hello_world.rs"
674 /// The exact text, of course, depends on what files you have in `.`.
675 #[stable(feature = "rust1", since = "1.0.0")]
676 pub fn path(&self) -> PathBuf { self.0.path() }
679 /// Removes a file from the underlying filesystem.
681 /// Note that, just because an unlink call was successful, it is not
682 /// guaranteed that a file is immediately deleted (e.g. depending on
683 /// platform, other open file descriptors may prevent immediate removal).
687 /// This function will return an error if `path` points to a directory, if the
688 /// user lacks permissions to remove the file, or if some other filesystem-level
696 /// # fn foo() -> std::io::Result<()> {
697 /// try!(fs::remove_file("a.txt"));
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
703 fs_imp::unlink(path.as_ref())
706 /// Given a path, query the file system to get information about a file,
709 /// This function will traverse soft links to query information about the
710 /// destination file.
715 /// # fn foo() -> std::io::Result<()> {
718 /// let attr = try!(fs::metadata("/some/file/path.txt"));
719 /// // inspect attr ...
726 /// This function will return an error if the user lacks the requisite
727 /// permissions to perform a `metadata` call on the given `path` or if there
728 /// is no entry in the filesystem at the provided path.
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
731 fs_imp::stat(path.as_ref()).map(Metadata)
734 /// Rename a file or directory to a new name.
738 /// This function will return an error if the provided `from` doesn't exist, if
739 /// the process lacks permissions to view the contents, if `from` and `to`
740 /// reside on separate filesystems, or if some other intermittent I/O error
748 /// # fn foo() -> std::io::Result<()> {
749 /// try!(fs::rename("a.txt", "b.txt"));
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
755 fs_imp::rename(from.as_ref(), to.as_ref())
758 /// Copies the contents of one file to another. This function will also
759 /// copy the permission bits of the original file to the destination file.
761 /// This function will **overwrite** the contents of `to`.
763 /// Note that if `from` and `to` both point to the same file, then the file
764 /// will likely get truncated by this operation.
768 /// This function will return an error in the following situations, but is not
769 /// limited to just these cases:
771 /// * The `from` path is not a file
772 /// * The `from` file does not exist
773 /// * The current process does not have the permission rights to access
774 /// `from` or write `to`
781 /// # fn foo() -> std::io::Result<()> {
782 /// try!(fs::copy("foo.txt", "bar.txt"));
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
787 let from = from.as_ref();
788 let to = to.as_ref();
790 return Err(Error::new(ErrorKind::InvalidInput,
791 "the source path is not an existing file"))
794 let mut reader = try!(File::open(from));
795 let mut writer = try!(File::create(to));
796 let perm = try!(reader.metadata()).permissions();
798 let ret = try!(io::copy(&mut reader, &mut writer));
799 try!(set_permissions(to, perm));
803 /// Creates a new hard link on the filesystem.
805 /// The `dst` path will be a link pointing to the `src` path. Note that systems
806 /// often require these two paths to both be located on the same filesystem.
813 /// # fn foo() -> std::io::Result<()> {
814 /// try!(fs::hard_link("a.txt", "b.txt"));
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
820 fs_imp::link(src.as_ref(), dst.as_ref())
823 /// Creates a new soft link on the filesystem.
825 /// The `dst` path will be a soft link pointing to the `src` path.
832 /// # fn foo() -> std::io::Result<()> {
833 /// try!(fs::soft_link("a.txt", "b.txt"));
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
839 fs_imp::symlink(src.as_ref(), dst.as_ref())
842 /// Reads a soft link, returning the file that the link points to.
846 /// This function will return an error on failure. Failure conditions include
847 /// reading a file that does not exist or reading a file that is not a soft
855 /// # fn foo() -> std::io::Result<()> {
856 /// let path = try!(fs::read_link("a.txt"));
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
862 fs_imp::readlink(path.as_ref())
865 /// Creates a new, empty directory at the provided path
869 /// This function will return an error if the user lacks permissions to make a
870 /// new directory at the provided `path`, or if the directory already exists.
877 /// # fn foo() -> std::io::Result<()> {
878 /// try!(fs::create_dir("/some/dir"));
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
884 fs_imp::mkdir(path.as_ref())
887 /// Recursively create a directory and all of its parent components if they
892 /// This function will fail if any directory in the path specified by `path`
893 /// does not already exist and it could not be created otherwise. The specific
894 /// error conditions for when a directory is being created (after it is
895 /// determined to not exist) are outlined by `fs::create_dir`.
902 /// # fn foo() -> std::io::Result<()> {
903 /// try!(fs::create_dir_all("/some/dir"));
907 #[stable(feature = "rust1", since = "1.0.0")]
908 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
909 let path = path.as_ref();
910 if path == Path::new("") || path.is_dir() { return Ok(()) }
911 if let Some(p) = path.parent() { try!(create_dir_all(p)) }
915 /// Removes an existing, empty directory.
919 /// This function will return an error if the user lacks permissions to remove
920 /// the directory at the provided `path`, or if the directory isn't empty.
927 /// # fn foo() -> std::io::Result<()> {
928 /// try!(fs::remove_dir("/some/dir"));
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
934 fs_imp::rmdir(path.as_ref())
937 /// Removes a directory at this path, after removing all its contents. Use
940 /// This function does **not** follow soft links and it will simply remove the
941 /// soft link itself.
945 /// See `file::remove_file` and `fs::remove_dir`.
952 /// # fn foo() -> std::io::Result<()> {
953 /// try!(fs::remove_dir_all("/some/dir"));
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
959 let path = path.as_ref();
960 for child in try!(read_dir(path)) {
961 let child = try!(child).path();
962 let stat = try!(lstat(&*child));
964 try!(remove_dir_all(&*child));
966 try!(remove_file(&*child));
969 return remove_dir(path);
972 fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::lstat(path) }
974 fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::stat(path) }
977 /// Returns an iterator over the entries within a directory.
979 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
980 /// be encountered after an iterator is initially constructed.
985 /// # #![feature(path_ext)]
987 /// use std::fs::{self, PathExt, DirEntry};
988 /// use std::path::Path;
990 /// // one possible implementation of fs::walk_dir only visiting files
991 /// fn visit_dirs(dir: &Path, cb: &mut FnMut(DirEntry)) -> io::Result<()> {
992 /// if dir.is_dir() {
993 /// for entry in try!(fs::read_dir(dir)) {
994 /// let entry = try!(entry);
995 /// if entry.path().is_dir() {
996 /// try!(visit_dirs(&entry.path(), cb));
1008 /// This function will return an error if the provided `path` doesn't exist, if
1009 /// the process lacks permissions to view the contents or if the `path` points
1010 /// at a non-directory file
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1013 fs_imp::readdir(path.as_ref()).map(ReadDir)
1016 /// Returns an iterator that will recursively walk the directory structure
1017 /// rooted at `path`.
1019 /// The path given will not be iterated over, and this will perform iteration in
1020 /// some top-down order. The contents of unreadable subdirectories are ignored.
1022 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1023 /// be encountered after an iterator is initially constructed.
1024 #[unstable(feature = "fs_walk",
1025 reason = "the precise semantics and defaults for a recursive walk \
1026 may change and this may end up accounting for files such \
1027 as symlinks differently")]
1028 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1029 let start = try!(read_dir(path));
1030 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1033 #[unstable(feature = "fs_walk")]
1034 impl Iterator for WalkDir {
1035 type Item = io::Result<DirEntry>;
1037 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1039 if let Some(ref mut cur) = self.cur {
1041 Some(Err(e)) => return Some(Err(e)),
1043 let path = next.path();
1045 self.stack.push(read_dir(&*path));
1047 return Some(Ok(next))
1053 match self.stack.pop() {
1054 Some(Err(e)) => return Some(Err(e)),
1055 Some(Ok(next)) => self.cur = Some(next),
1056 None => return None,
1062 /// Utility methods for paths.
1063 #[unstable(feature = "path_ext",
1064 reason = "the precise set of methods exposed on this trait may \
1065 change and some methods may be removed")]
1067 /// Gets information on the file, directory, etc at this path.
1069 /// Consult the `fs::stat` documentation for more info.
1071 /// This call preserves identical runtime/error semantics with `file::stat`.
1072 fn metadata(&self) -> io::Result<Metadata>;
1074 /// Boolean value indicator whether the underlying file exists on the local
1075 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1076 fn exists(&self) -> bool;
1078 /// Whether the underlying implementation (be it a file path, or something
1079 /// else) points at a "regular file" on the FS. Will return false for paths
1080 /// to non-existent locations or directories or other non-regular files
1081 /// (named pipes, etc). Follows links when making this determination.
1082 fn is_file(&self) -> bool;
1084 /// Whether the underlying implementation (be it a file path, or something
1085 /// else) is pointing at a directory in the underlying FS. Will return
1086 /// false for paths to non-existent locations or if the item is not a
1087 /// directory (eg files, named pipes, etc). Follows links when making this
1089 fn is_dir(&self) -> bool;
1092 impl PathExt for Path {
1093 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1095 fn exists(&self) -> bool { metadata(self).is_ok() }
1097 fn is_file(&self) -> bool {
1098 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1100 fn is_dir(&self) -> bool {
1101 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1105 /// Changes the timestamps for a file's last modification and access time.
1107 /// The file at the path specified will have its last access time set to
1108 /// `accessed` and its modification time set to `modified`. The times specified
1109 /// should be in milliseconds.
1110 #[unstable(feature = "fs_time",
1111 reason = "the argument type of u64 is not quite appropriate for \
1112 this function and may change if the standard library \
1113 gains a type to represent a moment in time")]
1114 pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
1115 modified: u64) -> io::Result<()> {
1116 fs_imp::utimes(path.as_ref(), accessed, modified)
1119 /// Changes the permissions found on a file or a directory.
1124 /// # #![feature(fs)]
1125 /// # fn foo() -> std::io::Result<()> {
1128 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1129 /// perms.set_readonly(true);
1130 /// try!(fs::set_permissions("foo.txt", perms));
1137 /// This function will return an error if the provided `path` doesn't exist, if
1138 /// the process lacks permissions to change the attributes of the file, or if
1139 /// some other I/O error is encountered.
1140 #[unstable(feature = "fs",
1141 reason = "a more granual ability to set specific permissions may \
1142 be exposed on the Permissions structure itself and this \
1143 method may not always exist")]
1144 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
1145 fs_imp::set_perm(path.as_ref(), perm.0)
1150 #![allow(deprecated)] //rand
1156 use fs::{self, File, OpenOptions};
1157 use io::{ErrorKind, SeekFrom};
1159 use path::Path as Path2;
1161 use rand::{self, StdRng, Rng};
1164 macro_rules! check { ($e:expr) => (
1167 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1171 macro_rules! error { ($e:expr, $s:expr) => (
1173 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1174 Err(ref err) => assert!(err.to_string().contains($s),
1175 format!("`{}` did not contain `{}`", err, $s))
1179 pub struct TempDir(PathBuf);
1182 fn join(&self, path: &str) -> PathBuf {
1183 let TempDir(ref p) = *self;
1187 fn path<'a>(&'a self) -> &'a Path2 {
1188 let TempDir(ref p) = *self;
1193 impl Drop for TempDir {
1194 fn drop(&mut self) {
1195 // Gee, seeing how we're testing the fs module I sure hope that we
1196 // at least implement this correctly!
1197 let TempDir(ref p) = *self;
1198 check!(fs::remove_dir_all(p));
1202 pub fn tmpdir() -> TempDir {
1203 let p = env::temp_dir();
1204 let mut r = rand::thread_rng();
1205 let ret = p.join(&format!("rust-{}", r.next_u32()));
1206 check!(fs::create_dir(&ret));
1211 fn file_test_io_smoke_test() {
1212 let message = "it's alright. have a good time";
1213 let tmpdir = tmpdir();
1214 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1216 let mut write_stream = check!(File::create(filename));
1217 check!(write_stream.write(message.as_bytes()));
1220 let mut read_stream = check!(File::open(filename));
1221 let mut read_buf = [0; 1028];
1222 let read_str = match check!(read_stream.read(&mut read_buf)) {
1223 0 => panic!("shouldn't happen"),
1224 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1226 assert_eq!(read_str, message);
1228 check!(fs::remove_file(filename));
1232 fn invalid_path_raises() {
1233 let tmpdir = tmpdir();
1234 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1235 let result = File::open(filename);
1238 error!(result, "o such file or directory");
1240 // error!(result, "couldn't open path as file");
1241 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1245 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1246 let tmpdir = tmpdir();
1247 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1249 let result = fs::remove_file(filename);
1252 error!(result, "o such file or directory");
1254 // error!(result, "couldn't unlink path");
1255 // error!(result, format!("path={}", filename.display()));
1259 fn file_test_io_non_positional_read() {
1260 let message: &str = "ten-four";
1261 let mut read_mem = [0; 8];
1262 let tmpdir = tmpdir();
1263 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1265 let mut rw_stream = check!(File::create(filename));
1266 check!(rw_stream.write(message.as_bytes()));
1269 let mut read_stream = check!(File::open(filename));
1271 let read_buf = &mut read_mem[0..4];
1272 check!(read_stream.read(read_buf));
1275 let read_buf = &mut read_mem[4..8];
1276 check!(read_stream.read(read_buf));
1279 check!(fs::remove_file(filename));
1280 let read_str = str::from_utf8(&read_mem).unwrap();
1281 assert_eq!(read_str, message);
1285 fn file_test_io_seek_and_tell_smoke_test() {
1286 let message = "ten-four";
1287 let mut read_mem = [0; 4];
1288 let set_cursor = 4 as u64;
1289 let mut tell_pos_pre_read;
1290 let mut tell_pos_post_read;
1291 let tmpdir = tmpdir();
1292 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1294 let mut rw_stream = check!(File::create(filename));
1295 check!(rw_stream.write(message.as_bytes()));
1298 let mut read_stream = check!(File::open(filename));
1299 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1300 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1301 check!(read_stream.read(&mut read_mem));
1302 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1304 check!(fs::remove_file(filename));
1305 let read_str = str::from_utf8(&read_mem).unwrap();
1306 assert_eq!(read_str, &message[4..8]);
1307 assert_eq!(tell_pos_pre_read, set_cursor);
1308 assert_eq!(tell_pos_post_read, message.len() as u64);
1312 fn file_test_io_seek_and_write() {
1313 let initial_msg = "food-is-yummy";
1314 let overwrite_msg = "-the-bar!!";
1315 let final_msg = "foo-the-bar!!";
1317 let mut read_mem = [0; 13];
1318 let tmpdir = tmpdir();
1319 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1321 let mut rw_stream = check!(File::create(filename));
1322 check!(rw_stream.write(initial_msg.as_bytes()));
1323 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1324 check!(rw_stream.write(overwrite_msg.as_bytes()));
1327 let mut read_stream = check!(File::open(filename));
1328 check!(read_stream.read(&mut read_mem));
1330 check!(fs::remove_file(filename));
1331 let read_str = str::from_utf8(&read_mem).unwrap();
1332 assert!(read_str == final_msg);
1336 fn file_test_io_seek_shakedown() {
1338 let initial_msg = "qwer-asdf-zxcv";
1339 let chunk_one: &str = "qwer";
1340 let chunk_two: &str = "asdf";
1341 let chunk_three: &str = "zxcv";
1342 let mut read_mem = [0; 4];
1343 let tmpdir = tmpdir();
1344 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1346 let mut rw_stream = check!(File::create(filename));
1347 check!(rw_stream.write(initial_msg.as_bytes()));
1350 let mut read_stream = check!(File::open(filename));
1352 check!(read_stream.seek(SeekFrom::End(-4)));
1353 check!(read_stream.read(&mut read_mem));
1354 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1356 check!(read_stream.seek(SeekFrom::Current(-9)));
1357 check!(read_stream.read(&mut read_mem));
1358 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1360 check!(read_stream.seek(SeekFrom::Start(0)));
1361 check!(read_stream.read(&mut read_mem));
1362 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1364 check!(fs::remove_file(filename));
1368 fn file_test_stat_is_correct_on_is_file() {
1369 let tmpdir = tmpdir();
1370 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1372 let mut opts = OpenOptions::new();
1373 let mut fs = check!(opts.read(true).write(true)
1374 .create(true).open(filename));
1376 fs.write(msg.as_bytes()).unwrap();
1378 let fstat_res = check!(fs.metadata());
1379 assert!(fstat_res.is_file());
1381 let stat_res_fn = check!(fs::metadata(filename));
1382 assert!(stat_res_fn.is_file());
1383 let stat_res_meth = check!(filename.metadata());
1384 assert!(stat_res_meth.is_file());
1385 check!(fs::remove_file(filename));
1389 fn file_test_stat_is_correct_on_is_dir() {
1390 let tmpdir = tmpdir();
1391 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1392 check!(fs::create_dir(filename));
1393 let stat_res_fn = check!(fs::metadata(filename));
1394 assert!(stat_res_fn.is_dir());
1395 let stat_res_meth = check!(filename.metadata());
1396 assert!(stat_res_meth.is_dir());
1397 check!(fs::remove_dir(filename));
1401 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1402 let tmpdir = tmpdir();
1403 let dir = &tmpdir.join("fileinfo_false_on_dir");
1404 check!(fs::create_dir(dir));
1405 assert!(dir.is_file() == false);
1406 check!(fs::remove_dir(dir));
1410 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1411 let tmpdir = tmpdir();
1412 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1413 check!(check!(File::create(file)).write(b"foo"));
1414 assert!(file.exists());
1415 check!(fs::remove_file(file));
1416 assert!(!file.exists());
1420 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1421 let tmpdir = tmpdir();
1422 let dir = &tmpdir.join("before_and_after_dir");
1423 assert!(!dir.exists());
1424 check!(fs::create_dir(dir));
1425 assert!(dir.exists());
1426 assert!(dir.is_dir());
1427 check!(fs::remove_dir(dir));
1428 assert!(!dir.exists());
1432 fn file_test_directoryinfo_readdir() {
1433 let tmpdir = tmpdir();
1434 let dir = &tmpdir.join("di_readdir");
1435 check!(fs::create_dir(dir));
1438 let f = dir.join(&format!("{}.txt", n));
1439 let mut w = check!(File::create(&f));
1440 let msg_str = format!("{}{}", prefix, n.to_string());
1441 let msg = msg_str.as_bytes();
1442 check!(w.write(msg));
1444 let files = check!(fs::read_dir(dir));
1445 let mut mem = [0; 4];
1447 let f = f.unwrap().path();
1449 let n = f.file_stem().unwrap();
1450 check!(check!(File::open(&f)).read(&mut mem));
1451 let read_str = str::from_utf8(&mem).unwrap();
1452 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1453 assert_eq!(expected, read_str);
1455 check!(fs::remove_file(&f));
1457 check!(fs::remove_dir(dir));
1461 fn file_test_walk_dir() {
1462 let tmpdir = tmpdir();
1463 let dir = &tmpdir.join("walk_dir");
1464 check!(fs::create_dir(dir));
1466 let dir1 = &dir.join("01/02/03");
1467 check!(fs::create_dir_all(dir1));
1468 check!(File::create(&dir1.join("04")));
1470 let dir2 = &dir.join("11/12/13");
1471 check!(fs::create_dir_all(dir2));
1472 check!(File::create(&dir2.join("14")));
1474 let files = check!(fs::walk_dir(dir));
1475 let mut cur = [0; 2];
1477 let f = f.unwrap().path();
1478 let stem = f.file_stem().unwrap().to_str().unwrap();
1479 let root = stem.as_bytes()[0] - b'0';
1480 let name = stem.as_bytes()[1] - b'0';
1481 assert!(cur[root as usize] < name);
1482 cur[root as usize] = name;
1485 check!(fs::remove_dir_all(dir));
1489 fn mkdir_path_already_exists_error() {
1490 let tmpdir = tmpdir();
1491 let dir = &tmpdir.join("mkdir_error_twice");
1492 check!(fs::create_dir(dir));
1493 let e = fs::create_dir(dir).err().unwrap();
1494 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1498 fn recursive_mkdir() {
1499 let tmpdir = tmpdir();
1500 let dir = tmpdir.join("d1/d2");
1501 check!(fs::create_dir_all(&dir));
1502 assert!(dir.is_dir())
1506 fn recursive_mkdir_failure() {
1507 let tmpdir = tmpdir();
1508 let dir = tmpdir.join("d1");
1509 let file = dir.join("f1");
1511 check!(fs::create_dir_all(&dir));
1512 check!(File::create(&file));
1514 let result = fs::create_dir_all(&file);
1516 assert!(result.is_err());
1517 // error!(result, "couldn't recursively mkdir");
1518 // error!(result, "couldn't create directory");
1519 // error!(result, "mode=0700");
1520 // error!(result, format!("path={}", file.display()));
1524 fn recursive_mkdir_slash() {
1525 check!(fs::create_dir_all(&Path2::new("/")));
1528 // FIXME(#12795) depends on lstat to work on windows
1529 #[cfg(not(windows))]
1531 fn recursive_rmdir() {
1532 let tmpdir = tmpdir();
1533 let d1 = tmpdir.join("d1");
1534 let dt = d1.join("t");
1535 let dtt = dt.join("t");
1536 let d2 = tmpdir.join("d2");
1537 let canary = d2.join("do_not_delete");
1538 check!(fs::create_dir_all(&dtt));
1539 check!(fs::create_dir_all(&d2));
1540 check!(check!(File::create(&canary)).write(b"foo"));
1541 check!(fs::soft_link(&d2, &dt.join("d2")));
1542 check!(fs::remove_dir_all(&d1));
1544 assert!(!d1.is_dir());
1545 assert!(canary.exists());
1549 fn unicode_path_is_dir() {
1550 assert!(Path2::new(".").is_dir());
1551 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1553 let tmpdir = tmpdir();
1555 let mut dirpath = tmpdir.path().to_path_buf();
1556 dirpath.push(&format!("test-가一ー你好"));
1557 check!(fs::create_dir(&dirpath));
1558 assert!(dirpath.is_dir());
1560 let mut filepath = dirpath;
1561 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1562 check!(File::create(&filepath)); // ignore return; touch only
1563 assert!(!filepath.is_dir());
1564 assert!(filepath.exists());
1568 fn unicode_path_exists() {
1569 assert!(Path2::new(".").exists());
1570 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1572 let tmpdir = tmpdir();
1573 let unicode = tmpdir.path();
1574 let unicode = unicode.join(&format!("test-각丁ー再见"));
1575 check!(fs::create_dir(&unicode));
1576 assert!(unicode.exists());
1577 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1581 fn copy_file_does_not_exist() {
1582 let from = Path2::new("test/nonexistent-bogus-path");
1583 let to = Path2::new("test/other-bogus-path");
1585 match fs::copy(&from, &to) {
1588 assert!(!from.exists());
1589 assert!(!to.exists());
1596 let tmpdir = tmpdir();
1597 let input = tmpdir.join("in.txt");
1598 let out = tmpdir.join("out.txt");
1600 check!(check!(File::create(&input)).write(b"hello"));
1601 check!(fs::copy(&input, &out));
1602 let mut v = Vec::new();
1603 check!(check!(File::open(&out)).read_to_end(&mut v));
1604 assert_eq!(v, b"hello");
1606 assert_eq!(check!(input.metadata()).permissions(),
1607 check!(out.metadata()).permissions());
1611 fn copy_file_dst_dir() {
1612 let tmpdir = tmpdir();
1613 let out = tmpdir.join("out");
1615 check!(File::create(&out));
1616 match fs::copy(&*out, tmpdir.path()) {
1617 Ok(..) => panic!(), Err(..) => {}
1622 fn copy_file_dst_exists() {
1623 let tmpdir = tmpdir();
1624 let input = tmpdir.join("in");
1625 let output = tmpdir.join("out");
1627 check!(check!(File::create(&input)).write("foo".as_bytes()));
1628 check!(check!(File::create(&output)).write("bar".as_bytes()));
1629 check!(fs::copy(&input, &output));
1631 let mut v = Vec::new();
1632 check!(check!(File::open(&output)).read_to_end(&mut v));
1633 assert_eq!(v, b"foo".to_vec());
1637 fn copy_file_src_dir() {
1638 let tmpdir = tmpdir();
1639 let out = tmpdir.join("out");
1641 match fs::copy(tmpdir.path(), &out) {
1642 Ok(..) => panic!(), Err(..) => {}
1644 assert!(!out.exists());
1648 fn copy_file_preserves_perm_bits() {
1649 let tmpdir = tmpdir();
1650 let input = tmpdir.join("in.txt");
1651 let out = tmpdir.join("out.txt");
1653 let attr = check!(check!(File::create(&input)).metadata());
1654 let mut p = attr.permissions();
1655 p.set_readonly(true);
1656 check!(fs::set_permissions(&input, p));
1657 check!(fs::copy(&input, &out));
1658 assert!(check!(out.metadata()).permissions().readonly());
1659 check!(fs::set_permissions(&input, attr.permissions()));
1660 check!(fs::set_permissions(&out, attr.permissions()));
1663 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1665 fn symlinks_work() {
1666 let tmpdir = tmpdir();
1667 let input = tmpdir.join("in.txt");
1668 let out = tmpdir.join("out.txt");
1670 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1671 check!(fs::soft_link(&input, &out));
1672 // if cfg!(not(windows)) {
1673 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1674 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1676 assert_eq!(check!(fs::metadata(&out)).len(),
1677 check!(fs::metadata(&input)).len());
1678 let mut v = Vec::new();
1679 check!(check!(File::open(&out)).read_to_end(&mut v));
1680 assert_eq!(v, b"foobar".to_vec());
1683 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1685 fn symlink_noexist() {
1686 let tmpdir = tmpdir();
1687 // symlinks can point to things that don't exist
1688 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1689 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1690 tmpdir.join("foo"));
1694 fn readlink_not_symlink() {
1695 let tmpdir = tmpdir();
1696 match fs::read_link(tmpdir.path()) {
1697 Ok(..) => panic!("wanted a failure"),
1704 let tmpdir = tmpdir();
1705 let input = tmpdir.join("in.txt");
1706 let out = tmpdir.join("out.txt");
1708 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1709 check!(fs::hard_link(&input, &out));
1710 assert_eq!(check!(fs::metadata(&out)).len(),
1711 check!(fs::metadata(&input)).len());
1712 assert_eq!(check!(fs::metadata(&out)).len(),
1713 check!(input.metadata()).len());
1714 let mut v = Vec::new();
1715 check!(check!(File::open(&out)).read_to_end(&mut v));
1716 assert_eq!(v, b"foobar".to_vec());
1718 // can't link to yourself
1719 match fs::hard_link(&input, &input) {
1720 Ok(..) => panic!("wanted a failure"),
1723 // can't link to something that doesn't exist
1724 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1725 Ok(..) => panic!("wanted a failure"),
1732 let tmpdir = tmpdir();
1733 let file = tmpdir.join("in.txt");
1735 check!(File::create(&file));
1736 let attr = check!(fs::metadata(&file));
1737 assert!(!attr.permissions().readonly());
1738 let mut p = attr.permissions();
1739 p.set_readonly(true);
1740 check!(fs::set_permissions(&file, p.clone()));
1741 let attr = check!(fs::metadata(&file));
1742 assert!(attr.permissions().readonly());
1744 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1745 Ok(..) => panic!("wanted an error"),
1749 p.set_readonly(false);
1750 check!(fs::set_permissions(&file, p));
1754 fn sync_doesnt_kill_anything() {
1755 let tmpdir = tmpdir();
1756 let path = tmpdir.join("in.txt");
1758 let mut file = check!(File::create(&path));
1759 check!(file.sync_all());
1760 check!(file.sync_data());
1761 check!(file.write(b"foo"));
1762 check!(file.sync_all());
1763 check!(file.sync_data());
1767 fn truncate_works() {
1768 let tmpdir = tmpdir();
1769 let path = tmpdir.join("in.txt");
1771 let mut file = check!(File::create(&path));
1772 check!(file.write(b"foo"));
1773 check!(file.sync_all());
1775 // Do some simple things with truncation
1776 assert_eq!(check!(file.metadata()).len(), 3);
1777 check!(file.set_len(10));
1778 assert_eq!(check!(file.metadata()).len(), 10);
1779 check!(file.write(b"bar"));
1780 check!(file.sync_all());
1781 assert_eq!(check!(file.metadata()).len(), 10);
1783 let mut v = Vec::new();
1784 check!(check!(File::open(&path)).read_to_end(&mut v));
1785 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1787 // Truncate to a smaller length, don't seek, and then write something.
1788 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1789 // past the end of the file).
1790 check!(file.set_len(2));
1791 assert_eq!(check!(file.metadata()).len(), 2);
1792 check!(file.write(b"wut"));
1793 check!(file.sync_all());
1794 assert_eq!(check!(file.metadata()).len(), 9);
1795 let mut v = Vec::new();
1796 check!(check!(File::open(&path)).read_to_end(&mut v));
1797 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1802 use fs::OpenOptions as OO;
1803 fn c<T: Clone>(t: &T) -> T { t.clone() }
1805 let tmpdir = tmpdir();
1807 let mut r = OO::new(); r.read(true);
1808 let mut w = OO::new(); w.write(true);
1809 let mut rw = OO::new(); rw.write(true).read(true);
1811 match r.open(&tmpdir.join("a")) {
1812 Ok(..) => panic!(), Err(..) => {}
1815 // Perform each one twice to make sure that it succeeds the second time
1816 // (where the file exists)
1817 check!(c(&w).create(true).open(&tmpdir.join("b")));
1818 assert!(tmpdir.join("b").exists());
1819 check!(c(&w).create(true).open(&tmpdir.join("b")));
1820 check!(w.open(&tmpdir.join("b")));
1822 check!(c(&rw).create(true).open(&tmpdir.join("c")));
1823 assert!(tmpdir.join("c").exists());
1824 check!(c(&rw).create(true).open(&tmpdir.join("c")));
1825 check!(rw.open(&tmpdir.join("c")));
1827 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
1828 assert!(tmpdir.join("d").exists());
1829 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
1830 check!(c(&w).append(true).open(&tmpdir.join("d")));
1832 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
1833 assert!(tmpdir.join("e").exists());
1834 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
1835 check!(c(&rw).append(true).open(&tmpdir.join("e")));
1837 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
1838 assert!(tmpdir.join("f").exists());
1839 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
1840 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
1842 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
1843 assert!(tmpdir.join("g").exists());
1844 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
1845 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
1847 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
1848 check!(r.open(&tmpdir.join("h")));
1850 let mut f = check!(r.open(&tmpdir.join("h")));
1851 assert!(f.write("wut".as_bytes()).is_err());
1853 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
1855 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
1856 check!(f.write("bar".as_bytes()));
1858 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
1860 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
1861 check!(f.write("bar".as_bytes()));
1863 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
1868 let tmpdir = tmpdir();
1869 let path = tmpdir.join("a");
1870 check!(File::create(&path));
1871 // These numbers have to be bigger than the time in the day to account
1872 // for timezones Windows in particular will fail in certain timezones
1873 // with small enough values
1874 check!(fs::set_file_times(&path, 100000, 200000));
1875 assert_eq!(check!(path.metadata()).accessed(), 100000);
1876 assert_eq!(check!(path.metadata()).modified(), 200000);
1880 fn utime_noexist() {
1881 let tmpdir = tmpdir();
1883 match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
1891 let mut bytes = [0; 1024];
1892 StdRng::new().unwrap().fill_bytes(&mut bytes);
1894 let tmpdir = tmpdir();
1896 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
1897 let mut v = Vec::new();
1898 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
1899 assert!(v == &bytes[..]);
1903 #[cfg(not(windows))]
1904 fn unlink_readonly() {
1905 let tmpdir = tmpdir();
1906 let path = tmpdir.join("file");
1907 check!(File::create(&path));
1908 let mut perm = check!(fs::metadata(&path)).permissions();
1909 perm.set_readonly(true);
1910 check!(fs::set_permissions(&path, perm));
1911 check!(fs::remove_file(&path));
1915 fn mkdir_trailing_slash() {
1916 let tmpdir = tmpdir();
1917 let path = tmpdir.join("file");
1918 check!(fs::create_dir_all(&path.join("a/")));