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. For stable code, \
1182 see the std::fs::metadata function.")]
1184 /// Gets information on the file, directory, etc at this path.
1186 /// Consult the `fs::metadata` documentation for more info.
1188 /// This call preserves identical runtime/error semantics with
1190 fn metadata(&self) -> io::Result<Metadata>;
1192 /// Gets information on the file, directory, etc at this path.
1194 /// Consult the `fs::symlink_metadata` documentation for more info.
1196 /// This call preserves identical runtime/error semantics with
1197 /// `fs::symlink_metadata`.
1198 fn symlink_metadata(&self) -> io::Result<Metadata>;
1200 /// Returns the canonical form of a path, normalizing all components and
1201 /// eliminate all symlinks.
1203 /// This call preserves identical runtime/error semantics with
1204 /// `fs::canonicalize`.
1205 fn canonicalize(&self) -> io::Result<PathBuf>;
1207 /// Reads the symlink at this path.
1209 /// For more information see `fs::read_link`.
1210 fn read_link(&self) -> io::Result<PathBuf>;
1212 /// Reads the directory at this path.
1214 /// For more information see `fs::read_dir`.
1215 fn read_dir(&self) -> io::Result<ReadDir>;
1217 /// Boolean value indicator whether the underlying file exists on the local
1218 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1219 fn exists(&self) -> bool;
1221 /// Whether the underlying implementation (be it a file path, or something
1222 /// else) points at a "regular file" on the FS. Will return false for paths
1223 /// to non-existent locations or directories or other non-regular files
1224 /// (named pipes, etc). Follows links when making this determination.
1225 fn is_file(&self) -> bool;
1227 /// Whether the underlying implementation (be it a file path, or something
1228 /// else) is pointing at a directory in the underlying FS. Will return
1229 /// false for paths to non-existent locations or if the item is not a
1230 /// directory (eg files, named pipes, etc). Follows links when making this
1232 fn is_dir(&self) -> bool;
1235 impl PathExt for Path {
1236 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1237 fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1238 fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1239 fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1240 fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1241 fn exists(&self) -> bool { metadata(self).is_ok() }
1243 fn is_file(&self) -> bool {
1244 metadata(self).map(|s| s.is_file()).unwrap_or(false)
1247 fn is_dir(&self) -> bool {
1248 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1252 /// Changes the timestamps for a file's last modification and access time.
1254 /// The file at the path specified will have its last access time set to
1255 /// `accessed` and its modification time set to `modified`. The times specified
1256 /// should be in milliseconds.
1257 #[unstable(feature = "fs_time",
1258 reason = "the argument type of u64 is not quite appropriate for \
1259 this function and may change if the standard library \
1260 gains a type to represent a moment in time")]
1261 pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
1262 modified: u64) -> io::Result<()> {
1263 fs_imp::utimes(path.as_ref(), accessed, modified)
1266 /// Changes the permissions found on a file or a directory.
1271 /// # #![feature(fs)]
1272 /// # fn foo() -> std::io::Result<()> {
1275 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1276 /// perms.set_readonly(true);
1277 /// try!(fs::set_permissions("foo.txt", perms));
1284 /// This function will return an error if the provided `path` doesn't exist, if
1285 /// the process lacks permissions to change the attributes of the file, or if
1286 /// some other I/O error is encountered.
1287 #[unstable(feature = "fs",
1288 reason = "a more granual ability to set specific permissions may \
1289 be exposed on the Permissions structure itself and this \
1290 method may not always exist")]
1291 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
1292 fs_imp::set_perm(path.as_ref(), perm.0)
1296 /// Creates a new set of options with default mode/security settings for all
1297 /// platforms and also non-recursive.
1298 pub fn new() -> DirBuilder {
1300 inner: fs_imp::DirBuilder::new(),
1305 /// Indicate that directories create should be created recursively, creating
1306 /// all parent directories if they do not exist with the same security and
1307 /// permissions settings.
1309 /// This option defaults to `false`
1310 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1311 self.recursive = recursive;
1315 /// Create the specified directory with the options configured in this
1317 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1318 let path = path.as_ref();
1320 self.create_dir_all(path)
1322 self.inner.mkdir(path)
1326 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1327 if path == Path::new("") || path.is_dir() { return Ok(()) }
1328 if let Some(p) = path.parent() {
1329 try!(self.create_dir_all(p))
1331 self.inner.mkdir(path)
1335 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1336 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1343 #![allow(deprecated)] //rand
1349 use fs::{self, File, OpenOptions};
1350 use io::{ErrorKind, SeekFrom};
1352 use path::Path as Path2;
1354 use rand::{self, StdRng, Rng};
1357 macro_rules! check { ($e:expr) => (
1360 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1364 macro_rules! error { ($e:expr, $s:expr) => (
1366 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1367 Err(ref err) => assert!(err.to_string().contains($s),
1368 format!("`{}` did not contain `{}`", err, $s))
1372 pub struct TempDir(PathBuf);
1375 fn join(&self, path: &str) -> PathBuf {
1376 let TempDir(ref p) = *self;
1380 fn path<'a>(&'a self) -> &'a Path2 {
1381 let TempDir(ref p) = *self;
1386 impl Drop for TempDir {
1387 fn drop(&mut self) {
1388 // Gee, seeing how we're testing the fs module I sure hope that we
1389 // at least implement this correctly!
1390 let TempDir(ref p) = *self;
1391 check!(fs::remove_dir_all(p));
1395 pub fn tmpdir() -> TempDir {
1396 let p = env::temp_dir();
1397 let mut r = rand::thread_rng();
1398 let ret = p.join(&format!("rust-{}", r.next_u32()));
1399 check!(fs::create_dir(&ret));
1404 fn file_test_io_smoke_test() {
1405 let message = "it's alright. have a good time";
1406 let tmpdir = tmpdir();
1407 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1409 let mut write_stream = check!(File::create(filename));
1410 check!(write_stream.write(message.as_bytes()));
1413 let mut read_stream = check!(File::open(filename));
1414 let mut read_buf = [0; 1028];
1415 let read_str = match check!(read_stream.read(&mut read_buf)) {
1416 0 => panic!("shouldn't happen"),
1417 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1419 assert_eq!(read_str, message);
1421 check!(fs::remove_file(filename));
1425 fn invalid_path_raises() {
1426 let tmpdir = tmpdir();
1427 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1428 let result = File::open(filename);
1431 error!(result, "o such file or directory");
1433 // error!(result, "couldn't open path as file");
1434 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1438 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1439 let tmpdir = tmpdir();
1440 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1442 let result = fs::remove_file(filename);
1445 error!(result, "o such file or directory");
1447 // error!(result, "couldn't unlink path");
1448 // error!(result, format!("path={}", filename.display()));
1452 fn file_test_io_non_positional_read() {
1453 let message: &str = "ten-four";
1454 let mut read_mem = [0; 8];
1455 let tmpdir = tmpdir();
1456 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1458 let mut rw_stream = check!(File::create(filename));
1459 check!(rw_stream.write(message.as_bytes()));
1462 let mut read_stream = check!(File::open(filename));
1464 let read_buf = &mut read_mem[0..4];
1465 check!(read_stream.read(read_buf));
1468 let read_buf = &mut read_mem[4..8];
1469 check!(read_stream.read(read_buf));
1472 check!(fs::remove_file(filename));
1473 let read_str = str::from_utf8(&read_mem).unwrap();
1474 assert_eq!(read_str, message);
1478 fn file_test_io_seek_and_tell_smoke_test() {
1479 let message = "ten-four";
1480 let mut read_mem = [0; 4];
1481 let set_cursor = 4 as u64;
1482 let mut tell_pos_pre_read;
1483 let mut tell_pos_post_read;
1484 let tmpdir = tmpdir();
1485 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1487 let mut rw_stream = check!(File::create(filename));
1488 check!(rw_stream.write(message.as_bytes()));
1491 let mut read_stream = check!(File::open(filename));
1492 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1493 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1494 check!(read_stream.read(&mut read_mem));
1495 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1497 check!(fs::remove_file(filename));
1498 let read_str = str::from_utf8(&read_mem).unwrap();
1499 assert_eq!(read_str, &message[4..8]);
1500 assert_eq!(tell_pos_pre_read, set_cursor);
1501 assert_eq!(tell_pos_post_read, message.len() as u64);
1505 fn file_test_io_seek_and_write() {
1506 let initial_msg = "food-is-yummy";
1507 let overwrite_msg = "-the-bar!!";
1508 let final_msg = "foo-the-bar!!";
1510 let mut read_mem = [0; 13];
1511 let tmpdir = tmpdir();
1512 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1514 let mut rw_stream = check!(File::create(filename));
1515 check!(rw_stream.write(initial_msg.as_bytes()));
1516 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1517 check!(rw_stream.write(overwrite_msg.as_bytes()));
1520 let mut read_stream = check!(File::open(filename));
1521 check!(read_stream.read(&mut read_mem));
1523 check!(fs::remove_file(filename));
1524 let read_str = str::from_utf8(&read_mem).unwrap();
1525 assert!(read_str == final_msg);
1529 fn file_test_io_seek_shakedown() {
1531 let initial_msg = "qwer-asdf-zxcv";
1532 let chunk_one: &str = "qwer";
1533 let chunk_two: &str = "asdf";
1534 let chunk_three: &str = "zxcv";
1535 let mut read_mem = [0; 4];
1536 let tmpdir = tmpdir();
1537 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1539 let mut rw_stream = check!(File::create(filename));
1540 check!(rw_stream.write(initial_msg.as_bytes()));
1543 let mut read_stream = check!(File::open(filename));
1545 check!(read_stream.seek(SeekFrom::End(-4)));
1546 check!(read_stream.read(&mut read_mem));
1547 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1549 check!(read_stream.seek(SeekFrom::Current(-9)));
1550 check!(read_stream.read(&mut read_mem));
1551 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1553 check!(read_stream.seek(SeekFrom::Start(0)));
1554 check!(read_stream.read(&mut read_mem));
1555 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1557 check!(fs::remove_file(filename));
1561 fn file_test_stat_is_correct_on_is_file() {
1562 let tmpdir = tmpdir();
1563 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1565 let mut opts = OpenOptions::new();
1566 let mut fs = check!(opts.read(true).write(true)
1567 .create(true).open(filename));
1569 fs.write(msg.as_bytes()).unwrap();
1571 let fstat_res = check!(fs.metadata());
1572 assert!(fstat_res.is_file());
1574 let stat_res_fn = check!(fs::metadata(filename));
1575 assert!(stat_res_fn.is_file());
1576 let stat_res_meth = check!(filename.metadata());
1577 assert!(stat_res_meth.is_file());
1578 check!(fs::remove_file(filename));
1582 fn file_test_stat_is_correct_on_is_dir() {
1583 let tmpdir = tmpdir();
1584 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1585 check!(fs::create_dir(filename));
1586 let stat_res_fn = check!(fs::metadata(filename));
1587 assert!(stat_res_fn.is_dir());
1588 let stat_res_meth = check!(filename.metadata());
1589 assert!(stat_res_meth.is_dir());
1590 check!(fs::remove_dir(filename));
1594 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1595 let tmpdir = tmpdir();
1596 let dir = &tmpdir.join("fileinfo_false_on_dir");
1597 check!(fs::create_dir(dir));
1598 assert!(dir.is_file() == false);
1599 check!(fs::remove_dir(dir));
1603 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1604 let tmpdir = tmpdir();
1605 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1606 check!(check!(File::create(file)).write(b"foo"));
1607 assert!(file.exists());
1608 check!(fs::remove_file(file));
1609 assert!(!file.exists());
1613 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1614 let tmpdir = tmpdir();
1615 let dir = &tmpdir.join("before_and_after_dir");
1616 assert!(!dir.exists());
1617 check!(fs::create_dir(dir));
1618 assert!(dir.exists());
1619 assert!(dir.is_dir());
1620 check!(fs::remove_dir(dir));
1621 assert!(!dir.exists());
1625 fn file_test_directoryinfo_readdir() {
1626 let tmpdir = tmpdir();
1627 let dir = &tmpdir.join("di_readdir");
1628 check!(fs::create_dir(dir));
1631 let f = dir.join(&format!("{}.txt", n));
1632 let mut w = check!(File::create(&f));
1633 let msg_str = format!("{}{}", prefix, n.to_string());
1634 let msg = msg_str.as_bytes();
1635 check!(w.write(msg));
1637 let files = check!(fs::read_dir(dir));
1638 let mut mem = [0; 4];
1640 let f = f.unwrap().path();
1642 let n = f.file_stem().unwrap();
1643 check!(check!(File::open(&f)).read(&mut mem));
1644 let read_str = str::from_utf8(&mem).unwrap();
1645 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1646 assert_eq!(expected, read_str);
1648 check!(fs::remove_file(&f));
1650 check!(fs::remove_dir(dir));
1654 fn file_test_walk_dir() {
1655 let tmpdir = tmpdir();
1656 let dir = &tmpdir.join("walk_dir");
1657 check!(fs::create_dir(dir));
1659 let dir1 = &dir.join("01/02/03");
1660 check!(fs::create_dir_all(dir1));
1661 check!(File::create(&dir1.join("04")));
1663 let dir2 = &dir.join("11/12/13");
1664 check!(fs::create_dir_all(dir2));
1665 check!(File::create(&dir2.join("14")));
1667 let files = check!(fs::walk_dir(dir));
1668 let mut cur = [0; 2];
1670 let f = f.unwrap().path();
1671 let stem = f.file_stem().unwrap().to_str().unwrap();
1672 let root = stem.as_bytes()[0] - b'0';
1673 let name = stem.as_bytes()[1] - b'0';
1674 assert!(cur[root as usize] < name);
1675 cur[root as usize] = name;
1678 check!(fs::remove_dir_all(dir));
1682 fn mkdir_path_already_exists_error() {
1683 let tmpdir = tmpdir();
1684 let dir = &tmpdir.join("mkdir_error_twice");
1685 check!(fs::create_dir(dir));
1686 let e = fs::create_dir(dir).err().unwrap();
1687 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1691 fn recursive_mkdir() {
1692 let tmpdir = tmpdir();
1693 let dir = tmpdir.join("d1/d2");
1694 check!(fs::create_dir_all(&dir));
1695 assert!(dir.is_dir())
1699 fn recursive_mkdir_failure() {
1700 let tmpdir = tmpdir();
1701 let dir = tmpdir.join("d1");
1702 let file = dir.join("f1");
1704 check!(fs::create_dir_all(&dir));
1705 check!(File::create(&file));
1707 let result = fs::create_dir_all(&file);
1709 assert!(result.is_err());
1710 // error!(result, "couldn't recursively mkdir");
1711 // error!(result, "couldn't create directory");
1712 // error!(result, "mode=0700");
1713 // error!(result, format!("path={}", file.display()));
1717 fn recursive_mkdir_slash() {
1718 check!(fs::create_dir_all(&Path2::new("/")));
1721 // FIXME(#12795) depends on lstat to work on windows
1722 #[cfg(not(windows))]
1724 fn recursive_rmdir() {
1725 let tmpdir = tmpdir();
1726 let d1 = tmpdir.join("d1");
1727 let dt = d1.join("t");
1728 let dtt = dt.join("t");
1729 let d2 = tmpdir.join("d2");
1730 let canary = d2.join("do_not_delete");
1731 check!(fs::create_dir_all(&dtt));
1732 check!(fs::create_dir_all(&d2));
1733 check!(check!(File::create(&canary)).write(b"foo"));
1734 check!(fs::soft_link(&d2, &dt.join("d2")));
1735 check!(fs::remove_dir_all(&d1));
1737 assert!(!d1.is_dir());
1738 assert!(canary.exists());
1742 fn unicode_path_is_dir() {
1743 assert!(Path2::new(".").is_dir());
1744 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1746 let tmpdir = tmpdir();
1748 let mut dirpath = tmpdir.path().to_path_buf();
1749 dirpath.push(&format!("test-가一ー你好"));
1750 check!(fs::create_dir(&dirpath));
1751 assert!(dirpath.is_dir());
1753 let mut filepath = dirpath;
1754 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1755 check!(File::create(&filepath)); // ignore return; touch only
1756 assert!(!filepath.is_dir());
1757 assert!(filepath.exists());
1761 fn unicode_path_exists() {
1762 assert!(Path2::new(".").exists());
1763 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1765 let tmpdir = tmpdir();
1766 let unicode = tmpdir.path();
1767 let unicode = unicode.join(&format!("test-각丁ー再见"));
1768 check!(fs::create_dir(&unicode));
1769 assert!(unicode.exists());
1770 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1774 fn copy_file_does_not_exist() {
1775 let from = Path2::new("test/nonexistent-bogus-path");
1776 let to = Path2::new("test/other-bogus-path");
1778 match fs::copy(&from, &to) {
1781 assert!(!from.exists());
1782 assert!(!to.exists());
1789 let tmpdir = tmpdir();
1790 let input = tmpdir.join("in.txt");
1791 let out = tmpdir.join("out.txt");
1793 check!(check!(File::create(&input)).write(b"hello"));
1794 check!(fs::copy(&input, &out));
1795 let mut v = Vec::new();
1796 check!(check!(File::open(&out)).read_to_end(&mut v));
1797 assert_eq!(v, b"hello");
1799 assert_eq!(check!(input.metadata()).permissions(),
1800 check!(out.metadata()).permissions());
1804 fn copy_file_dst_dir() {
1805 let tmpdir = tmpdir();
1806 let out = tmpdir.join("out");
1808 check!(File::create(&out));
1809 match fs::copy(&*out, tmpdir.path()) {
1810 Ok(..) => panic!(), Err(..) => {}
1815 fn copy_file_dst_exists() {
1816 let tmpdir = tmpdir();
1817 let input = tmpdir.join("in");
1818 let output = tmpdir.join("out");
1820 check!(check!(File::create(&input)).write("foo".as_bytes()));
1821 check!(check!(File::create(&output)).write("bar".as_bytes()));
1822 check!(fs::copy(&input, &output));
1824 let mut v = Vec::new();
1825 check!(check!(File::open(&output)).read_to_end(&mut v));
1826 assert_eq!(v, b"foo".to_vec());
1830 fn copy_file_src_dir() {
1831 let tmpdir = tmpdir();
1832 let out = tmpdir.join("out");
1834 match fs::copy(tmpdir.path(), &out) {
1835 Ok(..) => panic!(), Err(..) => {}
1837 assert!(!out.exists());
1841 fn copy_file_preserves_perm_bits() {
1842 let tmpdir = tmpdir();
1843 let input = tmpdir.join("in.txt");
1844 let out = tmpdir.join("out.txt");
1846 let attr = check!(check!(File::create(&input)).metadata());
1847 let mut p = attr.permissions();
1848 p.set_readonly(true);
1849 check!(fs::set_permissions(&input, p));
1850 check!(fs::copy(&input, &out));
1851 assert!(check!(out.metadata()).permissions().readonly());
1852 check!(fs::set_permissions(&input, attr.permissions()));
1853 check!(fs::set_permissions(&out, attr.permissions()));
1856 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1858 fn symlinks_work() {
1859 let tmpdir = tmpdir();
1860 let input = tmpdir.join("in.txt");
1861 let out = tmpdir.join("out.txt");
1863 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1864 check!(fs::soft_link(&input, &out));
1865 // if cfg!(not(windows)) {
1866 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1867 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1869 assert_eq!(check!(fs::metadata(&out)).len(),
1870 check!(fs::metadata(&input)).len());
1871 let mut v = Vec::new();
1872 check!(check!(File::open(&out)).read_to_end(&mut v));
1873 assert_eq!(v, b"foobar".to_vec());
1876 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1878 fn symlink_noexist() {
1879 let tmpdir = tmpdir();
1880 // symlinks can point to things that don't exist
1881 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1882 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1883 tmpdir.join("foo"));
1887 fn readlink_not_symlink() {
1888 let tmpdir = tmpdir();
1889 match fs::read_link(tmpdir.path()) {
1890 Ok(..) => panic!("wanted a failure"),
1897 let tmpdir = tmpdir();
1898 let input = tmpdir.join("in.txt");
1899 let out = tmpdir.join("out.txt");
1901 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1902 check!(fs::hard_link(&input, &out));
1903 assert_eq!(check!(fs::metadata(&out)).len(),
1904 check!(fs::metadata(&input)).len());
1905 assert_eq!(check!(fs::metadata(&out)).len(),
1906 check!(input.metadata()).len());
1907 let mut v = Vec::new();
1908 check!(check!(File::open(&out)).read_to_end(&mut v));
1909 assert_eq!(v, b"foobar".to_vec());
1911 // can't link to yourself
1912 match fs::hard_link(&input, &input) {
1913 Ok(..) => panic!("wanted a failure"),
1916 // can't link to something that doesn't exist
1917 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1918 Ok(..) => panic!("wanted a failure"),
1925 let tmpdir = tmpdir();
1926 let file = tmpdir.join("in.txt");
1928 check!(File::create(&file));
1929 let attr = check!(fs::metadata(&file));
1930 assert!(!attr.permissions().readonly());
1931 let mut p = attr.permissions();
1932 p.set_readonly(true);
1933 check!(fs::set_permissions(&file, p.clone()));
1934 let attr = check!(fs::metadata(&file));
1935 assert!(attr.permissions().readonly());
1937 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1938 Ok(..) => panic!("wanted an error"),
1942 p.set_readonly(false);
1943 check!(fs::set_permissions(&file, p));
1947 fn sync_doesnt_kill_anything() {
1948 let tmpdir = tmpdir();
1949 let path = tmpdir.join("in.txt");
1951 let mut file = check!(File::create(&path));
1952 check!(file.sync_all());
1953 check!(file.sync_data());
1954 check!(file.write(b"foo"));
1955 check!(file.sync_all());
1956 check!(file.sync_data());
1960 fn truncate_works() {
1961 let tmpdir = tmpdir();
1962 let path = tmpdir.join("in.txt");
1964 let mut file = check!(File::create(&path));
1965 check!(file.write(b"foo"));
1966 check!(file.sync_all());
1968 // Do some simple things with truncation
1969 assert_eq!(check!(file.metadata()).len(), 3);
1970 check!(file.set_len(10));
1971 assert_eq!(check!(file.metadata()).len(), 10);
1972 check!(file.write(b"bar"));
1973 check!(file.sync_all());
1974 assert_eq!(check!(file.metadata()).len(), 10);
1976 let mut v = Vec::new();
1977 check!(check!(File::open(&path)).read_to_end(&mut v));
1978 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1980 // Truncate to a smaller length, don't seek, and then write something.
1981 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1982 // past the end of the file).
1983 check!(file.set_len(2));
1984 assert_eq!(check!(file.metadata()).len(), 2);
1985 check!(file.write(b"wut"));
1986 check!(file.sync_all());
1987 assert_eq!(check!(file.metadata()).len(), 9);
1988 let mut v = Vec::new();
1989 check!(check!(File::open(&path)).read_to_end(&mut v));
1990 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1995 use fs::OpenOptions as OO;
1996 fn c<T: Clone>(t: &T) -> T { t.clone() }
1998 let tmpdir = tmpdir();
2000 let mut r = OO::new(); r.read(true);
2001 let mut w = OO::new(); w.write(true);
2002 let mut rw = OO::new(); rw.write(true).read(true);
2004 match r.open(&tmpdir.join("a")) {
2005 Ok(..) => panic!(), Err(..) => {}
2008 // Perform each one twice to make sure that it succeeds the second time
2009 // (where the file exists)
2010 check!(c(&w).create(true).open(&tmpdir.join("b")));
2011 assert!(tmpdir.join("b").exists());
2012 check!(c(&w).create(true).open(&tmpdir.join("b")));
2013 check!(w.open(&tmpdir.join("b")));
2015 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2016 assert!(tmpdir.join("c").exists());
2017 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2018 check!(rw.open(&tmpdir.join("c")));
2020 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2021 assert!(tmpdir.join("d").exists());
2022 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2023 check!(c(&w).append(true).open(&tmpdir.join("d")));
2025 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2026 assert!(tmpdir.join("e").exists());
2027 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2028 check!(c(&rw).append(true).open(&tmpdir.join("e")));
2030 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2031 assert!(tmpdir.join("f").exists());
2032 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2033 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2035 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2036 assert!(tmpdir.join("g").exists());
2037 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2038 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2040 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2041 check!(r.open(&tmpdir.join("h")));
2043 let mut f = check!(r.open(&tmpdir.join("h")));
2044 assert!(f.write("wut".as_bytes()).is_err());
2046 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2048 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2049 check!(f.write("bar".as_bytes()));
2051 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2053 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2054 check!(f.write("bar".as_bytes()));
2056 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2061 let tmpdir = tmpdir();
2062 let path = tmpdir.join("a");
2063 check!(File::create(&path));
2064 // These numbers have to be bigger than the time in the day to account
2065 // for timezones Windows in particular will fail in certain timezones
2066 // with small enough values
2067 check!(fs::set_file_times(&path, 100000, 200000));
2068 assert_eq!(check!(path.metadata()).accessed(), 100000);
2069 assert_eq!(check!(path.metadata()).modified(), 200000);
2073 fn utime_noexist() {
2074 let tmpdir = tmpdir();
2076 match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
2084 let mut bytes = [0; 1024];
2085 StdRng::new().unwrap().fill_bytes(&mut bytes);
2087 let tmpdir = tmpdir();
2089 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2090 let mut v = Vec::new();
2091 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2092 assert!(v == &bytes[..]);
2096 #[cfg(not(windows))]
2097 fn unlink_readonly() {
2098 let tmpdir = tmpdir();
2099 let path = tmpdir.join("file");
2100 check!(File::create(&path));
2101 let mut perm = check!(fs::metadata(&path)).permissions();
2102 perm.set_readonly(true);
2103 check!(fs::set_permissions(&path, perm));
2104 check!(fs::remove_file(&path));
2108 fn mkdir_trailing_slash() {
2109 let tmpdir = tmpdir();
2110 let path = tmpdir.join("file");
2111 check!(fs::create_dir_all(&path.join("a/")));
2115 #[cfg(not(windows))]
2116 fn realpath_works() {
2117 let tmpdir = tmpdir();
2118 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2119 let file = tmpdir.join("test");
2120 let dir = tmpdir.join("test2");
2121 let link = dir.join("link");
2122 let linkdir = tmpdir.join("test3");
2124 File::create(&file).unwrap();
2125 fs::create_dir(&dir).unwrap();
2126 fs::soft_link(&file, &link).unwrap();
2127 fs::soft_link(&dir, &linkdir).unwrap();
2129 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2131 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2132 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2133 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2134 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2135 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2139 #[cfg(not(windows))]
2140 fn realpath_works_tricky() {
2141 let tmpdir = tmpdir();
2142 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2144 let a = tmpdir.join("a");
2145 let b = a.join("b");
2146 let c = b.join("c");
2147 let d = a.join("d");
2148 let e = d.join("e");
2149 let f = a.join("f");
2151 fs::create_dir_all(&b).unwrap();
2152 fs::create_dir_all(&d).unwrap();
2153 File::create(&f).unwrap();
2154 fs::soft_link("../d/e", &c).unwrap();
2155 fs::soft_link("../f", &e).unwrap();
2157 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2158 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2162 fn dir_entry_methods() {
2163 let tmpdir = tmpdir();
2165 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2166 File::create(&tmpdir.join("b")).unwrap();
2168 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2169 let fname = file.file_name();
2170 match fname.to_str() {
2172 assert!(file.file_type().unwrap().is_dir());
2173 assert!(file.metadata().unwrap().is_dir());
2176 assert!(file.file_type().unwrap().is_file());
2177 assert!(file.metadata().unwrap().is_file());
2179 f => panic!("unknown file name: {:?}", f),