1 // Copyright 2013-2014 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 // ignore-lexer-test FIXME #15679
13 //! Synchronous File I/O
15 //! This module provides a set of functions and traits for working
16 //! with regular files & directories on a filesystem.
18 //! At the top-level of the module are a set of freestanding functions, associated
19 //! with various filesystem operations. They all operate on `Path` objects.
21 //! All operations in this module, including those as part of `File` et al
22 //! block the task during execution. In the event of failure, all functions/methods
23 //! will return an `IoResult` type with an `Err` value.
25 //! Also included in this module is an implementation block on the `Path` object
26 //! defined in `std::path::Path`. The impl adds useful methods about inspecting the
27 //! metadata of a file. This includes getting the `stat` information, reading off
28 //! particular bits of it, etc.
33 //! # #![allow(unused_must_use)]
34 //! use std::io::fs::PathExtensions;
35 //! use std::io::{File, fs};
37 //! let path = Path::new("foo.txt");
39 //! // create the file, whether it exists or not
40 //! let mut file = File::create(&path);
41 //! file.write(b"foobar");
44 //! // open the file in read-only mode
45 //! let mut file = File::open(&path);
46 //! file.read_to_end();
48 //! println!("{}", path.stat().unwrap().size);
50 //! fs::unlink(&path);
54 use io::standard_error;
55 use io::{FilePermission, Write, Open, FileAccess, FileMode, FileType};
56 use io::{IoResult, IoError, InvalidInput};
57 use io::{FileStat, SeekStyle, Seek, Writer, Reader};
58 use io::{Read, Truncate, ReadWrite, Append};
59 use io::UpdateIoError;
61 use iter::{Iterator, Extend};
63 use option::Option::{Some, None};
64 use path::{Path, GenericPath};
66 use result::Result::{Err, Ok};
67 use slice::SlicePrelude;
71 use sys::fs as fs_imp;
74 /// Unconstrained file access type that exposes read and write operations
76 /// Can be constructed via `File::open()`, `File::create()`, and
77 /// `File::open_mode()`.
81 /// This type will return errors as an `IoResult<T>` if operations are
82 /// attempted against it for which its underlying file descriptor was not
83 /// configured at creation time, via the `FileAccess` parameter to
84 /// `File::open_mode()`.
91 impl sys_common::AsInner<fs_imp::FileDesc> for File {
92 fn as_inner(&self) -> &fs_imp::FileDesc {
98 /// Open a file at `path` in the mode specified by the `mode` and `access`
103 /// ```rust,should_fail
104 /// use std::io::{File, Open, ReadWrite};
106 /// let p = Path::new("/some/file/path.txt");
108 /// let file = match File::open_mode(&p, Open, ReadWrite) {
110 /// Err(e) => panic!("file error: {}", e),
112 /// // do some stuff with that file
114 /// // the file will be closed at the end of this block
117 /// `FileMode` and `FileAccess` provide information about the permissions
118 /// context in which a given stream is created. More information about them
119 /// can be found in `std::io`'s docs. If a file is opened with `Write`
120 /// or `ReadWrite` access, then it will be created if it does not already
123 /// Note that, with this function, a `File` is returned regardless of the
124 /// access-limitations indicated by `FileAccess` (e.g. calling `write` on a
125 /// `File` opened as `Read` will return an error at runtime).
129 /// This function will return an error under a number of different
130 /// circumstances, to include but not limited to:
132 /// * Opening a file that does not exist with `Read` access.
133 /// * Attempting to open a file with a `FileAccess` that the user lacks
135 /// * Filesystem-level errors (full disk, etc)
136 pub fn open_mode(path: &Path,
138 access: FileAccess) -> IoResult<File> {
139 fs_imp::open(path, mode, access).and_then(|fd| {
140 // On *BSD systems, we can open a directory as a file and read from it:
141 // fd=open("/tmp", O_RDONLY); read(fd, buf, N);
142 // due to an old tradition before the introduction of opendir(3).
143 // We explicitly reject it because there are few use cases.
144 if cfg!(not(any(windows, target_os = "linux", target_os = "android"))) &&
145 try!(fd.fstat()).kind == FileType::Directory {
148 desc: "is a directory",
158 }).update_err("couldn't open path as file", |e| {
159 format!("{}; path={}; mode={}; access={}", e, path.display(),
160 mode_string(mode), access_string(access))
164 /// Attempts to open a file in read-only mode. This function is equivalent to
165 /// `File::open_mode(path, Open, Read)`, and will raise all of the same
166 /// errors that `File::open_mode` does.
168 /// For more information, see the `File::open_mode` function.
173 /// use std::io::File;
175 /// let contents = File::open(&Path::new("foo.txt")).read_to_end();
177 pub fn open(path: &Path) -> IoResult<File> {
178 File::open_mode(path, Open, Read)
181 /// Attempts to create a file in write-only mode. This function is
182 /// equivalent to `File::open_mode(path, Truncate, Write)`, and will
183 /// raise all of the same errors that `File::open_mode` does.
185 /// For more information, see the `File::open_mode` function.
190 /// # #![allow(unused_must_use)]
191 /// use std::io::File;
193 /// let mut f = File::create(&Path::new("foo.txt"));
194 /// f.write(b"This is a sample file");
196 /// # ::std::io::fs::unlink(&Path::new("foo.txt"));
198 pub fn create(path: &Path) -> IoResult<File> {
199 File::open_mode(path, Truncate, Write)
200 .update_desc("couldn't create file")
203 /// Returns the original path which was used to open this file.
204 pub fn path<'a>(&'a self) -> &'a Path {
208 /// Synchronizes all modifications to this file to its permanent storage
209 /// device. This will flush any internal buffers necessary to perform this
211 pub fn fsync(&mut self) -> IoResult<()> {
213 .update_err("couldn't fsync file",
214 |e| format!("{}; path={}", e, self.path.display()))
217 /// This function is similar to `fsync`, except that it may not synchronize
218 /// file metadata to the filesystem. This is intended for use case which
219 /// must synchronize content, but don't need the metadata on disk. The goal
220 /// of this method is to reduce disk operations.
221 pub fn datasync(&mut self) -> IoResult<()> {
223 .update_err("couldn't datasync file",
224 |e| format!("{}; path={}", e, self.path.display()))
227 /// Either truncates or extends the underlying file, updating the size of
228 /// this file to become `size`. This is equivalent to unix's `truncate`
231 /// If the `size` is less than the current file's size, then the file will
232 /// be shrunk. If it is greater than the current file's size, then the file
233 /// will be extended to `size` and have all of the intermediate data filled
235 pub fn truncate(&mut self, size: i64) -> IoResult<()> {
236 self.fd.truncate(size)
237 .update_err("couldn't truncate file", |e|
238 format!("{}; path={}; size={}", e, self.path.display(), size))
241 /// Returns true if the stream has reached the end of the file.
243 /// If true, then this file will no longer continue to return data via
246 /// Note that the operating system will not return an `EOF` indicator
247 /// until you have attempted to read past the end of the file, so if
248 /// you've read _exactly_ the number of bytes in the file, this will
249 /// return `false`, not `true`.
250 pub fn eof(&self) -> bool {
254 /// Queries information about the underlying file.
255 pub fn stat(&self) -> IoResult<FileStat> {
257 .update_err("couldn't fstat file", |e|
258 format!("{}; path={}", e, self.path.display()))
262 /// Unlink a file from the underlying filesystem.
267 /// # #![allow(unused_must_use)]
270 /// let p = Path::new("/some/file/path.txt");
274 /// Note that, just because an unlink call was successful, it is not
275 /// guaranteed that a file is immediately deleted (e.g. depending on
276 /// platform, other open file descriptors may prevent immediate removal)
280 /// This function will return an error if `path` points to a directory, if the
281 /// user lacks permissions to remove the file, or if some other filesystem-level
283 pub fn unlink(path: &Path) -> IoResult<()> {
285 .update_err("couldn't unlink path", |e|
286 format!("{}; path={}", e, path.display()))
289 /// Given a path, query the file system to get information about a file,
290 /// directory, etc. This function will traverse symlinks to query
291 /// information about the destination file.
298 /// let p = Path::new("/some/file/path.txt");
299 /// match fs::stat(&p) {
300 /// Ok(stat) => { /* ... */ }
301 /// Err(e) => { /* handle error */ }
307 /// This function will return an error if the user lacks the requisite permissions
308 /// to perform a `stat` call on the given `path` or if there is no entry in the
309 /// filesystem at the provided path.
310 pub fn stat(path: &Path) -> IoResult<FileStat> {
312 .update_err("couldn't stat path", |e|
313 format!("{}; path={}", e, path.display()))
316 /// Perform the same operation as the `stat` function, except that this
317 /// function does not traverse through symlinks. This will return
318 /// information about the symlink file instead of the file that it points
324 pub fn lstat(path: &Path) -> IoResult<FileStat> {
326 .update_err("couldn't lstat path", |e|
327 format!("{}; path={}", e, path.display()))
330 /// Rename a file or directory to a new name.
335 /// # #![allow(unused_must_use)]
338 /// fs::rename(&Path::new("foo"), &Path::new("bar"));
343 /// This function will return an error if the provided `from` doesn't exist, if
344 /// the process lacks permissions to view the contents, or if some other
345 /// intermittent I/O error occurs.
346 pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
347 fs_imp::rename(from, to)
348 .update_err("couldn't rename path", |e|
349 format!("{}; from={}; to={}", e, from.display(), to.display()))
352 /// Copies the contents of one file to another. This function will also
353 /// copy the permission bits of the original file to the destination file.
355 /// Note that if `from` and `to` both point to the same file, then the file
356 /// will likely get truncated by this operation.
361 /// # #![allow(unused_must_use)]
364 /// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt"));
369 /// This function will return an error in the following situations, but is not
370 /// limited to just these cases:
372 /// * The `from` path is not a file
373 /// * The `from` file does not exist
374 /// * The current process does not have the permission rights to access
375 /// `from` or write `to`
377 /// Note that this copy is not atomic in that once the destination is
378 /// ensured to not exist, there is nothing preventing the destination from
379 /// being created and then destroyed by this operation.
380 pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
381 fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
382 result.update_err("couldn't copy path", |e| {
383 format!("{}; from={}; to={}", e, from.display(), to.display())
388 return update_err(Err(IoError {
389 kind: io::MismatchedFileTypeForOperation,
390 desc: "the source path is not an existing file",
395 let mut reader = try!(File::open(from));
396 let mut writer = try!(File::create(to));
398 try!(update_err(super::util::copy(&mut reader, &mut writer), from, to));
400 chmod(to, try!(update_err(from.stat(), from, to)).perm)
403 /// Changes the permission mode bits found on a file or a directory. This
404 /// function takes a mask from the `io` module
409 /// # #![allow(unused_must_use)]
413 /// fs::chmod(&Path::new("file.txt"), io::USER_FILE);
414 /// fs::chmod(&Path::new("file.txt"), io::USER_READ | io::USER_WRITE);
415 /// fs::chmod(&Path::new("dir"), io::USER_DIR);
416 /// fs::chmod(&Path::new("file.exe"), io::USER_EXEC);
421 /// This function will return an error if the provided `path` doesn't exist, if
422 /// the process lacks permissions to change the attributes of the file, or if
423 /// some other I/O error is encountered.
424 pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> {
425 fs_imp::chmod(path, mode.bits() as uint)
426 .update_err("couldn't chmod path", |e|
427 format!("{}; path={}; mode={}", e, path.display(), mode))
430 /// Change the user and group owners of a file at the specified path.
431 pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
432 fs_imp::chown(path, uid, gid)
433 .update_err("couldn't chown path", |e|
434 format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid))
437 /// Creates a new hard link on the filesystem. The `dst` path will be a
438 /// link pointing to the `src` path. Note that systems often require these
439 /// two paths to both be located on the same filesystem.
440 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
441 fs_imp::link(src, dst)
442 .update_err("couldn't link path", |e|
443 format!("{}; src={}; dest={}", e, src.display(), dst.display()))
446 /// Creates a new symbolic link on the filesystem. The `dst` path will be a
447 /// symlink pointing to the `src` path.
448 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
449 fs_imp::symlink(src, dst)
450 .update_err("couldn't symlink path", |e|
451 format!("{}; src={}; dest={}", e, src.display(), dst.display()))
454 /// Reads a symlink, returning the file that the symlink points to.
458 /// This function will return an error on failure. Failure conditions include
459 /// reading a file that does not exist or reading a file which is not a symlink.
460 pub fn readlink(path: &Path) -> IoResult<Path> {
461 fs_imp::readlink(path)
462 .update_err("couldn't resolve symlink for path", |e|
463 format!("{}; path={}", e, path.display()))
466 /// Create a new, empty directory at the provided path
471 /// # #![allow(unused_must_use)]
475 /// let p = Path::new("/some/dir");
476 /// fs::mkdir(&p, io::USER_RWX);
481 /// This function will return an error if the user lacks permissions to make a
482 /// new directory at the provided `path`, or if the directory already exists.
483 pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
484 fs_imp::mkdir(path, mode.bits() as uint)
485 .update_err("couldn't create directory", |e|
486 format!("{}; path={}; mode={}", e, path.display(), mode))
489 /// Remove an existing, empty directory
494 /// # #![allow(unused_must_use)]
497 /// let p = Path::new("/some/dir");
503 /// This function will return an error if the user lacks permissions to remove
504 /// the directory at the provided `path`, or if the directory isn't empty.
505 pub fn rmdir(path: &Path) -> IoResult<()> {
507 .update_err("couldn't remove directory", |e|
508 format!("{}; path={}", e, path.display()))
511 /// Retrieve a vector containing all entries within a provided directory
516 /// use std::io::fs::PathExtensions;
520 /// // one possible implementation of fs::walk_dir only visiting files
521 /// fn visit_dirs(dir: &Path, cb: |&Path|) -> io::IoResult<()> {
522 /// if dir.is_dir() {
523 /// let contents = try!(fs::readdir(dir));
524 /// for entry in contents.iter() {
525 /// if entry.is_dir() {
526 /// try!(visit_dirs(entry, |p| cb(p)));
533 /// Err(io::standard_error(io::InvalidInput))
540 /// This function will return an error if the provided `path` doesn't exist, if
541 /// the process lacks permissions to view the contents or if the `path` points
542 /// at a non-directory file
543 pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
544 fs_imp::readdir(path)
545 .update_err("couldn't read directory",
546 |e| format!("{}; path={}", e, path.display()))
549 /// Returns an iterator which will recursively walk the directory structure
550 /// rooted at `path`. The path given will not be iterated over, and this will
551 /// perform iteration in some top-down order. The contents of unreadable
552 /// subdirectories are ignored.
553 pub fn walk_dir(path: &Path) -> IoResult<Directories> {
555 stack: try!(readdir(path).update_err("couldn't walk directory",
556 |e| format!("{}; path={}", e, path.display())))
560 /// An iterator which walks over a directory
561 pub struct Directories {
565 impl Iterator<Path> for Directories {
566 fn next(&mut self) -> Option<Path> {
567 match self.stack.pop() {
570 match readdir(&path) {
571 Ok(dirs) => { self.stack.extend(dirs.into_iter()); }
582 /// Recursively create a directory and all of its parent components if they
588 pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
589 // tjc: if directory exists but with different permissions,
590 // should we return false?
595 let mut comps = path.components();
596 let mut curpath = path.root_path().unwrap_or(Path::new("."));
601 let result = mkdir(&curpath, mode)
602 .update_err("couldn't recursively mkdir",
603 |e| format!("{}; path={}", e, path.display()));
608 if try!(stat(&curpath)).kind != FileType::Directory {
609 return Err(mkdir_err);
619 /// Removes a directory at this path, after removing all its contents. Use
624 /// See `file::unlink` and `fs::readdir`
625 pub fn rmdir_recursive(path: &Path) -> IoResult<()> {
626 let mut rm_stack = Vec::new();
627 rm_stack.push(path.clone());
629 fn rmdir_failed(err: &IoError, path: &Path) -> String {
630 format!("rmdir_recursive failed; path={}; cause={}",
634 fn update_err<T>(err: IoResult<T>, path: &Path) -> IoResult<T> {
635 err.update_err("couldn't recursively rmdir",
636 |e| rmdir_failed(e, path))
639 while !rm_stack.is_empty() {
640 let children = try!(readdir(rm_stack.last().unwrap())
641 .update_detail(|e| rmdir_failed(e, path)));
643 let mut has_child_dir = false;
645 // delete all regular files in the way and push subdirs
647 for child in children.into_iter() {
648 // FIXME(#12795) we should use lstat in all cases
649 let child_type = match cfg!(windows) {
650 true => try!(update_err(stat(&child), path)),
651 false => try!(update_err(lstat(&child), path))
654 if child_type.kind == FileType::Directory {
655 rm_stack.push(child);
656 has_child_dir = true;
658 // we can carry on safely if the file is already gone
659 // (eg: deleted by someone else since readdir)
660 match update_err(unlink(&child), path) {
662 Err(ref e) if e.kind == io::FileNotFound => (),
663 Err(e) => return Err(e)
668 // if no subdir was found, let's pop and delete
670 let result = update_err(rmdir(&rm_stack.pop().unwrap()), path);
673 Err(ref e) if e.kind == io::FileNotFound => (),
674 Err(e) => return Err(e)
682 /// Changes the timestamps for a file's last modification and access time.
683 /// The file at the path specified will have its last access time set to
684 /// `atime` and its modification time set to `mtime`. The times specified should
685 /// be in milliseconds.
686 // FIXME(#10301) these arguments should not be u64
687 pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> {
688 fs_imp::utime(path, atime, mtime)
689 .update_err("couldn't change_file_times", |e|
690 format!("{}; path={}", e, path.display()))
693 impl Reader for File {
694 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
695 fn update_err<T>(result: IoResult<T>, file: &File) -> IoResult<T> {
696 result.update_err("couldn't read file",
697 |e| format!("{}; path={}",
698 e, file.path.display()))
701 let result = update_err(self.fd.read(buf), self);
705 self.last_nread = read as int;
707 0 => update_err(Err(standard_error(io::EndOfFile)), self),
708 _ => Ok(read as uint)
716 impl Writer for File {
717 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
719 .update_err("couldn't write to file",
720 |e| format!("{}; path={}", e, self.path.display()))
725 fn tell(&self) -> IoResult<u64> {
727 .update_err("couldn't retrieve file cursor (`tell`)",
728 |e| format!("{}; path={}", e, self.path.display()))
731 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
732 let err = match self.fd.seek(pos, style) {
734 // successful seek resets EOF indicator
735 self.last_nread = -1;
740 err.update_err("couldn't seek in file",
741 |e| format!("{}; path={}", e, self.path.display()))
745 /// Utility methods for paths.
746 pub trait PathExtensions {
747 /// Get information on the file, directory, etc at this path.
749 /// Consult the `fs::stat` documentation for more info.
751 /// This call preserves identical runtime/error semantics with `file::stat`.
752 fn stat(&self) -> IoResult<FileStat>;
754 /// Get information on the file, directory, etc at this path, not following
757 /// Consult the `fs::lstat` documentation for more info.
759 /// This call preserves identical runtime/error semantics with `file::lstat`.
760 fn lstat(&self) -> IoResult<FileStat>;
762 /// Boolean value indicator whether the underlying file exists on the local
763 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
764 fn exists(&self) -> bool;
766 /// Whether the underlying implementation (be it a file path, or something
767 /// else) points at a "regular file" on the FS. Will return false for paths
768 /// to non-existent locations or directories or other non-regular files
769 /// (named pipes, etc). Follows links when making this determination.
770 fn is_file(&self) -> bool;
772 /// Whether the underlying implementation (be it a file path, or something
773 /// else) is pointing at a directory in the underlying FS. Will return
774 /// false for paths to non-existent locations or if the item is not a
775 /// directory (eg files, named pipes, etc). Follows links when making this
777 fn is_dir(&self) -> bool;
780 impl PathExtensions for path::Path {
781 fn stat(&self) -> IoResult<FileStat> { stat(self) }
782 fn lstat(&self) -> IoResult<FileStat> { lstat(self) }
783 fn exists(&self) -> bool {
786 fn is_file(&self) -> bool {
788 Ok(s) => s.kind == FileType::RegularFile,
792 fn is_dir(&self) -> bool {
794 Ok(s) => s.kind == FileType::Directory,
800 fn mode_string(mode: FileMode) -> &'static str {
802 super::Open => "open",
803 super::Append => "append",
804 super::Truncate => "truncate"
808 fn access_string(access: FileAccess) -> &'static str {
810 super::Read => "read",
811 super::Write => "write",
812 super::ReadWrite => "readwrite"
817 #[allow(unused_imports)]
818 #[allow(unused_variables)]
822 use io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite, FileType};
831 macro_rules! check( ($e:expr) => (
834 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
838 macro_rules! error( ($e:expr, $s:expr) => (
840 Ok(_) => panic!("Unexpected success. Should've been: {}", $s),
841 Err(ref err) => assert!(err.to_string().as_slice().contains($s.as_slice()),
842 format!("`{}` did not contain `{}`", err, $s))
846 pub struct TempDir(Path);
849 fn join(&self, path: &str) -> Path {
850 let TempDir(ref p) = *self;
854 fn path<'a>(&'a self) -> &'a Path {
855 let TempDir(ref p) = *self;
860 impl Drop for TempDir {
862 // Gee, seeing how we're testing the fs module I sure hope that we
863 // at least implement this correctly!
864 let TempDir(ref p) = *self;
865 check!(io::fs::rmdir_recursive(p));
869 pub fn tmpdir() -> TempDir {
872 let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>()));
873 check!(io::fs::mkdir(&ret, io::USER_RWX));
878 fn file_test_io_smoke_test() {
879 let message = "it's alright. have a good time";
880 let tmpdir = tmpdir();
881 let filename = &tmpdir.join("file_rt_io_file_test.txt");
883 let mut write_stream = File::open_mode(filename, Open, ReadWrite);
884 check!(write_stream.write(message.as_bytes()));
887 let mut read_stream = File::open_mode(filename, Open, Read);
888 let mut read_buf = [0, .. 1028];
889 let read_str = match check!(read_stream.read(&mut read_buf)) {
890 -1|0 => panic!("shouldn't happen"),
891 n => str::from_utf8(read_buf[..n]).unwrap().to_string()
893 assert_eq!(read_str.as_slice(), message);
895 check!(unlink(filename));
899 fn invalid_path_raises() {
900 let tmpdir = tmpdir();
901 let filename = &tmpdir.join("file_that_does_not_exist.txt");
902 let result = File::open_mode(filename, Open, Read);
904 error!(result, "couldn't open path as file");
906 error!(result, "no such file or directory");
908 error!(result, format!("path={}; mode=open; access=read", filename.display()));
912 fn file_test_iounlinking_invalid_path_should_raise_condition() {
913 let tmpdir = tmpdir();
914 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
916 let result = unlink(filename);
918 error!(result, "couldn't unlink path");
920 error!(result, "no such file or directory");
922 error!(result, format!("path={}", filename.display()));
926 fn file_test_io_non_positional_read() {
927 let message: &str = "ten-four";
928 let mut read_mem = [0, .. 8];
929 let tmpdir = tmpdir();
930 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
932 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
933 check!(rw_stream.write(message.as_bytes()));
936 let mut read_stream = File::open_mode(filename, Open, Read);
938 let read_buf = read_mem[mut 0..4];
939 check!(read_stream.read(read_buf));
942 let read_buf = read_mem[mut 4..8];
943 check!(read_stream.read(read_buf));
946 check!(unlink(filename));
947 let read_str = str::from_utf8(&read_mem).unwrap();
948 assert_eq!(read_str, message);
952 fn file_test_io_seek_and_tell_smoke_test() {
953 let message = "ten-four";
954 let mut read_mem = [0, .. 4];
955 let set_cursor = 4 as u64;
956 let mut tell_pos_pre_read;
957 let mut tell_pos_post_read;
958 let tmpdir = tmpdir();
959 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
961 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
962 check!(rw_stream.write(message.as_bytes()));
965 let mut read_stream = File::open_mode(filename, Open, Read);
966 check!(read_stream.seek(set_cursor as i64, SeekSet));
967 tell_pos_pre_read = check!(read_stream.tell());
968 check!(read_stream.read(&mut read_mem));
969 tell_pos_post_read = check!(read_stream.tell());
971 check!(unlink(filename));
972 let read_str = str::from_utf8(&read_mem).unwrap();
973 assert_eq!(read_str, message.slice(4, 8));
974 assert_eq!(tell_pos_pre_read, set_cursor);
975 assert_eq!(tell_pos_post_read, message.len() as u64);
979 fn file_test_io_seek_and_write() {
980 let initial_msg = "food-is-yummy";
981 let overwrite_msg = "-the-bar!!";
982 let final_msg = "foo-the-bar!!";
984 let mut read_mem = [0, .. 13];
985 let tmpdir = tmpdir();
986 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
988 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
989 check!(rw_stream.write(initial_msg.as_bytes()));
990 check!(rw_stream.seek(seek_idx as i64, SeekSet));
991 check!(rw_stream.write(overwrite_msg.as_bytes()));
994 let mut read_stream = File::open_mode(filename, Open, Read);
995 check!(read_stream.read(&mut read_mem));
997 check!(unlink(filename));
998 let read_str = str::from_utf8(&read_mem).unwrap();
999 assert!(read_str.as_slice() == final_msg.as_slice());
1003 fn file_test_io_seek_shakedown() {
1004 use str; // 01234567890123
1005 let initial_msg = "qwer-asdf-zxcv";
1006 let chunk_one: &str = "qwer";
1007 let chunk_two: &str = "asdf";
1008 let chunk_three: &str = "zxcv";
1009 let mut read_mem = [0, .. 4];
1010 let tmpdir = tmpdir();
1011 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1013 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1014 check!(rw_stream.write(initial_msg.as_bytes()));
1017 let mut read_stream = File::open_mode(filename, Open, Read);
1019 check!(read_stream.seek(-4, SeekEnd));
1020 check!(read_stream.read(&mut read_mem));
1021 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1023 check!(read_stream.seek(-9, SeekCur));
1024 check!(read_stream.read(&mut read_mem));
1025 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1027 check!(read_stream.seek(0, SeekSet));
1028 check!(read_stream.read(&mut read_mem));
1029 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1031 check!(unlink(filename));
1035 fn file_test_stat_is_correct_on_is_file() {
1036 let tmpdir = tmpdir();
1037 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1039 let mut fs = check!(File::open_mode(filename, Open, ReadWrite));
1041 fs.write(msg.as_bytes()).unwrap();
1043 let fstat_res = check!(fs.stat());
1044 assert_eq!(fstat_res.kind, FileType::RegularFile);
1046 let stat_res_fn = check!(stat(filename));
1047 assert_eq!(stat_res_fn.kind, FileType::RegularFile);
1048 let stat_res_meth = check!(filename.stat());
1049 assert_eq!(stat_res_meth.kind, FileType::RegularFile);
1050 check!(unlink(filename));
1054 fn file_test_stat_is_correct_on_is_dir() {
1055 let tmpdir = tmpdir();
1056 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1057 check!(mkdir(filename, io::USER_RWX));
1058 let stat_res_fn = check!(stat(filename));
1059 assert!(stat_res_fn.kind == FileType::Directory);
1060 let stat_res_meth = check!(filename.stat());
1061 assert!(stat_res_meth.kind == FileType::Directory);
1062 check!(rmdir(filename));
1066 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1067 let tmpdir = tmpdir();
1068 let dir = &tmpdir.join("fileinfo_false_on_dir");
1069 check!(mkdir(dir, io::USER_RWX));
1070 assert!(dir.is_file() == false);
1075 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1076 let tmpdir = tmpdir();
1077 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1078 check!(File::create(file).write(b"foo"));
1079 assert!(file.exists());
1080 check!(unlink(file));
1081 assert!(!file.exists());
1085 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1086 let tmpdir = tmpdir();
1087 let dir = &tmpdir.join("before_and_after_dir");
1088 assert!(!dir.exists());
1089 check!(mkdir(dir, io::USER_RWX));
1090 assert!(dir.exists());
1091 assert!(dir.is_dir());
1093 assert!(!dir.exists());
1097 fn file_test_directoryinfo_readdir() {
1099 let tmpdir = tmpdir();
1100 let dir = &tmpdir.join("di_readdir");
1101 check!(mkdir(dir, io::USER_RWX));
1103 for n in range(0i,3) {
1104 let f = dir.join(format!("{}.txt", n));
1105 let mut w = check!(File::create(&f));
1106 let msg_str = format!("{}{}", prefix, n.to_string());
1107 let msg = msg_str.as_slice().as_bytes();
1108 check!(w.write(msg));
1110 let files = check!(readdir(dir));
1111 let mut mem = [0u8, .. 4];
1112 for f in files.iter() {
1114 let n = f.filestem_str();
1115 check!(File::open(f).read(&mut mem));
1116 let read_str = str::from_utf8(&mem).unwrap();
1117 let expected = match n {
1118 None|Some("") => panic!("really shouldn't happen.."),
1119 Some(n) => format!("{}{}", prefix, n),
1121 assert_eq!(expected.as_slice(), read_str);
1129 fn file_test_walk_dir() {
1130 let tmpdir = tmpdir();
1131 let dir = &tmpdir.join("walk_dir");
1132 check!(mkdir(dir, io::USER_RWX));
1134 let dir1 = &dir.join("01/02/03");
1135 check!(mkdir_recursive(dir1, io::USER_RWX));
1136 check!(File::create(&dir1.join("04")));
1138 let dir2 = &dir.join("11/12/13");
1139 check!(mkdir_recursive(dir2, io::USER_RWX));
1140 check!(File::create(&dir2.join("14")));
1142 let mut files = check!(walk_dir(dir));
1143 let mut cur = [0u8, .. 2];
1145 let stem = f.filestem_str().unwrap();
1146 let root = stem.as_bytes()[0] - b'0';
1147 let name = stem.as_bytes()[1] - b'0';
1148 assert!(cur[root as uint] < name);
1149 cur[root as uint] = name;
1152 check!(rmdir_recursive(dir));
1156 fn recursive_mkdir() {
1157 let tmpdir = tmpdir();
1158 let dir = tmpdir.join("d1/d2");
1159 check!(mkdir_recursive(&dir, io::USER_RWX));
1160 assert!(dir.is_dir())
1164 fn recursive_mkdir_failure() {
1165 let tmpdir = tmpdir();
1166 let dir = tmpdir.join("d1");
1167 let file = dir.join("f1");
1169 check!(mkdir_recursive(&dir, io::USER_RWX));
1170 check!(File::create(&file));
1172 let result = mkdir_recursive(&file, io::USER_RWX);
1174 error!(result, "couldn't recursively mkdir");
1175 error!(result, "couldn't create directory");
1176 error!(result, "mode=0700");
1177 error!(result, format!("path={}", file.display()));
1181 fn recursive_mkdir_slash() {
1182 check!(mkdir_recursive(&Path::new("/"), io::USER_RWX));
1185 // FIXME(#12795) depends on lstat to work on windows
1186 #[cfg(not(windows))]
1188 fn recursive_rmdir() {
1189 let tmpdir = tmpdir();
1190 let d1 = tmpdir.join("d1");
1191 let dt = d1.join("t");
1192 let dtt = dt.join("t");
1193 let d2 = tmpdir.join("d2");
1194 let canary = d2.join("do_not_delete");
1195 check!(mkdir_recursive(&dtt, io::USER_RWX));
1196 check!(mkdir_recursive(&d2, io::USER_RWX));
1197 check!(File::create(&canary).write(b"foo"));
1198 check!(symlink(&d2, &dt.join("d2")));
1199 check!(rmdir_recursive(&d1));
1201 assert!(!d1.is_dir());
1202 assert!(canary.exists());
1206 fn unicode_path_is_dir() {
1207 assert!(Path::new(".").is_dir());
1208 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
1210 let tmpdir = tmpdir();
1212 let mut dirpath = tmpdir.path().clone();
1213 dirpath.push(format!("test-가一ー你好"));
1214 check!(mkdir(&dirpath, io::USER_RWX));
1215 assert!(dirpath.is_dir());
1217 let mut filepath = dirpath;
1218 filepath.push("unicode-file-\uac00\u4e00\u30fc\u4f60\u597d.rs");
1219 check!(File::create(&filepath)); // ignore return; touch only
1220 assert!(!filepath.is_dir());
1221 assert!(filepath.exists());
1225 fn unicode_path_exists() {
1226 assert!(Path::new(".").exists());
1227 assert!(!Path::new("test/nonexistent-bogus-path").exists());
1229 let tmpdir = tmpdir();
1230 let unicode = tmpdir.path();
1231 let unicode = unicode.join(format!("test-각丁ー再见"));
1232 check!(mkdir(&unicode, io::USER_RWX));
1233 assert!(unicode.exists());
1234 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
1238 fn copy_file_does_not_exist() {
1239 let from = Path::new("test/nonexistent-bogus-path");
1240 let to = Path::new("test/other-bogus-path");
1242 error!(copy(&from, &to),
1243 format!("couldn't copy path (the source path is not an \
1244 existing file; from={}; to={})",
1245 from.display(), to.display()));
1247 match copy(&from, &to) {
1250 assert!(!from.exists());
1251 assert!(!to.exists());
1258 let tmpdir = tmpdir();
1259 let input = tmpdir.join("in.txt");
1260 let out = tmpdir.join("out.txt");
1262 check!(File::create(&input).write(b"hello"));
1263 check!(copy(&input, &out));
1264 let contents = check!(File::open(&out).read_to_end());
1265 assert_eq!(contents.as_slice(), b"hello");
1267 assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
1271 fn copy_file_dst_dir() {
1272 let tmpdir = tmpdir();
1273 let out = tmpdir.join("out");
1275 check!(File::create(&out));
1276 match copy(&out, tmpdir.path()) {
1277 Ok(..) => panic!(), Err(..) => {}
1282 fn copy_file_dst_exists() {
1283 let tmpdir = tmpdir();
1284 let input = tmpdir.join("in");
1285 let output = tmpdir.join("out");
1287 check!(File::create(&input).write("foo".as_bytes()));
1288 check!(File::create(&output).write("bar".as_bytes()));
1289 check!(copy(&input, &output));
1291 assert_eq!(check!(File::open(&output).read_to_end()),
1296 fn copy_file_src_dir() {
1297 let tmpdir = tmpdir();
1298 let out = tmpdir.join("out");
1300 match copy(tmpdir.path(), &out) {
1301 Ok(..) => panic!(), Err(..) => {}
1303 assert!(!out.exists());
1307 fn copy_file_preserves_perm_bits() {
1308 let tmpdir = tmpdir();
1309 let input = tmpdir.join("in.txt");
1310 let out = tmpdir.join("out.txt");
1312 check!(File::create(&input));
1313 check!(chmod(&input, io::USER_READ));
1314 check!(copy(&input, &out));
1315 assert!(!check!(out.stat()).perm.intersects(io::USER_WRITE));
1317 check!(chmod(&input, io::USER_FILE));
1318 check!(chmod(&out, io::USER_FILE));
1321 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1323 fn symlinks_work() {
1324 let tmpdir = tmpdir();
1325 let input = tmpdir.join("in.txt");
1326 let out = tmpdir.join("out.txt");
1328 check!(File::create(&input).write("foobar".as_bytes()));
1329 check!(symlink(&input, &out));
1330 if cfg!(not(windows)) {
1331 assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1332 assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1334 assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1335 assert_eq!(check!(File::open(&out).read_to_end()),
1336 b"foobar".to_vec());
1339 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1341 fn symlink_noexist() {
1342 let tmpdir = tmpdir();
1343 // symlinks can point to things that don't exist
1344 check!(symlink(&tmpdir.join("foo"), &tmpdir.join("bar")));
1345 assert!(check!(readlink(&tmpdir.join("bar"))) == tmpdir.join("foo"));
1349 fn readlink_not_symlink() {
1350 let tmpdir = tmpdir();
1351 match readlink(tmpdir.path()) {
1352 Ok(..) => panic!("wanted a failure"),
1359 let tmpdir = tmpdir();
1360 let input = tmpdir.join("in.txt");
1361 let out = tmpdir.join("out.txt");
1363 check!(File::create(&input).write("foobar".as_bytes()));
1364 check!(link(&input, &out));
1365 if cfg!(not(windows)) {
1366 assert_eq!(check!(lstat(&out)).kind, FileType::RegularFile);
1367 assert_eq!(check!(out.lstat()).kind, FileType::RegularFile);
1368 assert_eq!(check!(stat(&out)).unstable.nlink, 2);
1369 assert_eq!(check!(out.stat()).unstable.nlink, 2);
1371 assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1372 assert_eq!(check!(stat(&out)).size, check!(input.stat()).size);
1373 assert_eq!(check!(File::open(&out).read_to_end()),
1374 b"foobar".to_vec());
1376 // can't link to yourself
1377 match link(&input, &input) {
1378 Ok(..) => panic!("wanted a failure"),
1381 // can't link to something that doesn't exist
1382 match link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1383 Ok(..) => panic!("wanted a failure"),
1390 let tmpdir = tmpdir();
1391 let file = tmpdir.join("in.txt");
1393 check!(File::create(&file));
1394 assert!(check!(stat(&file)).perm.contains(io::USER_WRITE));
1395 check!(chmod(&file, io::USER_READ));
1396 assert!(!check!(stat(&file)).perm.contains(io::USER_WRITE));
1398 match chmod(&tmpdir.join("foo"), io::USER_RWX) {
1399 Ok(..) => panic!("wanted a panic"),
1403 check!(chmod(&file, io::USER_FILE));
1407 fn sync_doesnt_kill_anything() {
1408 let tmpdir = tmpdir();
1409 let path = tmpdir.join("in.txt");
1411 let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1412 check!(file.fsync());
1413 check!(file.datasync());
1414 check!(file.write(b"foo"));
1415 check!(file.fsync());
1416 check!(file.datasync());
1421 fn truncate_works() {
1422 let tmpdir = tmpdir();
1423 let path = tmpdir.join("in.txt");
1425 let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1426 check!(file.write(b"foo"));
1427 check!(file.fsync());
1429 // Do some simple things with truncation
1430 assert_eq!(check!(file.stat()).size, 3);
1431 check!(file.truncate(10));
1432 assert_eq!(check!(file.stat()).size, 10);
1433 check!(file.write(b"bar"));
1434 check!(file.fsync());
1435 assert_eq!(check!(file.stat()).size, 10);
1436 assert_eq!(check!(File::open(&path).read_to_end()),
1437 b"foobar\0\0\0\0".to_vec());
1439 // Truncate to a smaller length, don't seek, and then write something.
1440 // Ensure that the intermediate zeroes are all filled in (we're seeked
1441 // past the end of the file).
1442 check!(file.truncate(2));
1443 assert_eq!(check!(file.stat()).size, 2);
1444 check!(file.write(b"wut"));
1445 check!(file.fsync());
1446 assert_eq!(check!(file.stat()).size, 9);
1447 assert_eq!(check!(File::open(&path).read_to_end()),
1448 b"fo\0\0\0\0wut".to_vec());
1454 let tmpdir = tmpdir();
1456 match File::open_mode(&tmpdir.join("a"), io::Open, io::Read) {
1457 Ok(..) => panic!(), Err(..) => {}
1460 // Perform each one twice to make sure that it succeeds the second time
1461 // (where the file exists)
1462 check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1463 assert!(tmpdir.join("b").exists());
1464 check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1466 check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1467 assert!(tmpdir.join("c").exists());
1468 check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1470 check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1471 assert!(tmpdir.join("d").exists());
1472 check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1474 check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1475 assert!(tmpdir.join("e").exists());
1476 check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1478 check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1479 assert!(tmpdir.join("f").exists());
1480 check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1482 check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1483 assert!(tmpdir.join("g").exists());
1484 check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1486 check!(File::create(&tmpdir.join("h")).write("foo".as_bytes()));
1487 check!(File::open_mode(&tmpdir.join("h"), io::Open, io::Read));
1489 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Open,
1491 match f.write("wut".as_bytes()) {
1492 Ok(..) => panic!(), Err(..) => {}
1495 assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1496 "write/stat failed");
1498 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Append,
1500 check!(f.write("bar".as_bytes()));
1502 assert!(check!(stat(&tmpdir.join("h"))).size == 6,
1503 "append didn't append");
1505 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Truncate,
1507 check!(f.write("bar".as_bytes()));
1509 assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1510 "truncate didn't truncate");
1515 let tmpdir = tmpdir();
1516 let path = tmpdir.join("a");
1517 check!(File::create(&path));
1518 // These numbers have to be bigger than the time in the day to account for timezones
1519 // Windows in particular will fail in certain timezones with small enough values
1520 check!(change_file_times(&path, 100000, 200000));
1521 assert_eq!(check!(path.stat()).accessed, 100000);
1522 assert_eq!(check!(path.stat()).modified, 200000);
1526 fn utime_noexist() {
1527 let tmpdir = tmpdir();
1529 match change_file_times(&tmpdir.join("a"), 100, 200) {
1537 use rand::{StdRng, Rng};
1539 let mut bytes = [0, ..1024];
1540 StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
1542 let tmpdir = tmpdir();
1544 check!(File::create(&tmpdir.join("test")).write(&bytes));
1545 let actual = check!(File::open(&tmpdir.join("test")).read_to_end());
1546 assert!(actual == bytes.as_slice());
1550 fn unlink_readonly() {
1551 let tmpdir = tmpdir();
1552 let path = tmpdir.join("file");
1553 check!(File::create(&path));
1554 check!(chmod(&path, io::USER_READ));
1555 check!(unlink(&path));