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")]
24 use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
25 use path::{Path, PathBuf};
26 use sys::fs as fs_imp;
27 use sys_common::{AsInnerMut, FromInner, AsInner};
30 /// A reference to an open file on the filesystem.
32 /// An instance of a `File` can be read and/or written depending on what options
33 /// it was opened with. Files also implement `Seek` to alter the logical cursor
34 /// that the file contains internally.
39 /// use std::io::prelude::*;
40 /// use std::fs::File;
42 /// # fn foo() -> std::io::Result<()> {
43 /// let mut f = try!(File::create("foo.txt"));
44 /// try!(f.write_all(b"Hello, world!"));
46 /// let mut f = try!(File::open("foo.txt"));
47 /// let mut s = String::new();
48 /// try!(f.read_to_string(&mut s));
49 /// assert_eq!(s, "Hello, world!");
53 #[stable(feature = "rust1", since = "1.0.0")]
58 /// Metadata information about a file.
60 /// This structure is returned from the `metadata` function or method and
61 /// represents known metadata about a file such as its permissions, size,
62 /// modification times, etc.
63 #[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")]
95 stack: Vec<io::Result<ReadDir>>,
98 /// Options and flags which can be used to configure how a file is opened.
100 /// This builder exposes the ability to configure how a `File` is opened and
101 /// what operations are permitted on the open file. The `File::open` and
102 /// `File::create` methods are aliases for commonly used options using this
105 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
106 /// then chain calls to methods to set each option, then call `open()`, passing
107 /// the path of the file you're trying to open. This will give you a
108 /// [`io::Result`][result] with a [`File`][file] inside that you can further
111 /// [result]: ../io/type.Result.html
112 /// [file]: struct.File.html
116 /// Opening a file to read:
119 /// use std::fs::OpenOptions;
121 /// let file = OpenOptions::new().read(true).open("foo.txt");
124 /// Opening a file for both reading and writing, as well as creating it if it
128 /// use std::fs::OpenOptions;
130 /// let file = OpenOptions::new()
134 /// .open("foo.txt");
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub struct OpenOptions(fs_imp::OpenOptions);
140 /// Representation of the various permissions on a file.
142 /// This module only currently provides one bit of information, `readonly`,
143 /// which is exposed on all currently supported platforms. Unix-specific
144 /// functionality, such as mode bits, is available through the
145 /// `os::unix::PermissionsExt` trait.
146 #[derive(Clone, PartialEq, Eq, Debug)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct Permissions(fs_imp::FilePermissions);
150 /// An structure representing a type of file with accessors for each file type.
151 #[unstable(feature = "file_type", reason = "recently added API")]
152 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
153 pub struct FileType(fs_imp::FileType);
155 /// A builder used to create directories in various manners.
157 /// This builder also supports platform-specific options.
158 #[unstable(feature = "dir_builder", reason = "recently added API")]
159 pub struct DirBuilder {
160 inner: fs_imp::DirBuilder,
165 /// Attempts to open a file in read-only mode.
167 /// See the `OpenOptions::open` method for more details.
171 /// This function will return an error if `path` does not already exist.
172 /// Other errors may also be returned according to `OpenOptions::open`.
177 /// use std::fs::File;
179 /// # fn foo() -> std::io::Result<()> {
180 /// let mut f = try!(File::open("foo.txt"));
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
186 OpenOptions::new().read(true).open(path)
189 /// Opens a file in write-only mode.
191 /// This function will create a file if it does not exist,
192 /// and will truncate it if it does.
194 /// See the `OpenOptions::open` function for more details.
199 /// use std::fs::File;
201 /// # fn foo() -> std::io::Result<()> {
202 /// let mut f = try!(File::create("foo.txt"));
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
208 OpenOptions::new().write(true).create(true).truncate(true).open(path)
212 #[unstable(feature = "file_path",
213 reason = "this abstraction was imposed by this library and was removed")]
214 #[deprecated(since = "1.0.0", reason = "abstraction was removed")]
215 pub fn path(&self) -> Option<&Path> {
219 /// Attempts to sync all OS-internal metadata to disk.
221 /// This function will attempt to ensure that all in-core data reaches the
222 /// filesystem before returning.
227 /// use std::fs::File;
228 /// use std::io::prelude::*;
230 /// # fn foo() -> std::io::Result<()> {
231 /// let mut f = try!(File::create("foo.txt"));
232 /// try!(f.write_all(b"Hello, world!"));
234 /// try!(f.sync_all());
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn sync_all(&self) -> io::Result<()> {
243 /// This function is similar to `sync_all`, except that it may not
244 /// synchronize file metadata to the filesystem.
246 /// This is intended for use cases that must synchronize content, but don't
247 /// need the metadata on disk. The goal of this method is to reduce disk
250 /// Note that some platforms may simply implement this in terms of
256 /// use std::fs::File;
257 /// use std::io::prelude::*;
259 /// # fn foo() -> std::io::Result<()> {
260 /// let mut f = try!(File::create("foo.txt"));
261 /// try!(f.write_all(b"Hello, world!"));
263 /// try!(f.sync_data());
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn sync_data(&self) -> io::Result<()> {
269 self.inner.datasync()
272 /// Truncates or extends the underlying file, updating the size of
273 /// this file to become `size`.
275 /// If the `size` is less than the current file's size, then the file will
276 /// be shrunk. If it is greater than the current file's size, then the file
277 /// will be extended to `size` and have all of the intermediate data filled
283 /// use std::fs::File;
285 /// # fn foo() -> std::io::Result<()> {
286 /// let mut f = try!(File::open("foo.txt"));
287 /// try!(f.set_len(0));
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn set_len(&self, size: u64) -> io::Result<()> {
293 self.inner.truncate(size)
296 /// Queries metadata about the underlying file.
301 /// use std::fs::File;
303 /// # fn foo() -> std::io::Result<()> {
304 /// let mut f = try!(File::open("foo.txt"));
305 /// let metadata = try!(f.metadata());
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub fn metadata(&self) -> io::Result<Metadata> {
311 self.inner.file_attr().map(Metadata)
315 impl AsInner<fs_imp::File> for File {
316 fn as_inner(&self) -> &fs_imp::File { &self.inner }
318 impl FromInner<fs_imp::File> for File {
319 fn from_inner(f: fs_imp::File) -> File {
324 impl fmt::Debug for File {
325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 #[stable(feature = "rust1", since = "1.0.0")]
332 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl Write for File {
338 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
339 self.inner.write(buf)
341 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
343 #[stable(feature = "rust1", since = "1.0.0")]
345 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
349 #[stable(feature = "rust1", since = "1.0.0")]
350 impl<'a> Read for &'a File {
351 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl<'a> Write for &'a File {
357 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
358 self.inner.write(buf)
360 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<'a> Seek for &'a File {
364 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
370 /// Creates a blank net set of options ready for configuration.
372 /// All options are initially set to `false`.
377 /// use std::fs::OpenOptions;
379 /// let file = OpenOptions::new().open("foo.txt");
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn new() -> OpenOptions {
383 OpenOptions(fs_imp::OpenOptions::new())
386 /// Sets the option for read access.
388 /// This option, when true, will indicate that the file should be
389 /// `read`-able if opened.
394 /// use std::fs::OpenOptions;
396 /// let file = OpenOptions::new().read(true).open("foo.txt");
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
400 self.0.read(read); self
403 /// Sets the option for write access.
405 /// This option, when true, will indicate that the file should be
406 /// `write`-able if opened.
411 /// use std::fs::OpenOptions;
413 /// let file = OpenOptions::new().write(true).open("foo.txt");
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
417 self.0.write(write); self
420 /// Sets the option for the append mode.
422 /// This option, when true, means that writes will append to a file instead
423 /// of overwriting previous contents.
428 /// use std::fs::OpenOptions;
430 /// let file = OpenOptions::new().append(true).open("foo.txt");
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
434 self.0.append(append); self
437 /// Sets the option for truncating a previous file.
439 /// If a file is successfully opened with this option set it will truncate
440 /// the file to 0 length if it already exists.
445 /// use std::fs::OpenOptions;
447 /// let file = OpenOptions::new().truncate(true).open("foo.txt");
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
451 self.0.truncate(truncate); self
454 /// Sets the option for creating a new file.
456 /// This option indicates whether a new file will be created if the file
457 /// does not yet already exist.
462 /// use std::fs::OpenOptions;
464 /// let file = OpenOptions::new().create(true).open("foo.txt");
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
468 self.0.create(create); self
471 /// Opens a file at `path` with the options specified by `self`.
475 /// This function will return an error under a number of different
476 /// circumstances, to include but not limited to:
478 /// * Opening a file that does not exist with read access.
479 /// * Attempting to open a file with access that the user lacks
481 /// * Filesystem-level errors (full disk, etc)
486 /// use std::fs::OpenOptions;
488 /// let file = OpenOptions::new().open("foo.txt");
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
492 let path = path.as_ref();
493 let inner = try!(fs_imp::File::open(path, &self.0));
494 Ok(File { inner: inner })
498 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
499 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
503 /// Returns the file type for this metadata.
504 #[unstable(feature = "file_type", reason = "recently added API")]
505 pub fn file_type(&self) -> FileType {
506 FileType(self.0.file_type())
509 /// Returns whether this metadata is for a directory.
514 /// # fn foo() -> std::io::Result<()> {
517 /// let metadata = try!(fs::metadata("foo.txt"));
519 /// assert!(!metadata.is_dir());
523 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
526 /// Returns whether this metadata is for a regular file.
531 /// # fn foo() -> std::io::Result<()> {
534 /// let metadata = try!(fs::metadata("foo.txt"));
536 /// assert!(metadata.is_file());
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn is_file(&self) -> bool { self.file_type().is_file() }
543 /// Returns the size of the file, in bytes, this metadata is for.
548 /// # fn foo() -> std::io::Result<()> {
551 /// let metadata = try!(fs::metadata("foo.txt"));
553 /// assert_eq!(0, metadata.len());
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn len(&self) -> u64 { self.0.size() }
560 /// Returns the permissions of the file this metadata is for.
565 /// # fn foo() -> std::io::Result<()> {
568 /// let metadata = try!(fs::metadata("foo.txt"));
570 /// assert!(!metadata.permissions().readonly());
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn permissions(&self) -> Permissions {
576 Permissions(self.0.perm())
579 /// Returns the most recent access time for a file.
581 /// The return value is in milliseconds since the epoch.
582 #[unstable(feature = "fs_time",
583 reason = "the return type of u64 is not quite appropriate for \
584 this method and may change if the standard library \
585 gains a type to represent a moment in time")]
586 #[deprecated(since = "1.1.0",
587 reason = "use os::platform::fs::MetadataExt extension traits")]
588 pub fn accessed(&self) -> u64 {
589 self.adjust_time(self.0.accessed())
592 /// Returns the most recent modification time for a file.
594 /// The return value is in milliseconds since the epoch.
595 #[unstable(feature = "fs_time",
596 reason = "the return type of u64 is not quite appropriate for \
597 this method and may change if the standard library \
598 gains a type to represent a moment in time")]
599 #[deprecated(since = "1.1.0",
600 reason = "use os::platform::fs::MetadataExt extension traits")]
601 pub fn modified(&self) -> u64 {
602 self.adjust_time(self.0.modified())
605 fn adjust_time(&self, val: u64) -> u64 {
606 // FILETIME (what `val` represents) is in 100ns intervals and there are
607 // 10000 intervals in a millisecond.
608 if cfg!(windows) {val / 10000} else {val}
612 impl AsInner<fs_imp::FileAttr> for Metadata {
613 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
617 /// Returns whether these permissions describe a readonly file.
622 /// use std::fs::File;
624 /// # fn foo() -> std::io::Result<()> {
625 /// let mut f = try!(File::create("foo.txt"));
626 /// let metadata = try!(f.metadata());
628 /// assert_eq!(false, metadata.permissions().readonly());
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn readonly(&self) -> bool { self.0.readonly() }
635 /// Modifies the readonly flag for this set of permissions.
637 /// This operation does **not** modify the filesystem. To modify the
638 /// filesystem use the `fs::set_permissions` function.
643 /// use std::fs::File;
645 /// # fn foo() -> std::io::Result<()> {
646 /// let f = try!(File::create("foo.txt"));
647 /// let metadata = try!(f.metadata());
648 /// let mut permissions = metadata.permissions();
650 /// permissions.set_readonly(true);
652 /// // filesystem doesn't change
653 /// assert_eq!(false, metadata.permissions().readonly());
655 /// // just this particular `permissions`.
656 /// assert_eq!(true, permissions.readonly());
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn set_readonly(&mut self, readonly: bool) {
662 self.0.set_readonly(readonly)
666 #[unstable(feature = "file_type", reason = "recently added API")]
668 /// Test whether this file type represents a directory.
669 pub fn is_dir(&self) -> bool { self.0.is_dir() }
671 /// Test whether this file type represents a regular file.
672 pub fn is_file(&self) -> bool { self.0.is_file() }
674 /// Test whether this file type represents a symbolic link.
675 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
678 impl FromInner<fs_imp::FilePermissions> for Permissions {
679 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
684 impl AsInner<fs_imp::FilePermissions> for Permissions {
685 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl Iterator for ReadDir {
690 type Item = io::Result<DirEntry>;
692 fn next(&mut self) -> Option<io::Result<DirEntry>> {
693 self.0.next().map(|entry| entry.map(DirEntry))
697 #[stable(feature = "rust1", since = "1.0.0")]
699 /// Returns the full path to the file that this entry represents.
701 /// The full path is created by joining the original path to `read_dir` or
702 /// `walk_dir` with the filename of this entry.
708 /// # fn foo() -> std::io::Result<()> {
709 /// for entry in try!(fs::read_dir(".")) {
710 /// let dir = try!(entry);
711 /// println!("{:?}", dir.path());
717 /// This prints output like:
722 /// "./hello_world.rs"
725 /// The exact text, of course, depends on what files you have in `.`.
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn path(&self) -> PathBuf { self.0.path() }
729 /// Return the metadata for the file that this entry points at.
731 /// This function will not traverse symlinks if this entry points at a
734 /// # Platform behavior
736 /// On Windows this function is cheap to call (no extra system calls
737 /// needed), but on Unix platforms this function is the equivalent of
738 /// calling `symlink_metadata` on the path.
739 #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
740 pub fn metadata(&self) -> io::Result<Metadata> {
741 self.0.metadata().map(Metadata)
744 /// Return the file type for the file that this entry points at.
746 /// This function will not traverse symlinks if this entry points at a
749 /// # Platform behavior
751 /// On Windows and most Unix platforms this function is free (no extra
752 /// system calls needed), but some Unix platforms may require the equivalent
753 /// call to `symlink_metadata` to learn about the target file type.
754 #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
755 pub fn file_type(&self) -> io::Result<FileType> {
756 self.0.file_type().map(FileType)
759 /// Returns the bare file name of this directory entry without any other
760 /// leading path component.
761 #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
762 pub fn file_name(&self) -> OsString {
767 impl AsInner<fs_imp::DirEntry> for DirEntry {
768 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
771 /// Removes a file from the underlying filesystem.
773 /// Note that, just because an unlink call was successful, it is not
774 /// guaranteed that a file is immediately deleted (e.g. depending on
775 /// platform, other open file descriptors may prevent immediate removal).
779 /// This function will return an error if `path` points to a directory, if the
780 /// user lacks permissions to remove the file, or if some other filesystem-level
788 /// # fn foo() -> std::io::Result<()> {
789 /// try!(fs::remove_file("a.txt"));
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
795 fs_imp::unlink(path.as_ref())
798 /// Given a path, query the file system to get information about a file,
801 /// This function will traverse symbolic links to query information about the
802 /// destination file.
807 /// # fn foo() -> std::io::Result<()> {
810 /// let attr = try!(fs::metadata("/some/file/path.txt"));
811 /// // inspect attr ...
818 /// This function will return an error if the user lacks the requisite
819 /// permissions to perform a `metadata` call on the given `path` or if there
820 /// is no entry in the filesystem at the provided path.
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
823 fs_imp::stat(path.as_ref()).map(Metadata)
826 /// Query the metadata about a file without following symlinks.
831 /// #![feature(symlink_metadata)]
832 /// # fn foo() -> std::io::Result<()> {
835 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
836 /// // inspect attr ...
840 #[unstable(feature = "symlink_metadata", reason = "recently added API")]
841 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
842 fs_imp::lstat(path.as_ref()).map(Metadata)
845 /// Rename a file or directory to a new name.
849 /// This function will return an error if the provided `from` doesn't exist, if
850 /// the process lacks permissions to view the contents, if `from` and `to`
851 /// reside on separate filesystems, or if some other intermittent I/O error
859 /// # fn foo() -> std::io::Result<()> {
860 /// try!(fs::rename("a.txt", "b.txt"));
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
866 fs_imp::rename(from.as_ref(), to.as_ref())
869 /// Copies the contents of one file to another. This function will also
870 /// copy the permission bits of the original file to the destination file.
872 /// This function will **overwrite** the contents of `to`.
874 /// Note that if `from` and `to` both point to the same file, then the file
875 /// will likely get truncated by this operation.
879 /// This function will return an error in the following situations, but is not
880 /// limited to just these cases:
882 /// * The `from` path is not a file
883 /// * The `from` file does not exist
884 /// * The current process does not have the permission rights to access
885 /// `from` or write `to`
892 /// # fn foo() -> std::io::Result<()> {
893 /// try!(fs::copy("foo.txt", "bar.txt"));
896 #[stable(feature = "rust1", since = "1.0.0")]
897 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
898 let from = from.as_ref();
899 let to = to.as_ref();
901 return Err(Error::new(ErrorKind::InvalidInput,
902 "the source path is not an existing file"))
905 let mut reader = try!(File::open(from));
906 let mut writer = try!(File::create(to));
907 let perm = try!(reader.metadata()).permissions();
909 let ret = try!(io::copy(&mut reader, &mut writer));
910 try!(set_permissions(to, perm));
914 /// Creates a new hard link on the filesystem.
916 /// The `dst` path will be a link pointing to the `src` path. Note that systems
917 /// often require these two paths to both be located on the same filesystem.
924 /// # fn foo() -> std::io::Result<()> {
925 /// try!(fs::hard_link("a.txt", "b.txt"));
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
931 fs_imp::link(src.as_ref(), dst.as_ref())
934 /// Creates a new symbolic link on the filesystem.
936 /// The `dst` path will be a symbolic link pointing to the `src` path.
937 /// On Windows, this will be a file symlink, not a directory symlink;
938 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
939 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
940 /// used instead to make the intent explicit.
947 /// # fn foo() -> std::io::Result<()> {
948 /// try!(fs::soft_link("a.txt", "b.txt"));
952 #[deprecated(since = "1.0.0",
953 reason = "replaced with std::os::unix::fs::symlink and \
954 std::os::windows::fs::{symlink_file, symlink_dir}")]
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
957 fs_imp::symlink(src.as_ref(), dst.as_ref())
960 /// Reads a symbolic link, returning the file that the link points to.
964 /// This function will return an error on failure. Failure conditions include
965 /// reading a file that does not exist or reading a file that is not a symbolic
973 /// # fn foo() -> std::io::Result<()> {
974 /// let path = try!(fs::read_link("a.txt"));
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
980 fs_imp::readlink(path.as_ref())
983 /// Returns the canonical form of a path with all intermediate components
984 /// normalized and symbolic links resolved.
985 #[unstable(feature = "fs_canonicalize", reason = "recently added API")]
986 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
987 fs_imp::canonicalize(path.as_ref())
990 /// Creates a new, empty directory at the provided path
994 /// This function will return an error if the user lacks permissions to make a
995 /// new directory at the provided `path`, or if the directory already exists.
1002 /// # fn foo() -> std::io::Result<()> {
1003 /// try!(fs::create_dir("/some/dir"));
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1009 DirBuilder::new().create(path.as_ref())
1012 /// Recursively create a directory and all of its parent components if they
1017 /// This function will fail if any directory in the path specified by `path`
1018 /// does not already exist and it could not be created otherwise. The specific
1019 /// error conditions for when a directory is being created (after it is
1020 /// determined to not exist) are outlined by `fs::create_dir`.
1027 /// # fn foo() -> std::io::Result<()> {
1028 /// try!(fs::create_dir_all("/some/dir"));
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1034 DirBuilder::new().recursive(true).create(path.as_ref())
1037 /// Removes an existing, empty directory.
1041 /// This function will return an error if the user lacks permissions to remove
1042 /// the directory at the provided `path`, or if the directory isn't empty.
1049 /// # fn foo() -> std::io::Result<()> {
1050 /// try!(fs::remove_dir("/some/dir"));
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1056 fs_imp::rmdir(path.as_ref())
1059 /// Removes a directory at this path, after removing all its contents. Use
1062 /// This function does **not** follow symbolic links and it will simply remove the
1063 /// symbolic link itself.
1067 /// See `file::remove_file` and `fs::remove_dir`.
1074 /// # fn foo() -> std::io::Result<()> {
1075 /// try!(fs::remove_dir_all("/some/dir"));
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1081 let path = path.as_ref();
1082 for child in try!(read_dir(path)) {
1083 let child = try!(child).path();
1084 let stat = try!(symlink_metadata(&*child));
1086 try!(remove_dir_all(&*child));
1088 try!(remove_file(&*child));
1094 /// Returns an iterator over the entries within a directory.
1096 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1097 /// be encountered after an iterator is initially constructed.
1103 /// use std::fs::{self, DirEntry};
1104 /// use std::path::Path;
1106 /// // one possible implementation of fs::walk_dir only visiting files
1107 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1108 /// if try!(fs::metadata(dir)).is_dir() {
1109 /// for entry in try!(fs::read_dir(dir)) {
1110 /// let entry = try!(entry);
1111 /// if try!(fs::metadata(entry.path())).is_dir() {
1112 /// try!(visit_dirs(&entry.path(), cb));
1124 /// This function will return an error if the provided `path` doesn't exist, if
1125 /// the process lacks permissions to view the contents or if the `path` points
1126 /// at a non-directory file
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1129 fs_imp::readdir(path.as_ref()).map(ReadDir)
1132 /// Returns an iterator that will recursively walk the directory structure
1133 /// rooted at `path`.
1135 /// The path given will not be iterated over, and this will perform iteration in
1136 /// some top-down order. The contents of unreadable subdirectories are ignored.
1138 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1139 /// be encountered after an iterator is initially constructed.
1140 #[unstable(feature = "fs_walk",
1141 reason = "the precise semantics and defaults for a recursive walk \
1142 may change and this may end up accounting for files such \
1143 as symlinks differently")]
1144 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1145 let start = try!(read_dir(path));
1146 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1149 #[unstable(feature = "fs_walk")]
1150 impl Iterator for WalkDir {
1151 type Item = io::Result<DirEntry>;
1153 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1155 if let Some(ref mut cur) = self.cur {
1157 Some(Err(e)) => return Some(Err(e)),
1159 let path = next.path();
1161 self.stack.push(read_dir(&*path));
1163 return Some(Ok(next))
1169 match self.stack.pop() {
1170 Some(Err(e)) => return Some(Err(e)),
1171 Some(Ok(next)) => self.cur = Some(next),
1172 None => return None,
1178 /// Utility methods for paths.
1179 #[unstable(feature = "path_ext",
1180 reason = "the precise set of methods exposed on this trait may \
1181 change and some methods may be removed")]
1183 /// Gets information on the file, directory, etc at this path.
1185 /// Consult the `fs::metadata` documentation for more info.
1187 /// This call preserves identical runtime/error semantics with
1189 fn metadata(&self) -> io::Result<Metadata>;
1191 /// Gets information on the file, directory, etc at this path.
1193 /// Consult the `fs::symlink_metadata` documentation for more info.
1195 /// This call preserves identical runtime/error semantics with
1196 /// `fs::symlink_metadata`.
1197 fn symlink_metadata(&self) -> io::Result<Metadata>;
1199 /// Returns the canonical form of a path, normalizing all components and
1200 /// eliminate all symlinks.
1202 /// This call preserves identical runtime/error semantics with
1203 /// `fs::canonicalize`.
1204 fn canonicalize(&self) -> io::Result<PathBuf>;
1206 /// Reads the symlink at this path.
1208 /// For more information see `fs::read_link`.
1209 fn read_link(&self) -> io::Result<PathBuf>;
1211 /// Reads the directory at this path.
1213 /// For more information see `fs::read_dir`.
1214 fn read_dir(&self) -> io::Result<ReadDir>;
1216 /// Boolean value indicator whether the underlying file exists on the local
1217 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1218 fn exists(&self) -> bool;
1220 /// Whether the underlying implementation (be it a file path, or something
1221 /// else) points at a "regular file" on the FS. Will return false for paths
1222 /// to non-existent locations or directories or other non-regular files
1223 /// (named pipes, etc). Follows links when making this determination.
1224 fn is_file(&self) -> bool;
1226 /// Whether the underlying implementation (be it a file path, or something
1227 /// else) is pointing at a directory in the underlying FS. Will return
1228 /// false for paths to non-existent locations or if the item is not a
1229 /// directory (eg files, named pipes, etc). Follows links when making this
1231 fn is_dir(&self) -> bool;
1234 impl PathExt for Path {
1235 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1236 fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1237 fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1238 fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1239 fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1240 fn exists(&self) -> bool { metadata(self).is_ok() }
1242 fn is_file(&self) -> bool {
1243 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1246 fn is_dir(&self) -> bool {
1247 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1251 /// Changes the timestamps for a file's last modification and access time.
1253 /// The file at the path specified will have its last access time set to
1254 /// `accessed` and its modification time set to `modified`. The times specified
1255 /// should be in milliseconds.
1256 #[unstable(feature = "fs_time",
1257 reason = "the argument type of u64 is not quite appropriate for \
1258 this function and may change if the standard library \
1259 gains a type to represent a moment in time")]
1260 pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
1261 modified: u64) -> io::Result<()> {
1262 fs_imp::utimes(path.as_ref(), accessed, modified)
1265 /// Changes the permissions found on a file or a directory.
1270 /// # #![feature(fs)]
1271 /// # fn foo() -> std::io::Result<()> {
1274 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1275 /// perms.set_readonly(true);
1276 /// try!(fs::set_permissions("foo.txt", perms));
1283 /// This function will return an error if the provided `path` doesn't exist, if
1284 /// the process lacks permissions to change the attributes of the file, or if
1285 /// some other I/O error is encountered.
1286 #[unstable(feature = "fs",
1287 reason = "a more granual ability to set specific permissions may \
1288 be exposed on the Permissions structure itself and this \
1289 method may not always exist")]
1290 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
1291 fs_imp::set_perm(path.as_ref(), perm.0)
1295 /// Creates a new set of options with default mode/security settings for all
1296 /// platforms and also non-recursive.
1297 pub fn new() -> DirBuilder {
1299 inner: fs_imp::DirBuilder::new(),
1304 /// Indicate that directories create should be created recursively, creating
1305 /// all parent directories if they do not exist with the same security and
1306 /// permissions settings.
1308 /// This option defaults to `false`
1309 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1310 self.recursive = recursive;
1314 /// Create the specified directory with the options configured in this
1316 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1317 let path = path.as_ref();
1319 self.create_dir_all(path)
1321 self.inner.mkdir(path)
1325 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1326 if path == Path::new("") || path.is_dir() { return Ok(()) }
1327 if let Some(p) = path.parent() {
1328 try!(self.create_dir_all(p))
1330 self.inner.mkdir(path)
1334 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1335 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1342 #![allow(deprecated)] //rand
1348 use fs::{self, File, OpenOptions};
1349 use io::{ErrorKind, SeekFrom};
1351 use path::Path as Path2;
1353 use rand::{self, StdRng, Rng};
1356 macro_rules! check { ($e:expr) => (
1359 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1363 macro_rules! error { ($e:expr, $s:expr) => (
1365 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1366 Err(ref err) => assert!(err.to_string().contains($s),
1367 format!("`{}` did not contain `{}`", err, $s))
1371 pub struct TempDir(PathBuf);
1374 fn join(&self, path: &str) -> PathBuf {
1375 let TempDir(ref p) = *self;
1379 fn path<'a>(&'a self) -> &'a Path2 {
1380 let TempDir(ref p) = *self;
1385 impl Drop for TempDir {
1386 fn drop(&mut self) {
1387 // Gee, seeing how we're testing the fs module I sure hope that we
1388 // at least implement this correctly!
1389 let TempDir(ref p) = *self;
1390 check!(fs::remove_dir_all(p));
1394 pub fn tmpdir() -> TempDir {
1395 let p = env::temp_dir();
1396 let mut r = rand::thread_rng();
1397 let ret = p.join(&format!("rust-{}", r.next_u32()));
1398 check!(fs::create_dir(&ret));
1403 fn file_test_io_smoke_test() {
1404 let message = "it's alright. have a good time";
1405 let tmpdir = tmpdir();
1406 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1408 let mut write_stream = check!(File::create(filename));
1409 check!(write_stream.write(message.as_bytes()));
1412 let mut read_stream = check!(File::open(filename));
1413 let mut read_buf = [0; 1028];
1414 let read_str = match check!(read_stream.read(&mut read_buf)) {
1415 0 => panic!("shouldn't happen"),
1416 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1418 assert_eq!(read_str, message);
1420 check!(fs::remove_file(filename));
1424 fn invalid_path_raises() {
1425 let tmpdir = tmpdir();
1426 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1427 let result = File::open(filename);
1430 error!(result, "o such file or directory");
1432 // error!(result, "couldn't open path as file");
1433 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1437 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1438 let tmpdir = tmpdir();
1439 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1441 let result = fs::remove_file(filename);
1444 error!(result, "o such file or directory");
1446 // error!(result, "couldn't unlink path");
1447 // error!(result, format!("path={}", filename.display()));
1451 fn file_test_io_non_positional_read() {
1452 let message: &str = "ten-four";
1453 let mut read_mem = [0; 8];
1454 let tmpdir = tmpdir();
1455 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1457 let mut rw_stream = check!(File::create(filename));
1458 check!(rw_stream.write(message.as_bytes()));
1461 let mut read_stream = check!(File::open(filename));
1463 let read_buf = &mut read_mem[0..4];
1464 check!(read_stream.read(read_buf));
1467 let read_buf = &mut read_mem[4..8];
1468 check!(read_stream.read(read_buf));
1471 check!(fs::remove_file(filename));
1472 let read_str = str::from_utf8(&read_mem).unwrap();
1473 assert_eq!(read_str, message);
1477 fn file_test_io_seek_and_tell_smoke_test() {
1478 let message = "ten-four";
1479 let mut read_mem = [0; 4];
1480 let set_cursor = 4 as u64;
1481 let mut tell_pos_pre_read;
1482 let mut tell_pos_post_read;
1483 let tmpdir = tmpdir();
1484 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1486 let mut rw_stream = check!(File::create(filename));
1487 check!(rw_stream.write(message.as_bytes()));
1490 let mut read_stream = check!(File::open(filename));
1491 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1492 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1493 check!(read_stream.read(&mut read_mem));
1494 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1496 check!(fs::remove_file(filename));
1497 let read_str = str::from_utf8(&read_mem).unwrap();
1498 assert_eq!(read_str, &message[4..8]);
1499 assert_eq!(tell_pos_pre_read, set_cursor);
1500 assert_eq!(tell_pos_post_read, message.len() as u64);
1504 fn file_test_io_seek_and_write() {
1505 let initial_msg = "food-is-yummy";
1506 let overwrite_msg = "-the-bar!!";
1507 let final_msg = "foo-the-bar!!";
1509 let mut read_mem = [0; 13];
1510 let tmpdir = tmpdir();
1511 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1513 let mut rw_stream = check!(File::create(filename));
1514 check!(rw_stream.write(initial_msg.as_bytes()));
1515 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1516 check!(rw_stream.write(overwrite_msg.as_bytes()));
1519 let mut read_stream = check!(File::open(filename));
1520 check!(read_stream.read(&mut read_mem));
1522 check!(fs::remove_file(filename));
1523 let read_str = str::from_utf8(&read_mem).unwrap();
1524 assert!(read_str == final_msg);
1528 fn file_test_io_seek_shakedown() {
1530 let initial_msg = "qwer-asdf-zxcv";
1531 let chunk_one: &str = "qwer";
1532 let chunk_two: &str = "asdf";
1533 let chunk_three: &str = "zxcv";
1534 let mut read_mem = [0; 4];
1535 let tmpdir = tmpdir();
1536 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1538 let mut rw_stream = check!(File::create(filename));
1539 check!(rw_stream.write(initial_msg.as_bytes()));
1542 let mut read_stream = check!(File::open(filename));
1544 check!(read_stream.seek(SeekFrom::End(-4)));
1545 check!(read_stream.read(&mut read_mem));
1546 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1548 check!(read_stream.seek(SeekFrom::Current(-9)));
1549 check!(read_stream.read(&mut read_mem));
1550 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1552 check!(read_stream.seek(SeekFrom::Start(0)));
1553 check!(read_stream.read(&mut read_mem));
1554 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1556 check!(fs::remove_file(filename));
1560 fn file_test_stat_is_correct_on_is_file() {
1561 let tmpdir = tmpdir();
1562 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1564 let mut opts = OpenOptions::new();
1565 let mut fs = check!(opts.read(true).write(true)
1566 .create(true).open(filename));
1568 fs.write(msg.as_bytes()).unwrap();
1570 let fstat_res = check!(fs.metadata());
1571 assert!(fstat_res.is_file());
1573 let stat_res_fn = check!(fs::metadata(filename));
1574 assert!(stat_res_fn.is_file());
1575 let stat_res_meth = check!(filename.metadata());
1576 assert!(stat_res_meth.is_file());
1577 check!(fs::remove_file(filename));
1581 fn file_test_stat_is_correct_on_is_dir() {
1582 let tmpdir = tmpdir();
1583 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1584 check!(fs::create_dir(filename));
1585 let stat_res_fn = check!(fs::metadata(filename));
1586 assert!(stat_res_fn.is_dir());
1587 let stat_res_meth = check!(filename.metadata());
1588 assert!(stat_res_meth.is_dir());
1589 check!(fs::remove_dir(filename));
1593 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1594 let tmpdir = tmpdir();
1595 let dir = &tmpdir.join("fileinfo_false_on_dir");
1596 check!(fs::create_dir(dir));
1597 assert!(dir.is_file() == false);
1598 check!(fs::remove_dir(dir));
1602 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1603 let tmpdir = tmpdir();
1604 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1605 check!(check!(File::create(file)).write(b"foo"));
1606 assert!(file.exists());
1607 check!(fs::remove_file(file));
1608 assert!(!file.exists());
1612 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1613 let tmpdir = tmpdir();
1614 let dir = &tmpdir.join("before_and_after_dir");
1615 assert!(!dir.exists());
1616 check!(fs::create_dir(dir));
1617 assert!(dir.exists());
1618 assert!(dir.is_dir());
1619 check!(fs::remove_dir(dir));
1620 assert!(!dir.exists());
1624 fn file_test_directoryinfo_readdir() {
1625 let tmpdir = tmpdir();
1626 let dir = &tmpdir.join("di_readdir");
1627 check!(fs::create_dir(dir));
1630 let f = dir.join(&format!("{}.txt", n));
1631 let mut w = check!(File::create(&f));
1632 let msg_str = format!("{}{}", prefix, n.to_string());
1633 let msg = msg_str.as_bytes();
1634 check!(w.write(msg));
1636 let files = check!(fs::read_dir(dir));
1637 let mut mem = [0; 4];
1639 let f = f.unwrap().path();
1641 let n = f.file_stem().unwrap();
1642 check!(check!(File::open(&f)).read(&mut mem));
1643 let read_str = str::from_utf8(&mem).unwrap();
1644 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1645 assert_eq!(expected, read_str);
1647 check!(fs::remove_file(&f));
1649 check!(fs::remove_dir(dir));
1653 fn file_test_walk_dir() {
1654 let tmpdir = tmpdir();
1655 let dir = &tmpdir.join("walk_dir");
1656 check!(fs::create_dir(dir));
1658 let dir1 = &dir.join("01/02/03");
1659 check!(fs::create_dir_all(dir1));
1660 check!(File::create(&dir1.join("04")));
1662 let dir2 = &dir.join("11/12/13");
1663 check!(fs::create_dir_all(dir2));
1664 check!(File::create(&dir2.join("14")));
1666 let files = check!(fs::walk_dir(dir));
1667 let mut cur = [0; 2];
1669 let f = f.unwrap().path();
1670 let stem = f.file_stem().unwrap().to_str().unwrap();
1671 let root = stem.as_bytes()[0] - b'0';
1672 let name = stem.as_bytes()[1] - b'0';
1673 assert!(cur[root as usize] < name);
1674 cur[root as usize] = name;
1677 check!(fs::remove_dir_all(dir));
1681 fn mkdir_path_already_exists_error() {
1682 let tmpdir = tmpdir();
1683 let dir = &tmpdir.join("mkdir_error_twice");
1684 check!(fs::create_dir(dir));
1685 let e = fs::create_dir(dir).err().unwrap();
1686 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1690 fn recursive_mkdir() {
1691 let tmpdir = tmpdir();
1692 let dir = tmpdir.join("d1/d2");
1693 check!(fs::create_dir_all(&dir));
1694 assert!(dir.is_dir())
1698 fn recursive_mkdir_failure() {
1699 let tmpdir = tmpdir();
1700 let dir = tmpdir.join("d1");
1701 let file = dir.join("f1");
1703 check!(fs::create_dir_all(&dir));
1704 check!(File::create(&file));
1706 let result = fs::create_dir_all(&file);
1708 assert!(result.is_err());
1709 // error!(result, "couldn't recursively mkdir");
1710 // error!(result, "couldn't create directory");
1711 // error!(result, "mode=0700");
1712 // error!(result, format!("path={}", file.display()));
1716 fn recursive_mkdir_slash() {
1717 check!(fs::create_dir_all(&Path2::new("/")));
1720 // FIXME(#12795) depends on lstat to work on windows
1721 #[cfg(not(windows))]
1723 fn recursive_rmdir() {
1724 let tmpdir = tmpdir();
1725 let d1 = tmpdir.join("d1");
1726 let dt = d1.join("t");
1727 let dtt = dt.join("t");
1728 let d2 = tmpdir.join("d2");
1729 let canary = d2.join("do_not_delete");
1730 check!(fs::create_dir_all(&dtt));
1731 check!(fs::create_dir_all(&d2));
1732 check!(check!(File::create(&canary)).write(b"foo"));
1733 check!(fs::soft_link(&d2, &dt.join("d2")));
1734 check!(fs::remove_dir_all(&d1));
1736 assert!(!d1.is_dir());
1737 assert!(canary.exists());
1741 fn unicode_path_is_dir() {
1742 assert!(Path2::new(".").is_dir());
1743 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1745 let tmpdir = tmpdir();
1747 let mut dirpath = tmpdir.path().to_path_buf();
1748 dirpath.push(&format!("test-가一ー你好"));
1749 check!(fs::create_dir(&dirpath));
1750 assert!(dirpath.is_dir());
1752 let mut filepath = dirpath;
1753 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1754 check!(File::create(&filepath)); // ignore return; touch only
1755 assert!(!filepath.is_dir());
1756 assert!(filepath.exists());
1760 fn unicode_path_exists() {
1761 assert!(Path2::new(".").exists());
1762 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1764 let tmpdir = tmpdir();
1765 let unicode = tmpdir.path();
1766 let unicode = unicode.join(&format!("test-각丁ー再见"));
1767 check!(fs::create_dir(&unicode));
1768 assert!(unicode.exists());
1769 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1773 fn copy_file_does_not_exist() {
1774 let from = Path2::new("test/nonexistent-bogus-path");
1775 let to = Path2::new("test/other-bogus-path");
1777 match fs::copy(&from, &to) {
1780 assert!(!from.exists());
1781 assert!(!to.exists());
1788 let tmpdir = tmpdir();
1789 let input = tmpdir.join("in.txt");
1790 let out = tmpdir.join("out.txt");
1792 check!(check!(File::create(&input)).write(b"hello"));
1793 check!(fs::copy(&input, &out));
1794 let mut v = Vec::new();
1795 check!(check!(File::open(&out)).read_to_end(&mut v));
1796 assert_eq!(v, b"hello");
1798 assert_eq!(check!(input.metadata()).permissions(),
1799 check!(out.metadata()).permissions());
1803 fn copy_file_dst_dir() {
1804 let tmpdir = tmpdir();
1805 let out = tmpdir.join("out");
1807 check!(File::create(&out));
1808 match fs::copy(&*out, tmpdir.path()) {
1809 Ok(..) => panic!(), Err(..) => {}
1814 fn copy_file_dst_exists() {
1815 let tmpdir = tmpdir();
1816 let input = tmpdir.join("in");
1817 let output = tmpdir.join("out");
1819 check!(check!(File::create(&input)).write("foo".as_bytes()));
1820 check!(check!(File::create(&output)).write("bar".as_bytes()));
1821 check!(fs::copy(&input, &output));
1823 let mut v = Vec::new();
1824 check!(check!(File::open(&output)).read_to_end(&mut v));
1825 assert_eq!(v, b"foo".to_vec());
1829 fn copy_file_src_dir() {
1830 let tmpdir = tmpdir();
1831 let out = tmpdir.join("out");
1833 match fs::copy(tmpdir.path(), &out) {
1834 Ok(..) => panic!(), Err(..) => {}
1836 assert!(!out.exists());
1840 fn copy_file_preserves_perm_bits() {
1841 let tmpdir = tmpdir();
1842 let input = tmpdir.join("in.txt");
1843 let out = tmpdir.join("out.txt");
1845 let attr = check!(check!(File::create(&input)).metadata());
1846 let mut p = attr.permissions();
1847 p.set_readonly(true);
1848 check!(fs::set_permissions(&input, p));
1849 check!(fs::copy(&input, &out));
1850 assert!(check!(out.metadata()).permissions().readonly());
1851 check!(fs::set_permissions(&input, attr.permissions()));
1852 check!(fs::set_permissions(&out, attr.permissions()));
1855 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1857 fn symlinks_work() {
1858 let tmpdir = tmpdir();
1859 let input = tmpdir.join("in.txt");
1860 let out = tmpdir.join("out.txt");
1862 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1863 check!(fs::soft_link(&input, &out));
1864 // if cfg!(not(windows)) {
1865 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1866 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1868 assert_eq!(check!(fs::metadata(&out)).len(),
1869 check!(fs::metadata(&input)).len());
1870 let mut v = Vec::new();
1871 check!(check!(File::open(&out)).read_to_end(&mut v));
1872 assert_eq!(v, b"foobar".to_vec());
1875 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1877 fn symlink_noexist() {
1878 let tmpdir = tmpdir();
1879 // symlinks can point to things that don't exist
1880 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1881 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1882 tmpdir.join("foo"));
1886 fn readlink_not_symlink() {
1887 let tmpdir = tmpdir();
1888 match fs::read_link(tmpdir.path()) {
1889 Ok(..) => panic!("wanted a failure"),
1896 let tmpdir = tmpdir();
1897 let input = tmpdir.join("in.txt");
1898 let out = tmpdir.join("out.txt");
1900 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1901 check!(fs::hard_link(&input, &out));
1902 assert_eq!(check!(fs::metadata(&out)).len(),
1903 check!(fs::metadata(&input)).len());
1904 assert_eq!(check!(fs::metadata(&out)).len(),
1905 check!(input.metadata()).len());
1906 let mut v = Vec::new();
1907 check!(check!(File::open(&out)).read_to_end(&mut v));
1908 assert_eq!(v, b"foobar".to_vec());
1910 // can't link to yourself
1911 match fs::hard_link(&input, &input) {
1912 Ok(..) => panic!("wanted a failure"),
1915 // can't link to something that doesn't exist
1916 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1917 Ok(..) => panic!("wanted a failure"),
1924 let tmpdir = tmpdir();
1925 let file = tmpdir.join("in.txt");
1927 check!(File::create(&file));
1928 let attr = check!(fs::metadata(&file));
1929 assert!(!attr.permissions().readonly());
1930 let mut p = attr.permissions();
1931 p.set_readonly(true);
1932 check!(fs::set_permissions(&file, p.clone()));
1933 let attr = check!(fs::metadata(&file));
1934 assert!(attr.permissions().readonly());
1936 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1937 Ok(..) => panic!("wanted an error"),
1941 p.set_readonly(false);
1942 check!(fs::set_permissions(&file, p));
1946 fn sync_doesnt_kill_anything() {
1947 let tmpdir = tmpdir();
1948 let path = tmpdir.join("in.txt");
1950 let mut file = check!(File::create(&path));
1951 check!(file.sync_all());
1952 check!(file.sync_data());
1953 check!(file.write(b"foo"));
1954 check!(file.sync_all());
1955 check!(file.sync_data());
1959 fn truncate_works() {
1960 let tmpdir = tmpdir();
1961 let path = tmpdir.join("in.txt");
1963 let mut file = check!(File::create(&path));
1964 check!(file.write(b"foo"));
1965 check!(file.sync_all());
1967 // Do some simple things with truncation
1968 assert_eq!(check!(file.metadata()).len(), 3);
1969 check!(file.set_len(10));
1970 assert_eq!(check!(file.metadata()).len(), 10);
1971 check!(file.write(b"bar"));
1972 check!(file.sync_all());
1973 assert_eq!(check!(file.metadata()).len(), 10);
1975 let mut v = Vec::new();
1976 check!(check!(File::open(&path)).read_to_end(&mut v));
1977 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1979 // Truncate to a smaller length, don't seek, and then write something.
1980 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1981 // past the end of the file).
1982 check!(file.set_len(2));
1983 assert_eq!(check!(file.metadata()).len(), 2);
1984 check!(file.write(b"wut"));
1985 check!(file.sync_all());
1986 assert_eq!(check!(file.metadata()).len(), 9);
1987 let mut v = Vec::new();
1988 check!(check!(File::open(&path)).read_to_end(&mut v));
1989 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1994 use fs::OpenOptions as OO;
1995 fn c<T: Clone>(t: &T) -> T { t.clone() }
1997 let tmpdir = tmpdir();
1999 let mut r = OO::new(); r.read(true);
2000 let mut w = OO::new(); w.write(true);
2001 let mut rw = OO::new(); rw.write(true).read(true);
2003 match r.open(&tmpdir.join("a")) {
2004 Ok(..) => panic!(), Err(..) => {}
2007 // Perform each one twice to make sure that it succeeds the second time
2008 // (where the file exists)
2009 check!(c(&w).create(true).open(&tmpdir.join("b")));
2010 assert!(tmpdir.join("b").exists());
2011 check!(c(&w).create(true).open(&tmpdir.join("b")));
2012 check!(w.open(&tmpdir.join("b")));
2014 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2015 assert!(tmpdir.join("c").exists());
2016 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2017 check!(rw.open(&tmpdir.join("c")));
2019 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2020 assert!(tmpdir.join("d").exists());
2021 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2022 check!(c(&w).append(true).open(&tmpdir.join("d")));
2024 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2025 assert!(tmpdir.join("e").exists());
2026 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2027 check!(c(&rw).append(true).open(&tmpdir.join("e")));
2029 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2030 assert!(tmpdir.join("f").exists());
2031 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2032 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2034 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2035 assert!(tmpdir.join("g").exists());
2036 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2037 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2039 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2040 check!(r.open(&tmpdir.join("h")));
2042 let mut f = check!(r.open(&tmpdir.join("h")));
2043 assert!(f.write("wut".as_bytes()).is_err());
2045 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2047 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2048 check!(f.write("bar".as_bytes()));
2050 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2052 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2053 check!(f.write("bar".as_bytes()));
2055 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2060 let tmpdir = tmpdir();
2061 let path = tmpdir.join("a");
2062 check!(File::create(&path));
2063 // These numbers have to be bigger than the time in the day to account
2064 // for timezones Windows in particular will fail in certain timezones
2065 // with small enough values
2066 check!(fs::set_file_times(&path, 100000, 200000));
2067 assert_eq!(check!(path.metadata()).accessed(), 100000);
2068 assert_eq!(check!(path.metadata()).modified(), 200000);
2072 fn utime_noexist() {
2073 let tmpdir = tmpdir();
2075 match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
2083 let mut bytes = [0; 1024];
2084 StdRng::new().unwrap().fill_bytes(&mut bytes);
2086 let tmpdir = tmpdir();
2088 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2089 let mut v = Vec::new();
2090 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2091 assert!(v == &bytes[..]);
2095 #[cfg(not(windows))]
2096 fn unlink_readonly() {
2097 let tmpdir = tmpdir();
2098 let path = tmpdir.join("file");
2099 check!(File::create(&path));
2100 let mut perm = check!(fs::metadata(&path)).permissions();
2101 perm.set_readonly(true);
2102 check!(fs::set_permissions(&path, perm));
2103 check!(fs::remove_file(&path));
2107 fn mkdir_trailing_slash() {
2108 let tmpdir = tmpdir();
2109 let path = tmpdir.join("file");
2110 check!(fs::create_dir_all(&path.join("a/")));
2114 #[cfg(not(windows))]
2115 fn realpath_works() {
2116 let tmpdir = tmpdir();
2117 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2118 let file = tmpdir.join("test");
2119 let dir = tmpdir.join("test2");
2120 let link = dir.join("link");
2121 let linkdir = tmpdir.join("test3");
2123 File::create(&file).unwrap();
2124 fs::create_dir(&dir).unwrap();
2125 fs::soft_link(&file, &link).unwrap();
2126 fs::soft_link(&dir, &linkdir).unwrap();
2128 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2130 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2131 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2132 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2133 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2134 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2138 #[cfg(not(windows))]
2139 fn realpath_works_tricky() {
2140 let tmpdir = tmpdir();
2141 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2143 let a = tmpdir.join("a");
2144 let b = a.join("b");
2145 let c = b.join("c");
2146 let d = a.join("d");
2147 let e = d.join("e");
2148 let f = a.join("f");
2150 fs::create_dir_all(&b).unwrap();
2151 fs::create_dir_all(&d).unwrap();
2152 File::create(&f).unwrap();
2153 fs::soft_link("../d/e", &c).unwrap();
2154 fs::soft_link("../f", &e).unwrap();
2156 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2157 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2161 fn dir_entry_methods() {
2162 let tmpdir = tmpdir();
2164 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2165 File::create(&tmpdir.join("b")).unwrap();
2167 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2168 let fname = file.file_name();
2169 match fname.to_str() {
2171 assert!(file.file_type().unwrap().is_dir());
2172 assert!(file.metadata().unwrap().is_dir());
2175 assert!(file.file_type().unwrap().is_file());
2176 assert!(file.metadata().unwrap().is_file());
2178 f => panic!("unknown file name: {:?}", f),