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 #![unstable(feature = "fs")]
22 use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
23 use path::{AsPath, Path, PathBuf};
24 use sys::fs2 as fs_imp;
25 use sys_common::{AsInnerMut, FromInner, AsInner};
28 pub use self::tempdir::TempDir;
32 /// A reference to an open file on the filesystem.
34 /// An instance of a `File` can be read and/or written depending on what options
35 /// it was opened with. Files also implement `Seek` to alter the logical cursor
36 /// that the file contains internally.
41 /// use std::io::prelude::*;
42 /// use std::fs::File;
44 /// # fn foo() -> std::io::Result<()> {
45 /// let mut f = try!(File::create("foo.txt"));
46 /// try!(f.write_all(b"Hello, world!"));
48 /// let mut f = try!(File::open("foo.txt"));
49 /// let mut s = String::new();
50 /// try!(f.read_to_string(&mut s));
51 /// assert_eq!(s, "Hello, world!");
60 /// Metadata information about a file.
62 /// This structure is returned from the `metadata` function or method and
63 /// represents known metadata about a file such as its permissions, size,
64 /// modification times, etc.
65 pub struct Metadata(fs_imp::FileAttr);
67 /// Iterator over the entries in a directory.
69 /// This iterator is returned from the `read_dir` function of this module and
70 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
71 /// information like the entry's path and possibly other metadata can be
73 pub struct ReadDir(fs_imp::ReadDir);
75 /// Entries returned by the `ReadDir` iterator.
77 /// An instance of `DirEntry` represents an entry inside of a directory on the
78 /// filesystem. Each entry can be inspected via methods to learn about the full
79 /// path or possibly other metadata through per-platform extension traits.
80 pub struct DirEntry(fs_imp::DirEntry);
82 /// An iterator that recursively walks over the contents of a directory.
85 stack: Vec<io::Result<ReadDir>>,
88 /// Options and flags which can be used to configure how a file is opened.
90 /// This builder exposes the ability to configure how a `File` is opened and
91 /// what operations are permitted on the open file. The `File::open` and
92 /// `File::create` methods are aliases for commonly used options using this
95 pub struct OpenOptions(fs_imp::OpenOptions);
97 /// Representation of the various permissions on a file.
99 /// This module only currently provides one bit of information, `readonly`,
100 /// which is exposed on all currently supported platforms. Unix-specific
101 /// functionality, such as mode bits, is available through the
102 /// `os::unix::PermissionsExt` trait.
103 #[derive(Clone, PartialEq, Eq, Debug)]
104 pub struct Permissions(fs_imp::FilePermissions);
107 /// Attempts to open a file in read-only mode.
109 /// See the `OpenOptions::open` method for more details.
113 /// This function will return an error if `path` does not already exist.
114 /// Other errors may also be returned according to `OpenOptions::open`.
115 pub fn open<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
116 OpenOptions::new().read(true).open(path)
119 /// Open a file in write-only mode.
121 /// This function will create a file if it does not exist,
122 /// and will truncate it if it does.
124 /// See the `OpenOptions::open` function for more details.
125 pub fn create<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
126 OpenOptions::new().write(true).create(true).truncate(true).open(path)
129 /// Returns the original path that was used to open this file.
130 pub fn path(&self) -> Option<&Path> {
134 /// Attempt to sync all OS-internal metadata to disk.
136 /// This function will attempt to ensure that all in-core data reaches the
137 /// filesystem before returning.
138 pub fn sync_all(&self) -> io::Result<()> {
142 /// This function is similar to `sync_all`, except that it may not
143 /// synchronize file metadata to the filesystem.
145 /// This is intended for use cases that must synchronize content, but don't
146 /// need the metadata on disk. The goal of this method is to reduce disk
149 /// Note that some platforms may simply implement this in terms of
151 pub fn sync_data(&self) -> io::Result<()> {
152 self.inner.datasync()
155 /// Truncates or extends the underlying file, updating the size of
156 /// this file to become `size`.
158 /// If the `size` is less than the current file's size, then the file will
159 /// be shrunk. If it is greater than the current file's size, then the file
160 /// will be extended to `size` and have all of the intermediate data filled
162 pub fn set_len(&self, size: u64) -> io::Result<()> {
163 self.inner.truncate(size)
166 /// Queries information about the underlying file.
167 pub fn metadata(&self) -> io::Result<Metadata> {
168 self.inner.file_attr().map(Metadata)
172 impl AsInner<fs_imp::File> for File {
173 fn as_inner(&self) -> &fs_imp::File { &self.inner }
176 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
180 impl Write for File {
181 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
182 self.inner.write(buf)
184 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
187 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
191 impl<'a> Read for &'a File {
192 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
196 impl<'a> Write for &'a File {
197 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
198 self.inner.write(buf)
200 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
202 impl<'a> Seek for &'a File {
203 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
209 /// Creates a blank net set of options ready for configuration.
211 /// All options are initially set to `false`.
212 pub fn new() -> OpenOptions {
213 OpenOptions(fs_imp::OpenOptions::new())
216 /// Set the option for read access.
218 /// This option, when true, will indicate that the file should be
219 /// `read`-able if opened.
220 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
221 self.0.read(read); self
224 /// Set the option for write access.
226 /// This option, when true, will indicate that the file should be
227 /// `write`-able if opened.
228 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
229 self.0.write(write); self
232 /// Set the option for the append mode.
234 /// This option, when true, means that writes will append to a file instead
235 /// of overwriting previous contents.
236 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
237 self.0.append(append); self
240 /// Set the option for truncating a previous file.
242 /// If a file is successfully opened with this option set it will truncate
243 /// the file to 0 length if it already exists.
244 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
245 self.0.truncate(truncate); self
248 /// Set the option for creating a new file.
250 /// This option indicates whether a new file will be created if the file
251 /// does not yet already exist.
252 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
253 self.0.create(create); self
256 /// Open a file at `path` with the options specified by `self`.
260 /// This function will return an error under a number of different
261 /// circumstances, to include but not limited to:
263 /// * Opening a file that does not exist with read access.
264 /// * Attempting to open a file with access that the user lacks
266 /// * Filesystem-level errors (full disk, etc)
267 pub fn open<P: AsPath + ?Sized>(&self, path: &P) -> io::Result<File> {
268 let path = path.as_path();
269 let inner = try!(fs_imp::File::open(path, &self.0));
271 // On *BSD systems, we can open a directory as a file and read from
272 // it: fd=open("/tmp", O_RDONLY); read(fd, buf, N); due to an old
273 // tradition before the introduction of opendir(3). We explicitly
274 // reject it because there are few use cases.
275 if cfg!(not(any(target_os = "linux", target_os = "android"))) &&
276 try!(inner.file_attr()).is_dir() {
277 Err(Error::new(ErrorKind::InvalidInput, "is a directory", None))
279 Ok(File { path: path.to_path_buf(), inner: inner })
283 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
284 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
288 /// Returns whether this metadata is for a directory.
289 pub fn is_dir(&self) -> bool { self.0.is_dir() }
291 /// Returns whether this metadata is for a regular file.
292 pub fn is_file(&self) -> bool { self.0.is_file() }
294 /// Returns the size of the file, in bytes, this metadata is for.
295 pub fn len(&self) -> u64 { self.0.size() }
297 /// Returns the permissions of the file this metadata is for.
298 pub fn permissions(&self) -> Permissions {
299 Permissions(self.0.perm())
302 /// Returns the most recent access time for a file.
304 /// The return value is in milliseconds since the epoch.
305 pub fn accessed(&self) -> u64 { self.0.accessed() }
307 /// Returns the most recent modification time for a file.
309 /// The return value is in milliseconds since the epoch.
310 pub fn modified(&self) -> u64 { self.0.modified() }
314 /// Returns whether these permissions describe a readonly file.
315 pub fn readonly(&self) -> bool { self.0.readonly() }
317 /// Modify the readonly flag for this set of permissions.
319 /// This operation does **not** modify the filesystem. To modify the
320 /// filesystem use the `fs::set_permissions` function.
321 pub fn set_readonly(&mut self, readonly: bool) {
322 self.0.set_readonly(readonly)
326 impl FromInner<fs_imp::FilePermissions> for Permissions {
327 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
332 impl Iterator for ReadDir {
333 type Item = io::Result<DirEntry>;
335 fn next(&mut self) -> Option<io::Result<DirEntry>> {
336 self.0.next().map(|entry| entry.map(DirEntry))
341 /// Returns the full path to the file that this entry represents.
343 /// The full path is created by joining the original path to `read_dir` or
344 /// `walk_dir` with the filename of this entry.
345 pub fn path(&self) -> PathBuf { self.0.path() }
348 /// Remove a file from the underlying filesystem.
355 /// fs::remove_file("/some/file/path.txt");
358 /// Note that, just because an unlink call was successful, it is not
359 /// guaranteed that a file is immediately deleted (e.g. depending on
360 /// platform, other open file descriptors may prevent immediate removal).
364 /// This function will return an error if `path` points to a directory, if the
365 /// user lacks permissions to remove the file, or if some other filesystem-level
367 pub fn remove_file<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
368 let path = path.as_path();
369 let e = match fs_imp::unlink(path) {
370 Ok(()) => return Ok(()),
373 if !cfg!(windows) { return Err(e) }
375 // On unix, a readonly file can be successfully removed. On windows,
376 // however, it cannot. To keep the two platforms in line with
377 // respect to their behavior, catch this case on windows, attempt to
378 // change it to read-write, and then remove the file.
379 if e.kind() != ErrorKind::PermissionDenied { return Err(e) }
381 let attr = match metadata(path) { Ok(a) => a, Err(..) => return Err(e) };
382 let mut perms = attr.permissions();
383 if !perms.readonly() { return Err(e) }
384 perms.set_readonly(false);
386 if set_permissions(path, perms).is_err() { return Err(e) }
387 if fs_imp::unlink(path).is_ok() { return Ok(()) }
389 // Oops, try to put things back the way we found it
390 let _ = set_permissions(path, attr.permissions());
394 /// Given a path, query the file system to get information about a file,
397 /// This function will traverse soft links to query information about the
398 /// destination file.
403 /// # fn foo() -> std::io::Result<()> {
406 /// let attr = try!(fs::metadata("/some/file/path.txt"));
407 /// // inspect attr ...
414 /// This function will return an error if the user lacks the requisite
415 /// permissions to perform a `metadata` call on the given `path` or if there
416 /// is no entry in the filesystem at the provided path.
417 pub fn metadata<P: AsPath + ?Sized>(path: &P) -> io::Result<Metadata> {
418 fs_imp::stat(path.as_path()).map(Metadata)
421 /// Rename a file or directory to a new name.
428 /// fs::rename("foo", "bar");
433 /// This function will return an error if the provided `from` doesn't exist, if
434 /// the process lacks permissions to view the contents, if `from` and `to`
435 /// reside on separate filesystems, or if some other intermittent I/O error
437 pub fn rename<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
439 fs_imp::rename(from.as_path(), to.as_path())
442 /// Copies the contents of one file to another. This function will also
443 /// copy the permission bits of the original file to the destination file.
445 /// This function will **overwrite** the contents of `to`.
447 /// Note that if `from` and `to` both point to the same file, then the file
448 /// will likely get truncated by this operation.
455 /// fs::copy("foo.txt", "bar.txt");
460 /// This function will return an error in the following situations, but is not
461 /// limited to just these cases:
463 /// * The `from` path is not a file
464 /// * The `from` file does not exist
465 /// * The current process does not have the permission rights to access
466 /// `from` or write `to`
467 pub fn copy<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
469 let from = from.as_path();
471 return Err(Error::new(ErrorKind::MismatchedFileTypeForOperation,
472 "the source path is not an existing file",
476 let mut reader = try!(File::open(from));
477 let mut writer = try!(File::create(to));
478 let perm = try!(reader.metadata()).permissions();
480 let ret = try!(io::copy(&mut reader, &mut writer));
481 try!(set_permissions(to, perm));
485 /// Creates a new hard link on the filesystem.
487 /// The `dst` path will be a link pointing to the `src` path. Note that systems
488 /// often require these two paths to both be located on the same filesystem.
489 pub fn hard_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
491 fs_imp::link(src.as_path(), dst.as_path())
494 /// Creates a new soft link on the filesystem.
496 /// The `dst` path will be a soft link pointing to the `src` path.
497 pub fn soft_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
499 fs_imp::symlink(src.as_path(), dst.as_path())
502 /// Reads a soft link, returning the file that the link points to.
506 /// This function will return an error on failure. Failure conditions include
507 /// reading a file that does not exist or reading a file that is not a soft
509 pub fn read_link<P: AsPath + ?Sized>(path: &P) -> io::Result<PathBuf> {
510 fs_imp::readlink(path.as_path())
513 /// Create a new, empty directory at the provided path
520 /// fs::create_dir("/some/dir");
525 /// This function will return an error if the user lacks permissions to make a
526 /// new directory at the provided `path`, or if the directory already exists.
527 pub fn create_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
528 fs_imp::mkdir(path.as_path())
531 /// Recursively create a directory and all of its parent components if they
536 /// This function will fail if any directory in the path specified by `path`
537 /// does not already exist and it could not be created otherwise. The specific
538 /// error conditions for when a directory is being created (after it is
539 /// determined to not exist) are outlined by `fs::create_dir`.
540 pub fn create_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
541 let path = path.as_path();
542 if path.is_dir() { return Ok(()) }
543 match path.parent() {
544 Some(p) if p != path => try!(create_dir_all(p)),
547 // If the file name of the given `path` is blank then the creation of the
548 // parent directory will have taken care of the whole path for us, so we're
550 if path.file_name().is_none() {
557 /// Remove an existing, empty directory
564 /// fs::remove_dir("/some/dir");
569 /// This function will return an error if the user lacks permissions to remove
570 /// the directory at the provided `path`, or if the directory isn't empty.
571 pub fn remove_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
572 fs_imp::rmdir(path.as_path())
575 /// Removes a directory at this path, after removing all its contents. Use
578 /// This function does **not** follow soft links and it will simply remove the
579 /// soft link itself.
583 /// See `file::remove_file` and `fs::remove_dir`
584 pub fn remove_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
585 let path = path.as_path();
586 for child in try!(read_dir(path)) {
587 let child = try!(child).path();
588 let stat = try!(lstat(&*child));
590 try!(remove_dir_all(&*child));
592 try!(remove_file(&*child));
595 return remove_dir(path);
598 fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::lstat(path) }
600 fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::stat(path) }
603 /// Returns an iterator over the entries within a directory.
605 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
606 /// be encountered after an iterator is initially constructed.
612 /// use std::fs::{self, PathExt, DirEntry};
613 /// use std::path::Path;
615 /// // one possible implementation of fs::walk_dir only visiting files
616 /// fn visit_dirs(dir: &Path, cb: &mut FnMut(DirEntry)) -> io::Result<()> {
617 /// if dir.is_dir() {
618 /// for entry in try!(fs::read_dir(dir)) {
619 /// let entry = try!(entry);
620 /// if entry.path().is_dir() {
621 /// try!(visit_dirs(&entry.path(), cb));
633 /// This function will return an error if the provided `path` doesn't exist, if
634 /// the process lacks permissions to view the contents or if the `path` points
635 /// at a non-directory file
636 pub fn read_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<ReadDir> {
637 fs_imp::readdir(path.as_path()).map(ReadDir)
640 /// Returns an iterator that will recursively walk the directory structure
641 /// rooted at `path`.
643 /// The path given will not be iterated over, and this will perform iteration in
644 /// some top-down order. The contents of unreadable subdirectories are ignored.
646 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
647 /// be encountered after an iterator is initially constructed.
648 pub fn walk_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<WalkDir> {
649 let start = try!(read_dir(path));
650 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
653 impl Iterator for WalkDir {
654 type Item = io::Result<DirEntry>;
656 fn next(&mut self) -> Option<io::Result<DirEntry>> {
658 if let Some(ref mut cur) = self.cur {
660 Some(Err(e)) => return Some(Err(e)),
662 let path = next.path();
664 self.stack.push(read_dir(&*path));
666 return Some(Ok(next))
672 match self.stack.pop() {
673 Some(Err(e)) => return Some(Err(e)),
674 Some(Ok(next)) => self.cur = Some(next),
681 /// Utility methods for paths.
683 /// Get information on the file, directory, etc at this path.
685 /// Consult the `fs::stat` documentation for more info.
687 /// This call preserves identical runtime/error semantics with `file::stat`.
688 fn metadata(&self) -> io::Result<Metadata>;
690 /// Boolean value indicator whether the underlying file exists on the local
691 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
692 fn exists(&self) -> bool;
694 /// Whether the underlying implementation (be it a file path, or something
695 /// else) points at a "regular file" on the FS. Will return false for paths
696 /// to non-existent locations or directories or other non-regular files
697 /// (named pipes, etc). Follows links when making this determination.
698 fn is_file(&self) -> bool;
700 /// Whether the underlying implementation (be it a file path, or something
701 /// else) is pointing at a directory in the underlying FS. Will return
702 /// false for paths to non-existent locations or if the item is not a
703 /// directory (eg files, named pipes, etc). Follows links when making this
705 fn is_dir(&self) -> bool;
708 impl PathExt for Path {
709 fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
711 fn exists(&self) -> bool { metadata(self).is_ok() }
713 fn is_file(&self) -> bool {
714 metadata(self).map(|s| s.is_file()).unwrap_or(false)
716 fn is_dir(&self) -> bool {
717 metadata(self).map(|s| s.is_dir()).unwrap_or(false)
721 /// Changes the timestamps for a file's last modification and access time.
723 /// The file at the path specified will have its last access time set to
724 /// `atime` and its modification time set to `mtime`. The times specified should
725 /// be in milliseconds.
726 pub fn set_file_times<P: AsPath + ?Sized>(path: &P, accessed: u64,
727 modified: u64) -> io::Result<()> {
728 fs_imp::utimes(path.as_path(), accessed, modified)
731 /// Changes the permissions found on a file or a directory.
736 /// # fn foo() -> std::io::Result<()> {
739 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
740 /// perms.set_readonly(true);
741 /// try!(fs::set_permissions("foo.txt", perms));
748 /// This function will return an error if the provided `path` doesn't exist, if
749 /// the process lacks permissions to change the attributes of the file, or if
750 /// some other I/O error is encountered.
751 pub fn set_permissions<P: AsPath + ?Sized>(path: &P, perm: Permissions)
753 fs_imp::set_perm(path.as_path(), perm.0)
758 #![allow(deprecated)] //rand
763 use fs::{self, File, OpenOptions};
764 use io::{ErrorKind, SeekFrom};
766 use path::Path as Path2;
768 use rand::{self, StdRng, Rng};
771 macro_rules! check { ($e:expr) => (
774 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
778 macro_rules! error { ($e:expr, $s:expr) => (
780 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
781 Err(ref err) => assert!(err.to_string().contains($s.as_slice()),
782 format!("`{}` did not contain `{}`", err, $s))
786 pub struct TempDir(PathBuf);
789 fn join(&self, path: &str) -> PathBuf {
790 let TempDir(ref p) = *self;
794 fn path<'a>(&'a self) -> &'a Path2 {
795 let TempDir(ref p) = *self;
800 impl Drop for TempDir {
802 // Gee, seeing how we're testing the fs module I sure hope that we
803 // at least implement this correctly!
804 let TempDir(ref p) = *self;
805 check!(fs::remove_dir_all(p));
809 pub fn tmpdir() -> TempDir {
810 let s = os::tmpdir();
811 let p = Path2::new(s.as_str().unwrap());
812 let ret = p.join(&format!("rust-{}", rand::random::<u32>()));
813 check!(fs::create_dir(&ret));
818 fn file_test_io_smoke_test() {
819 let message = "it's alright. have a good time";
820 let tmpdir = tmpdir();
821 let filename = &tmpdir.join("file_rt_io_file_test.txt");
823 let mut write_stream = check!(File::create(filename));
824 check!(write_stream.write(message.as_bytes()));
827 let mut read_stream = check!(File::open(filename));
828 let mut read_buf = [0; 1028];
829 let read_str = match check!(read_stream.read(&mut read_buf)) {
830 -1|0 => panic!("shouldn't happen"),
831 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
833 assert_eq!(read_str.as_slice(), message);
835 check!(fs::remove_file(filename));
839 fn invalid_path_raises() {
840 let tmpdir = tmpdir();
841 let filename = &tmpdir.join("file_that_does_not_exist.txt");
842 let result = File::open(filename);
845 error!(result, "o such file or directory");
847 // error!(result, "couldn't open path as file");
848 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
852 fn file_test_iounlinking_invalid_path_should_raise_condition() {
853 let tmpdir = tmpdir();
854 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
856 let result = fs::remove_file(filename);
859 error!(result, "o such file or directory");
861 // error!(result, "couldn't unlink path");
862 // error!(result, format!("path={}", filename.display()));
866 fn file_test_io_non_positional_read() {
867 let message: &str = "ten-four";
868 let mut read_mem = [0; 8];
869 let tmpdir = tmpdir();
870 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
872 let mut rw_stream = check!(File::create(filename));
873 check!(rw_stream.write(message.as_bytes()));
876 let mut read_stream = check!(File::open(filename));
878 let read_buf = &mut read_mem[0..4];
879 check!(read_stream.read(read_buf));
882 let read_buf = &mut read_mem[4..8];
883 check!(read_stream.read(read_buf));
886 check!(fs::remove_file(filename));
887 let read_str = str::from_utf8(&read_mem).unwrap();
888 assert_eq!(read_str, message);
892 fn file_test_io_seek_and_tell_smoke_test() {
893 let message = "ten-four";
894 let mut read_mem = [0; 4];
895 let set_cursor = 4 as u64;
896 let mut tell_pos_pre_read;
897 let mut tell_pos_post_read;
898 let tmpdir = tmpdir();
899 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
901 let mut rw_stream = check!(File::create(filename));
902 check!(rw_stream.write(message.as_bytes()));
905 let mut read_stream = check!(File::open(filename));
906 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
907 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
908 check!(read_stream.read(&mut read_mem));
909 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
911 check!(fs::remove_file(filename));
912 let read_str = str::from_utf8(&read_mem).unwrap();
913 assert_eq!(read_str, &message[4..8]);
914 assert_eq!(tell_pos_pre_read, set_cursor);
915 assert_eq!(tell_pos_post_read, message.len() as u64);
919 fn file_test_io_seek_and_write() {
920 let initial_msg = "food-is-yummy";
921 let overwrite_msg = "-the-bar!!";
922 let final_msg = "foo-the-bar!!";
924 let mut read_mem = [0; 13];
925 let tmpdir = tmpdir();
926 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
928 let mut rw_stream = check!(File::create(filename));
929 check!(rw_stream.write(initial_msg.as_bytes()));
930 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
931 check!(rw_stream.write(overwrite_msg.as_bytes()));
934 let mut read_stream = check!(File::open(filename));
935 check!(read_stream.read(&mut read_mem));
937 check!(fs::remove_file(filename));
938 let read_str = str::from_utf8(&read_mem).unwrap();
939 assert!(read_str == final_msg);
943 fn file_test_io_seek_shakedown() {
945 let initial_msg = "qwer-asdf-zxcv";
946 let chunk_one: &str = "qwer";
947 let chunk_two: &str = "asdf";
948 let chunk_three: &str = "zxcv";
949 let mut read_mem = [0; 4];
950 let tmpdir = tmpdir();
951 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
953 let mut rw_stream = check!(File::create(filename));
954 check!(rw_stream.write(initial_msg.as_bytes()));
957 let mut read_stream = check!(File::open(filename));
959 check!(read_stream.seek(SeekFrom::End(-4)));
960 check!(read_stream.read(&mut read_mem));
961 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
963 check!(read_stream.seek(SeekFrom::Current(-9)));
964 check!(read_stream.read(&mut read_mem));
965 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
967 check!(read_stream.seek(SeekFrom::Start(0)));
968 check!(read_stream.read(&mut read_mem));
969 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
971 check!(fs::remove_file(filename));
975 fn file_test_stat_is_correct_on_is_file() {
976 let tmpdir = tmpdir();
977 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
979 let mut opts = OpenOptions::new();
980 let mut fs = check!(opts.read(true).write(true)
981 .create(true).open(filename));
983 fs.write(msg.as_bytes()).unwrap();
985 let fstat_res = check!(fs.metadata());
986 assert!(fstat_res.is_file());
988 let stat_res_fn = check!(fs::metadata(filename));
989 assert!(stat_res_fn.is_file());
990 let stat_res_meth = check!(filename.metadata());
991 assert!(stat_res_meth.is_file());
992 check!(fs::remove_file(filename));
996 fn file_test_stat_is_correct_on_is_dir() {
997 let tmpdir = tmpdir();
998 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
999 check!(fs::create_dir(filename));
1000 let stat_res_fn = check!(fs::metadata(filename));
1001 assert!(stat_res_fn.is_dir());
1002 let stat_res_meth = check!(filename.metadata());
1003 assert!(stat_res_meth.is_dir());
1004 check!(fs::remove_dir(filename));
1008 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1009 let tmpdir = tmpdir();
1010 let dir = &tmpdir.join("fileinfo_false_on_dir");
1011 check!(fs::create_dir(dir));
1012 assert!(dir.is_file() == false);
1013 check!(fs::remove_dir(dir));
1017 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1018 let tmpdir = tmpdir();
1019 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1020 check!(check!(File::create(file)).write(b"foo"));
1021 assert!(file.exists());
1022 check!(fs::remove_file(file));
1023 assert!(!file.exists());
1027 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1028 let tmpdir = tmpdir();
1029 let dir = &tmpdir.join("before_and_after_dir");
1030 assert!(!dir.exists());
1031 check!(fs::create_dir(dir));
1032 assert!(dir.exists());
1033 assert!(dir.is_dir());
1034 check!(fs::remove_dir(dir));
1035 assert!(!dir.exists());
1039 fn file_test_directoryinfo_readdir() {
1040 let tmpdir = tmpdir();
1041 let dir = &tmpdir.join("di_readdir");
1042 check!(fs::create_dir(dir));
1044 for n in range(0, 3) {
1045 let f = dir.join(&format!("{}.txt", n));
1046 let mut w = check!(File::create(&f));
1047 let msg_str = format!("{}{}", prefix, n.to_string());
1048 let msg = msg_str.as_bytes();
1049 check!(w.write(msg));
1051 let files = check!(fs::read_dir(dir));
1052 let mut mem = [0u8; 4];
1054 let f = f.unwrap().path();
1056 let n = f.file_stem().unwrap();
1057 check!(check!(File::open(&f)).read(&mut mem));
1058 let read_str = str::from_utf8(&mem).unwrap();
1059 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1060 assert_eq!(expected.as_slice(), read_str);
1062 check!(fs::remove_file(&f));
1064 check!(fs::remove_dir(dir));
1068 fn file_test_walk_dir() {
1069 let tmpdir = tmpdir();
1070 let dir = &tmpdir.join("walk_dir");
1071 check!(fs::create_dir(dir));
1073 let dir1 = &dir.join("01/02/03");
1074 check!(fs::create_dir_all(dir1));
1075 check!(File::create(&dir1.join("04")));
1077 let dir2 = &dir.join("11/12/13");
1078 check!(fs::create_dir_all(dir2));
1079 check!(File::create(&dir2.join("14")));
1081 let files = check!(fs::walk_dir(dir));
1082 let mut cur = [0u8; 2];
1084 let f = f.unwrap().path();
1085 let stem = f.file_stem().unwrap().to_str().unwrap();
1086 let root = stem.as_bytes()[0] - b'0';
1087 let name = stem.as_bytes()[1] - b'0';
1088 assert!(cur[root as usize] < name);
1089 cur[root as usize] = name;
1092 check!(fs::remove_dir_all(dir));
1096 fn mkdir_path_already_exists_error() {
1097 let tmpdir = tmpdir();
1098 let dir = &tmpdir.join("mkdir_error_twice");
1099 check!(fs::create_dir(dir));
1100 let e = fs::create_dir(dir).err().unwrap();
1101 assert_eq!(e.kind(), ErrorKind::PathAlreadyExists);
1105 fn recursive_mkdir() {
1106 let tmpdir = tmpdir();
1107 let dir = tmpdir.join("d1/d2");
1108 check!(fs::create_dir_all(&dir));
1109 assert!(dir.is_dir())
1113 fn recursive_mkdir_failure() {
1114 let tmpdir = tmpdir();
1115 let dir = tmpdir.join("d1");
1116 let file = dir.join("f1");
1118 check!(fs::create_dir_all(&dir));
1119 check!(File::create(&file));
1121 let result = fs::create_dir_all(&file);
1123 assert!(result.is_err());
1124 // error!(result, "couldn't recursively mkdir");
1125 // error!(result, "couldn't create directory");
1126 // error!(result, "mode=0700");
1127 // error!(result, format!("path={}", file.display()));
1131 fn recursive_mkdir_slash() {
1132 check!(fs::create_dir_all(&Path2::new("/")));
1135 // FIXME(#12795) depends on lstat to work on windows
1136 #[cfg(not(windows))]
1138 fn recursive_rmdir() {
1139 let tmpdir = tmpdir();
1140 let d1 = tmpdir.join("d1");
1141 let dt = d1.join("t");
1142 let dtt = dt.join("t");
1143 let d2 = tmpdir.join("d2");
1144 let canary = d2.join("do_not_delete");
1145 check!(fs::create_dir_all(&dtt));
1146 check!(fs::create_dir_all(&d2));
1147 check!(check!(File::create(&canary)).write(b"foo"));
1148 check!(fs::soft_link(&d2, &dt.join("d2")));
1149 check!(fs::remove_dir_all(&d1));
1151 assert!(!d1.is_dir());
1152 assert!(canary.exists());
1156 fn unicode_path_is_dir() {
1157 assert!(Path2::new(".").is_dir());
1158 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1160 let tmpdir = tmpdir();
1162 let mut dirpath = tmpdir.path().to_path_buf();
1163 dirpath.push(&format!("test-가一ー你好"));
1164 check!(fs::create_dir(&dirpath));
1165 assert!(dirpath.is_dir());
1167 let mut filepath = dirpath;
1168 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1169 check!(File::create(&filepath)); // ignore return; touch only
1170 assert!(!filepath.is_dir());
1171 assert!(filepath.exists());
1175 fn unicode_path_exists() {
1176 assert!(Path2::new(".").exists());
1177 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1179 let tmpdir = tmpdir();
1180 let unicode = tmpdir.path();
1181 let unicode = unicode.join(&format!("test-각丁ー再见"));
1182 check!(fs::create_dir(&unicode));
1183 assert!(unicode.exists());
1184 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1188 fn copy_file_does_not_exist() {
1189 let from = Path2::new("test/nonexistent-bogus-path");
1190 let to = Path2::new("test/other-bogus-path");
1192 match fs::copy(&from, &to) {
1195 assert!(!from.exists());
1196 assert!(!to.exists());
1203 let tmpdir = tmpdir();
1204 let input = tmpdir.join("in.txt");
1205 let out = tmpdir.join("out.txt");
1207 check!(check!(File::create(&input)).write(b"hello"));
1208 check!(fs::copy(&input, &out));
1209 let mut v = Vec::new();
1210 check!(check!(File::open(&out)).read_to_end(&mut v));
1211 assert_eq!(v.as_slice(), b"hello");
1213 assert_eq!(check!(input.metadata()).permissions(),
1214 check!(out.metadata()).permissions());
1218 fn copy_file_dst_dir() {
1219 let tmpdir = tmpdir();
1220 let out = tmpdir.join("out");
1222 check!(File::create(&out));
1223 match fs::copy(&*out, tmpdir.path()) {
1224 Ok(..) => panic!(), Err(..) => {}
1229 fn copy_file_dst_exists() {
1230 let tmpdir = tmpdir();
1231 let input = tmpdir.join("in");
1232 let output = tmpdir.join("out");
1234 check!(check!(File::create(&input)).write("foo".as_bytes()));
1235 check!(check!(File::create(&output)).write("bar".as_bytes()));
1236 check!(fs::copy(&input, &output));
1238 let mut v = Vec::new();
1239 check!(check!(File::open(&output)).read_to_end(&mut v));
1240 assert_eq!(v, b"foo".to_vec());
1244 fn copy_file_src_dir() {
1245 let tmpdir = tmpdir();
1246 let out = tmpdir.join("out");
1248 match fs::copy(tmpdir.path(), &out) {
1249 Ok(..) => panic!(), Err(..) => {}
1251 assert!(!out.exists());
1255 fn copy_file_preserves_perm_bits() {
1256 let tmpdir = tmpdir();
1257 let input = tmpdir.join("in.txt");
1258 let out = tmpdir.join("out.txt");
1260 let attr = check!(check!(File::create(&input)).metadata());
1261 let mut p = attr.permissions();
1262 p.set_readonly(true);
1263 check!(fs::set_permissions(&input, p));
1264 check!(fs::copy(&input, &out));
1265 assert!(check!(out.metadata()).permissions().readonly());
1268 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1270 fn symlinks_work() {
1271 let tmpdir = tmpdir();
1272 let input = tmpdir.join("in.txt");
1273 let out = tmpdir.join("out.txt");
1275 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1276 check!(fs::soft_link(&input, &out));
1277 // if cfg!(not(windows)) {
1278 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1279 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1281 assert_eq!(check!(fs::metadata(&out)).len(),
1282 check!(fs::metadata(&input)).len());
1283 let mut v = Vec::new();
1284 check!(check!(File::open(&out)).read_to_end(&mut v));
1285 assert_eq!(v, b"foobar".to_vec());
1288 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1290 fn symlink_noexist() {
1291 let tmpdir = tmpdir();
1292 // symlinks can point to things that don't exist
1293 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1294 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1295 tmpdir.join("foo"));
1299 fn readlink_not_symlink() {
1300 let tmpdir = tmpdir();
1301 match fs::read_link(tmpdir.path()) {
1302 Ok(..) => panic!("wanted a failure"),
1309 let tmpdir = tmpdir();
1310 let input = tmpdir.join("in.txt");
1311 let out = tmpdir.join("out.txt");
1313 check!(check!(File::create(&input)).write("foobar".as_bytes()));
1314 check!(fs::hard_link(&input, &out));
1315 assert_eq!(check!(fs::metadata(&out)).len(),
1316 check!(fs::metadata(&input)).len());
1317 assert_eq!(check!(fs::metadata(&out)).len(),
1318 check!(input.metadata()).len());
1319 let mut v = Vec::new();
1320 check!(check!(File::open(&out)).read_to_end(&mut v));
1321 assert_eq!(v, b"foobar".to_vec());
1323 // can't link to yourself
1324 match fs::hard_link(&input, &input) {
1325 Ok(..) => panic!("wanted a failure"),
1328 // can't link to something that doesn't exist
1329 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1330 Ok(..) => panic!("wanted a failure"),
1337 let tmpdir = tmpdir();
1338 let file = tmpdir.join("in.txt");
1340 check!(File::create(&file));
1341 let attr = check!(fs::metadata(&file));
1342 assert!(!attr.permissions().readonly());
1343 let mut p = attr.permissions();
1344 p.set_readonly(true);
1345 check!(fs::set_permissions(&file, p.clone()));
1346 let attr = check!(fs::metadata(&file));
1347 assert!(attr.permissions().readonly());
1349 match fs::set_permissions(&tmpdir.join("foo"), p) {
1350 Ok(..) => panic!("wanted a panic"),
1356 fn sync_doesnt_kill_anything() {
1357 let tmpdir = tmpdir();
1358 let path = tmpdir.join("in.txt");
1360 let mut file = check!(File::create(&path));
1361 check!(file.sync_all());
1362 check!(file.sync_data());
1363 check!(file.write(b"foo"));
1364 check!(file.sync_all());
1365 check!(file.sync_data());
1369 fn truncate_works() {
1370 let tmpdir = tmpdir();
1371 let path = tmpdir.join("in.txt");
1373 let mut file = check!(File::create(&path));
1374 check!(file.write(b"foo"));
1375 check!(file.sync_all());
1377 // Do some simple things with truncation
1378 assert_eq!(check!(file.metadata()).len(), 3);
1379 check!(file.set_len(10));
1380 assert_eq!(check!(file.metadata()).len(), 10);
1381 check!(file.write(b"bar"));
1382 check!(file.sync_all());
1383 assert_eq!(check!(file.metadata()).len(), 10);
1385 let mut v = Vec::new();
1386 check!(check!(File::open(&path)).read_to_end(&mut v));
1387 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1389 // Truncate to a smaller length, don't seek, and then write something.
1390 // Ensure that the intermediate zeroes are all filled in (we're seeked
1391 // past the end of the file).
1392 check!(file.set_len(2));
1393 assert_eq!(check!(file.metadata()).len(), 2);
1394 check!(file.write(b"wut"));
1395 check!(file.sync_all());
1396 assert_eq!(check!(file.metadata()).len(), 9);
1397 let mut v = Vec::new();
1398 check!(check!(File::open(&path)).read_to_end(&mut v));
1399 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1404 use fs::OpenOptions as OO;
1405 fn c<T: Clone>(t: &T) -> T { t.clone() }
1407 let tmpdir = tmpdir();
1409 let mut r = OO::new(); r.read(true);
1410 let mut w = OO::new(); w.write(true);
1411 let mut rw = OO::new(); rw.write(true).read(true);
1413 match r.open(&tmpdir.join("a")) {
1414 Ok(..) => panic!(), Err(..) => {}
1417 // Perform each one twice to make sure that it succeeds the second time
1418 // (where the file exists)
1419 check!(c(&w).create(true).open(&tmpdir.join("b")));
1420 assert!(tmpdir.join("b").exists());
1421 check!(c(&w).create(true).open(&tmpdir.join("b")));
1422 check!(w.open(&tmpdir.join("b")));
1424 check!(c(&rw).create(true).open(&tmpdir.join("c")));
1425 assert!(tmpdir.join("c").exists());
1426 check!(c(&rw).create(true).open(&tmpdir.join("c")));
1427 check!(rw.open(&tmpdir.join("c")));
1429 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
1430 assert!(tmpdir.join("d").exists());
1431 check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
1432 check!(c(&w).append(true).open(&tmpdir.join("d")));
1434 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
1435 assert!(tmpdir.join("e").exists());
1436 check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
1437 check!(c(&rw).append(true).open(&tmpdir.join("e")));
1439 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
1440 assert!(tmpdir.join("f").exists());
1441 check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
1442 check!(c(&w).truncate(true).open(&tmpdir.join("f")));
1444 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
1445 assert!(tmpdir.join("g").exists());
1446 check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
1447 check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
1449 check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
1450 check!(r.open(&tmpdir.join("h")));
1452 let mut f = check!(r.open(&tmpdir.join("h")));
1453 assert!(f.write("wut".as_bytes()).is_err());
1455 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
1457 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
1458 check!(f.write("bar".as_bytes()));
1460 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
1462 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
1463 check!(f.write("bar".as_bytes()));
1465 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
1470 let tmpdir = tmpdir();
1471 let path = tmpdir.join("a");
1472 check!(File::create(&path));
1473 // These numbers have to be bigger than the time in the day to account
1474 // for timezones Windows in particular will fail in certain timezones
1475 // with small enough values
1476 check!(fs::set_file_times(&path, 100000, 200000));
1477 assert_eq!(check!(path.metadata()).accessed(), 100000);
1478 assert_eq!(check!(path.metadata()).modified(), 200000);
1482 fn utime_noexist() {
1483 let tmpdir = tmpdir();
1485 match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
1493 let mut bytes = [0; 1024];
1494 StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
1496 let tmpdir = tmpdir();
1498 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
1499 let mut v = Vec::new();
1500 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
1501 assert!(v == bytes.as_slice());
1505 fn unlink_readonly() {
1506 let tmpdir = tmpdir();
1507 let path = tmpdir.join("file");
1508 check!(File::create(&path));
1509 let mut perm = check!(fs::metadata(&path)).permissions();
1510 perm.set_readonly(true);
1511 check!(fs::set_permissions(&path, perm));
1512 check!(fs::remove_file(&path));
1516 fn mkdir_trailing_slash() {
1517 let tmpdir = tmpdir();
1518 let path = tmpdir.join("file");
1519 check!(fs::create_dir_all(&path.join("a/")));