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::{File, fs};
36 let path = Path::new("foo.txt");
38 // create the file, whether it exists or not
39 let mut file = File::create(&path);
40 file.write(b"foobar");
43 // open the file in read-only mode
44 let mut file = File::open(&path);
47 println!("{}", path.stat().unwrap().size);
56 use collections::Collection;
57 use io::standard_error;
58 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
59 use io::{IoResult, IoError, FileStat, SeekStyle, Seek, Writer, Reader};
60 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
61 use io::UpdateIoError;
66 use option::{Some, None, Option};
68 use path::{Path, GenericPath};
70 use result::{Err, Ok};
71 use rt::rtio::LocalIo;
73 use slice::ImmutableVector;
77 /// Unconstrained file access type that exposes read and write operations
79 /// Can be constructed via `File::open()`, `File::create()`, and
80 /// `File::open_mode()`.
84 /// This type will return errors as an `IoResult<T>` if operations are
85 /// attempted against it for which its underlying file descriptor was not
86 /// configured at creation time, via the `FileAccess` parameter to
87 /// `File::open_mode()`.
89 fd: Box<rtio::RtioFileStream + Send>,
95 /// Open a file at `path` in the mode specified by the `mode` and `access`
100 /// ```rust,should_fail
101 /// use std::io::{File, Open, ReadWrite};
103 /// let p = Path::new("/some/file/path.txt");
105 /// let file = match File::open_mode(&p, Open, ReadWrite) {
107 /// Err(e) => fail!("file error: {}", e),
109 /// // do some stuff with that file
111 /// // the file will be closed at the end of this block
114 /// `FileMode` and `FileAccess` provide information about the permissions
115 /// context in which a given stream is created. More information about them
116 /// can be found in `std::io`'s docs. If a file is opened with `Write`
117 /// or `ReadWrite` access, then it will be created it does not already
120 /// Note that, with this function, a `File` is returned regardless of the
121 /// access-limitations indicated by `FileAccess` (e.g. calling `write` on a
122 /// `File` opened as `Read` will return an error at runtime).
126 /// This function will return an error under a number of different
127 /// circumstances, to include but not limited to:
129 /// * Opening a file that does not exist with `Read` access.
130 /// * Attempting to open a file with a `FileAccess` that the user lacks
132 /// * Filesystem-level errors (full disk, etc)
133 pub fn open_mode(path: &Path,
135 access: FileAccess) -> IoResult<File> {
136 let rtio_mode = match mode {
138 Append => rtio::Append,
139 Truncate => rtio::Truncate,
141 let rtio_access = match access {
143 Write => rtio::Write,
144 ReadWrite => rtio::ReadWrite,
146 let err = LocalIo::maybe_raise(|io| {
147 io.fs_open(&path.to_c_str(), rtio_mode, rtio_access).map(|fd| {
154 }).map_err(IoError::from_rtio_error);
155 err.update_err("couldn't open file", |e| {
156 format!("{}; path={}; mode={}; access={}", e, path.display(),
157 mode_string(mode), access_string(access))
161 /// Attempts to open a file in read-only mode. This function is equivalent to
162 /// `File::open_mode(path, Open, Read)`, and will raise all of the same
163 /// errors that `File::open_mode` does.
165 /// For more information, see the `File::open_mode` function.
170 /// use std::io::File;
172 /// let contents = File::open(&Path::new("foo.txt")).read_to_end();
174 pub fn open(path: &Path) -> IoResult<File> {
175 File::open_mode(path, Open, Read)
178 /// Attempts to create a file in write-only mode. This function is
179 /// equivalent to `File::open_mode(path, Truncate, Write)`, and will
180 /// raise all of the same errors that `File::open_mode` does.
182 /// For more information, see the `File::open_mode` function.
187 /// # #![allow(unused_must_use)]
188 /// use std::io::File;
190 /// let mut f = File::create(&Path::new("foo.txt"));
191 /// f.write(b"This is a sample file");
193 /// # ::std::io::fs::unlink(&Path::new("foo.txt"));
195 pub fn create(path: &Path) -> IoResult<File> {
196 File::open_mode(path, Truncate, Write)
197 .update_desc("couldn't create file")
200 /// Returns the original path which was used to open this file.
201 pub fn path<'a>(&'a self) -> &'a Path {
205 /// Synchronizes all modifications to this file to its permanent storage
206 /// device. This will flush any internal buffers necessary to perform this
208 pub fn fsync(&mut self) -> IoResult<()> {
209 let err = self.fd.fsync().map_err(IoError::from_rtio_error);
210 err.update_err("couldn't fsync file",
211 |e| format!("{}; path={}", e, self.path.display()))
214 /// This function is similar to `fsync`, except that it may not synchronize
215 /// file metadata to the filesystem. This is intended for use case which
216 /// must synchronize content, but don't need the metadata on disk. The goal
217 /// of this method is to reduce disk operations.
218 pub fn datasync(&mut self) -> IoResult<()> {
219 let err = self.fd.datasync().map_err(IoError::from_rtio_error);
220 err.update_err("couldn't datasync file",
221 |e| format!("{}; path={}", e, self.path.display()))
224 /// Either truncates or extends the underlying file, updating the size of
225 /// this file to become `size`. This is equivalent to unix's `truncate`
228 /// If the `size` is less than the current file's size, then the file will
229 /// be shrunk. If it is greater than the current file's size, then the file
230 /// will be extended to `size` and have all of the intermediate data filled
232 pub fn truncate(&mut self, size: i64) -> IoResult<()> {
233 let err = self.fd.truncate(size).map_err(IoError::from_rtio_error);
234 err.update_err("couldn't truncate file", |e| {
235 format!("{}; path={}; size={}", e, self.path.display(), size)
239 /// Tests whether this stream has reached EOF.
241 /// If true, then this file will no longer continue to return data via
243 pub fn eof(&self) -> bool {
247 /// Queries information about the underlying file.
248 pub fn stat(&mut self) -> IoResult<FileStat> {
249 let err = match self.fd.fstat() {
250 Ok(s) => Ok(from_rtio(s)),
251 Err(e) => Err(IoError::from_rtio_error(e)),
253 err.update_err("couldn't fstat file",
254 |e| format!("{}; path={}", e, self.path.display()))
258 /// Unlink a file from the underlying filesystem.
263 /// # #![allow(unused_must_use)]
266 /// let p = Path::new("/some/file/path.txt");
270 /// Note that, just because an unlink call was successful, it is not
271 /// guaranteed that a file is immediately deleted (e.g. depending on
272 /// platform, other open file descriptors may prevent immediate removal)
276 /// This function will return an error if the path points to a directory, the
277 /// user lacks permissions to remove the file, or if some other filesystem-level
279 pub fn unlink(path: &Path) -> IoResult<()> {
280 return match do_unlink(path) {
283 // On unix, a readonly file can be successfully removed. On windows,
284 // however, it cannot. To keep the two platforms in line with
285 // respect to their behavior, catch this case on windows, attempt to
286 // change it to read-write, and then remove the file.
287 if cfg!(windows) && e.kind == io::PermissionDenied {
288 let stat = match stat(path) {
290 Err(..) => return Err(e),
292 if stat.perm.intersects(io::UserWrite) { return Err(e) }
294 match chmod(path, stat.perm | io::UserWrite) {
295 Ok(()) => do_unlink(path),
297 // Try to put it back as we found it
298 let _ = chmod(path, stat.perm);
308 fn do_unlink(path: &Path) -> IoResult<()> {
309 let err = LocalIo::maybe_raise(|io| {
310 io.fs_unlink(&path.to_c_str())
311 }).map_err(IoError::from_rtio_error);
312 err.update_err("couldn't unlink path",
313 |e| format!("{}; path={}", e, path.display()))
317 /// Given a path, query the file system to get information about a file,
318 /// directory, etc. This function will traverse symlinks to query
319 /// information about the destination file.
326 /// let p = Path::new("/some/file/path.txt");
327 /// match fs::stat(&p) {
328 /// Ok(stat) => { /* ... */ }
329 /// Err(e) => { /* handle error */ }
335 /// This call will return an error if the user lacks the requisite permissions
336 /// to perform a `stat` call on the given path or if there is no entry in the
337 /// filesystem at the provided path.
338 pub fn stat(path: &Path) -> IoResult<FileStat> {
339 let err = match LocalIo::maybe_raise(|io| io.fs_stat(&path.to_c_str())) {
340 Ok(s) => Ok(from_rtio(s)),
341 Err(e) => Err(IoError::from_rtio_error(e)),
343 err.update_err("couldn't stat path",
344 |e| format!("{}; path={}", e, path.display()))
347 /// Perform the same operation as the `stat` function, except that this
348 /// function does not traverse through symlinks. This will return
349 /// information about the symlink file instead of the file that it points
355 pub fn lstat(path: &Path) -> IoResult<FileStat> {
356 let err = match LocalIo::maybe_raise(|io| io.fs_lstat(&path.to_c_str())) {
357 Ok(s) => Ok(from_rtio(s)),
358 Err(e) => Err(IoError::from_rtio_error(e)),
360 err.update_err("couldn't lstat path",
361 |e| format!("{}; path={}", e, path.display()))
364 fn from_rtio(s: rtio::FileStat) -> FileStat {
366 type Mode = libc::c_int;
368 type Mode = libc::mode_t;
371 size, kind, perm, created, modified,
372 accessed, device, inode, rdev,
373 nlink, uid, gid, blksize, blocks, flags, gen
378 kind: match (kind as Mode) & libc::S_IFMT {
379 libc::S_IFREG => io::TypeFile,
380 libc::S_IFDIR => io::TypeDirectory,
381 libc::S_IFIFO => io::TypeNamedPipe,
382 libc::S_IFBLK => io::TypeBlockSpecial,
383 libc::S_IFLNK => io::TypeSymlink,
384 _ => io::TypeUnknown,
386 perm: FilePermission::from_bits_truncate(perm as u32),
390 unstable: UnstableFileStat {
405 /// Rename a file or directory to a new name.
410 /// # #![allow(unused_must_use)]
413 /// fs::rename(&Path::new("foo"), &Path::new("bar"));
418 /// Will return an error if the provided `path` doesn't exist, the process lacks
419 /// permissions to view the contents, or if some other intermittent I/O error
421 pub fn rename(from: &Path, to: &Path) -> IoResult<()> {
422 let err = LocalIo::maybe_raise(|io| {
423 io.fs_rename(&from.to_c_str(), &to.to_c_str())
424 }).map_err(IoError::from_rtio_error);
425 err.update_err("couldn't rename path", |e| {
426 format!("{}; from={}; to={}", e, from.display(), to.display())
430 /// Copies the contents of one file to another. This function will also
431 /// copy the permission bits of the original file to the destination file.
433 /// Note that if `from` and `to` both point to the same file, then the file
434 /// will likely get truncated by this operation.
439 /// # #![allow(unused_must_use)]
442 /// fs::copy(&Path::new("foo.txt"), &Path::new("bar.txt"));
447 /// Will return an error in the following situations, but is not limited to
448 /// just these cases:
450 /// * The `from` path is not a file
451 /// * The `from` file does not exist
452 /// * The current process does not have the permission rights to access
453 /// `from` or write `to`
455 /// Note that this copy is not atomic in that once the destination is
456 /// ensured to not exist, there is nothing preventing the destination from
457 /// being created and then destroyed by this operation.
458 pub fn copy(from: &Path, to: &Path) -> IoResult<()> {
459 fn update_err<T>(result: IoResult<T>, from: &Path, to: &Path) -> IoResult<T> {
460 result.update_err("couldn't copy path",
461 |e| format!("{}; from={}; to={}", e, from.display(), to.display()))
465 return update_err(Err(IoError {
466 kind: io::MismatchedFileTypeForOperation,
467 desc: "the source path is not an existing file",
472 let mut reader = try!(File::open(from));
473 let mut writer = try!(File::create(to));
474 let mut buf = [0, ..io::DEFAULT_BUF_SIZE];
477 let amt = match reader.read(buf) {
479 Err(ref e) if e.kind == io::EndOfFile => { break }
480 Err(e) => return update_err(Err(e), from, to)
482 try!(writer.write(buf.slice_to(amt)));
485 chmod(to, try!(update_err(from.stat(), from, to)).perm)
488 /// Changes the permission mode bits found on a file or a directory. This
489 /// function takes a mask from the `io` module
494 /// # #![allow(unused_must_use)]
498 /// fs::chmod(&Path::new("file.txt"), io::UserFile);
499 /// fs::chmod(&Path::new("file.txt"), io::UserRead | io::UserWrite);
500 /// fs::chmod(&Path::new("dir"), io::UserDir);
501 /// fs::chmod(&Path::new("file.exe"), io::UserExec);
506 /// If this function encounters an I/O error, it will return an `Err` value.
507 /// Some possible error situations are not having the permission to
508 /// change the attributes of a file or the file not existing.
509 pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> {
510 let err = LocalIo::maybe_raise(|io| {
511 io.fs_chmod(&path.to_c_str(), mode.bits() as uint)
512 }).map_err(IoError::from_rtio_error);
513 err.update_err("couldn't chmod path", |e| {
514 format!("{}; path={}; mode={}", e, path.display(), mode)
518 /// Change the user and group owners of a file at the specified path.
519 pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> {
520 let err = LocalIo::maybe_raise(|io| {
521 io.fs_chown(&path.to_c_str(), uid, gid)
522 }).map_err(IoError::from_rtio_error);
523 err.update_err("couldn't chown path", |e| {
524 format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid)
528 /// Creates a new hard link on the filesystem. The `dst` path will be a
529 /// link pointing to the `src` path. Note that systems often require these
530 /// two paths to both be located on the same filesystem.
531 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
532 let err = LocalIo::maybe_raise(|io| {
533 io.fs_link(&src.to_c_str(), &dst.to_c_str())
534 }).map_err(IoError::from_rtio_error);
535 err.update_err("couldn't link path", |e| {
536 format!("{}; src={}; dest={}", e, src.display(), dst.display())
540 /// Creates a new symbolic link on the filesystem. The `dst` path will be a
541 /// symlink pointing to the `src` path.
542 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
543 let err = LocalIo::maybe_raise(|io| {
544 io.fs_symlink(&src.to_c_str(), &dst.to_c_str())
545 }).map_err(IoError::from_rtio_error);
546 err.update_err("couldn't symlink path", |e| {
547 format!("{}; src={}; dest={}", e, src.display(), dst.display())
551 /// Reads a symlink, returning the file that the symlink points to.
555 /// This function will return an error on failure. Failure conditions include
556 /// reading a file that does not exist or reading a file which is not a symlink.
557 pub fn readlink(path: &Path) -> IoResult<Path> {
558 let err = LocalIo::maybe_raise(|io| {
559 Ok(Path::new(try!(io.fs_readlink(&path.to_c_str()))))
560 }).map_err(IoError::from_rtio_error);
561 err.update_err("couldn't resolve symlink for path",
562 |e| format!("{}; path={}", e, path.display()))
565 /// Create a new, empty directory at the provided path
570 /// # #![allow(unused_must_use)]
574 /// let p = Path::new("/some/dir");
575 /// fs::mkdir(&p, io::UserRWX);
580 /// This call will return an error if the user lacks permissions to make a new
581 /// directory at the provided path, or if the directory already exists.
582 pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> {
583 let err = LocalIo::maybe_raise(|io| {
584 io.fs_mkdir(&path.to_c_str(), mode.bits() as uint)
585 }).map_err(IoError::from_rtio_error);
586 err.update_err("couldn't create directory", |e| {
587 format!("{}; path={}; mode={}", e, path.display(), mode)
591 /// Remove an existing, empty directory
596 /// # #![allow(unused_must_use)]
599 /// let p = Path::new("/some/dir");
605 /// This call will return an error if the user lacks permissions to remove the
606 /// directory at the provided path, or if the directory isn't empty.
607 pub fn rmdir(path: &Path) -> IoResult<()> {
608 let err = LocalIo::maybe_raise(|io| {
609 io.fs_rmdir(&path.to_c_str())
610 }).map_err(IoError::from_rtio_error);
611 err.update_err("couldn't remove directory",
612 |e| format!("{}; path={}", e, path.display()))
615 /// Retrieve a vector containing all entries within a provided directory
623 /// // one possible implementation of fs::walk_dir only visiting files
624 /// fn visit_dirs(dir: &Path, cb: |&Path|) -> io::IoResult<()> {
625 /// if dir.is_dir() {
626 /// let contents = try!(fs::readdir(dir));
627 /// for entry in contents.iter() {
628 /// if entry.is_dir() {
629 /// try!(visit_dirs(entry, |p| cb(p)));
636 /// Err(io::standard_error(io::InvalidInput))
643 /// Will return an error if the provided `from` doesn't exist, the process lacks
644 /// permissions to view the contents or if the `path` points at a non-directory
646 pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
647 let err = LocalIo::maybe_raise(|io| {
648 Ok(try!(io.fs_readdir(&path.to_c_str(), 0)).move_iter().map(|a| {
651 }).map_err(IoError::from_rtio_error);
652 err.update_err("couldn't read directory",
653 |e| format!("{}; path={}", e, path.display()))
656 /// Returns an iterator which will recursively walk the directory structure
657 /// rooted at `path`. The path given will not be iterated over, and this will
658 /// perform iteration in some top-down order. The contents of unreadable
659 /// subdirectories are ignored.
660 pub fn walk_dir(path: &Path) -> IoResult<Directories> {
662 stack: try!(readdir(path).update_err("couldn't walk directory",
663 |e| format!("{}; path={}",
668 /// An iterator which walks over a directory
669 pub struct Directories {
673 impl Iterator<Path> for Directories {
674 fn next(&mut self) -> Option<Path> {
675 match self.stack.pop() {
678 let result = readdir(&path)
679 .update_err("couldn't advance Directories iterator",
680 |e| format!("{}; path={}",
684 Ok(dirs) => { self.stack.push_all_move(dirs); }
695 /// Recursively create a directory and all of its parent components if they
700 /// This function will return an `Err` value if an error happens, see
701 /// `fs::mkdir` for more information about error conditions and performance.
702 pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> {
703 // tjc: if directory exists but with different permissions,
704 // should we return false?
709 let mut comps = path.components();
710 let mut curpath = path.root_path().unwrap_or(Path::new("."));
715 let result = mkdir(&curpath, mode)
716 .update_err("couldn't recursively mkdir",
717 |e| format!("{}; path={}", e, path.display()));
722 if try!(stat(&curpath)).kind != io::TypeDirectory {
723 return Err(mkdir_err);
733 /// Removes a directory at this path, after removing all its contents. Use
738 /// This function will return an `Err` value if an error happens. See
739 /// `file::unlink` and `fs::readdir` for possible error conditions.
740 pub fn rmdir_recursive(path: &Path) -> IoResult<()> {
741 let mut rm_stack = Vec::new();
742 rm_stack.push(path.clone());
744 fn rmdir_failed(err: &IoError, path: &Path) -> String {
745 format!("rmdir_recursive failed; path={}; cause={}",
749 fn update_err<T>(err: IoResult<T>, path: &Path) -> IoResult<T> {
750 err.update_err("couldn't recursively rmdir",
751 |e| rmdir_failed(e, path))
754 while !rm_stack.is_empty() {
755 let children = try!(readdir(rm_stack.last().unwrap())
756 .update_detail(|e| rmdir_failed(e, path)));
758 let mut has_child_dir = false;
760 // delete all regular files in the way and push subdirs
762 for child in children.move_iter() {
763 // FIXME(#12795) we should use lstat in all cases
764 let child_type = match cfg!(windows) {
765 true => try!(update_err(stat(&child), path)),
766 false => try!(update_err(lstat(&child), path))
769 if child_type.kind == io::TypeDirectory {
770 rm_stack.push(child);
771 has_child_dir = true;
773 // we can carry on safely if the file is already gone
774 // (eg: deleted by someone else since readdir)
775 match update_err(unlink(&child), path) {
777 Err(ref e) if e.kind == io::FileNotFound => (),
778 Err(e) => return Err(e)
783 // if no subdir was found, let's pop and delete
785 let result = update_err(rmdir(&rm_stack.pop().unwrap()), path);
788 Err(ref e) if e.kind == io::FileNotFound => (),
789 Err(e) => return Err(e)
797 /// Changes the timestamps for a file's last modification and access time.
798 /// The file at the path specified will have its last access time set to
799 /// `atime` and its modification time set to `mtime`. The times specified should
800 /// be in milliseconds.
801 // FIXME(#10301) these arguments should not be u64
802 pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> {
803 let err = LocalIo::maybe_raise(|io| {
804 io.fs_utime(&path.to_c_str(), atime, mtime)
805 }).map_err(IoError::from_rtio_error);
806 err.update_err("couldn't change_file_times",
807 |e| format!("{}; path={}", e, path.display()))
810 impl Reader for File {
811 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
812 fn update_err<T>(result: IoResult<T>, file: &File) -> IoResult<T> {
813 result.update_err("couldn't read file",
814 |e| format!("{}; path={}",
815 e, file.path.display()))
818 let result = update_err(self.fd.read(buf)
819 .map_err(IoError::from_rtio_error), self);
823 self.last_nread = read;
825 0 => update_err(Err(standard_error(io::EndOfFile)), self),
826 _ => Ok(read as uint)
834 impl Writer for File {
835 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
836 let err = self.fd.write(buf).map_err(IoError::from_rtio_error);
837 err.update_err("couldn't write to file",
838 |e| format!("{}; path={}", e, self.path.display()))
843 fn tell(&self) -> IoResult<u64> {
844 let err = self.fd.tell().map_err(IoError::from_rtio_error);
845 err.update_err("couldn't retrieve file cursor (`tell`)",
846 |e| format!("{}; path={}", e, self.path.display()))
849 fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> {
850 let style = match style {
851 SeekSet => rtio::SeekSet,
852 SeekCur => rtio::SeekCur,
853 SeekEnd => rtio::SeekEnd,
855 let err = match self.fd.seek(pos, style) {
857 // successful seek resets EOF indicator
858 self.last_nread = -1;
861 Err(e) => Err(IoError::from_rtio_error(e)),
863 err.update_err("couldn't seek in file",
864 |e| format!("{}; path={}", e, self.path.display()))
869 /// Get information on the file, directory, etc at this path.
871 /// Consult the `fs::stat` documentation for more info.
873 /// This call preserves identical runtime/error semantics with `file::stat`.
874 pub fn stat(&self) -> IoResult<FileStat> { stat(self) }
876 /// Get information on the file, directory, etc at this path, not following
879 /// Consult the `fs::lstat` documentation for more info.
881 /// This call preserves identical runtime/error semantics with `file::lstat`.
882 pub fn lstat(&self) -> IoResult<FileStat> { lstat(self) }
884 /// Boolean value indicator whether the underlying file exists on the local
885 /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
886 pub fn exists(&self) -> bool {
890 /// Whether the underlying implementation (be it a file path, or something
891 /// else) points at a "regular file" on the FS. Will return false for paths
892 /// to non-existent locations or directories or other non-regular files
893 /// (named pipes, etc). Follows links when making this determination.
894 pub fn is_file(&self) -> bool {
896 Ok(s) => s.kind == io::TypeFile,
901 /// Whether the underlying implementation (be it a file path, or something
902 /// else) is pointing at a directory in the underlying FS. Will return
903 /// false for paths to non-existent locations or if the item is not a
904 /// directory (eg files, named pipes, etc). Follows links when making this
906 pub fn is_dir(&self) -> bool {
908 Ok(s) => s.kind == io::TypeDirectory,
914 fn mode_string(mode: FileMode) -> &'static str {
916 super::Open => "open",
917 super::Append => "append",
918 super::Truncate => "truncate"
922 fn access_string(access: FileAccess) -> &'static str {
924 super::Read => "read",
925 super::Write => "write",
926 super::ReadWrite => "readwrite"
931 #[allow(unused_imports)]
934 use io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite};
937 use io::fs::{File, rmdir, mkdir, readdir, rmdir_recursive,
938 mkdir_recursive, copy, unlink, stat, symlink, link,
939 readlink, chmod, lstat, change_file_times};
945 macro_rules! check( ($e:expr) => (
948 Err(e) => fail!("{} failed with: {}", stringify!($e), e),
952 macro_rules! error( ($e:expr, $s:expr) => (
954 Ok(val) => fail!("Should have been an error, was {:?}", val),
955 Err(ref err) => assert!(err.to_string().as_slice().contains($s.as_slice()),
956 format!("`{}` did not contain `{}`", err, $s))
960 struct TempDir(Path);
963 fn join(&self, path: &str) -> Path {
964 let TempDir(ref p) = *self;
968 fn path<'a>(&'a self) -> &'a Path {
969 let TempDir(ref p) = *self;
974 impl Drop for TempDir {
976 // Gee, seeing how we're testing the fs module I sure hope that we
977 // at least implement this correctly!
978 let TempDir(ref p) = *self;
979 check!(io::fs::rmdir_recursive(p));
983 pub fn tmpdir() -> TempDir {
986 let ret = os::tmpdir().join(format!("rust-{}", rand::random::<u32>()));
987 check!(io::fs::mkdir(&ret, io::UserRWX));
991 iotest!(fn file_test_io_smoke_test() {
992 let message = "it's alright. have a good time";
993 let tmpdir = tmpdir();
994 let filename = &tmpdir.join("file_rt_io_file_test.txt");
996 let mut write_stream = File::open_mode(filename, Open, ReadWrite);
997 check!(write_stream.write(message.as_bytes()));
1000 let mut read_stream = File::open_mode(filename, Open, Read);
1001 let mut read_buf = [0, .. 1028];
1002 let read_str = match check!(read_stream.read(read_buf)) {
1003 -1|0 => fail!("shouldn't happen"),
1004 n => str::from_utf8(read_buf.slice_to(n)).unwrap().to_string()
1006 assert_eq!(read_str.as_slice(), message);
1008 check!(unlink(filename));
1011 iotest!(fn invalid_path_raises() {
1012 let tmpdir = tmpdir();
1013 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1014 let result = File::open_mode(filename, Open, Read);
1016 error!(result, "couldn't open file");
1018 error!(result, "no such file or directory");
1020 error!(result, format!("path={}; mode=open; access=read", filename.display()));
1023 iotest!(fn file_test_iounlinking_invalid_path_should_raise_condition() {
1024 let tmpdir = tmpdir();
1025 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1027 let result = unlink(filename);
1029 error!(result, "couldn't unlink path");
1031 error!(result, "no such file or directory");
1033 error!(result, format!("path={}", filename.display()));
1036 iotest!(fn file_test_io_non_positional_read() {
1037 let message: &str = "ten-four";
1038 let mut read_mem = [0, .. 8];
1039 let tmpdir = tmpdir();
1040 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1042 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1043 check!(rw_stream.write(message.as_bytes()));
1046 let mut read_stream = File::open_mode(filename, Open, Read);
1048 let read_buf = read_mem.mut_slice(0, 4);
1049 check!(read_stream.read(read_buf));
1052 let read_buf = read_mem.mut_slice(4, 8);
1053 check!(read_stream.read(read_buf));
1056 check!(unlink(filename));
1057 let read_str = str::from_utf8(read_mem).unwrap();
1058 assert_eq!(read_str, message);
1061 iotest!(fn file_test_io_seek_and_tell_smoke_test() {
1062 let message = "ten-four";
1063 let mut read_mem = [0, .. 4];
1064 let set_cursor = 4 as u64;
1065 let mut tell_pos_pre_read;
1066 let mut tell_pos_post_read;
1067 let tmpdir = tmpdir();
1068 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1070 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1071 check!(rw_stream.write(message.as_bytes()));
1074 let mut read_stream = File::open_mode(filename, Open, Read);
1075 check!(read_stream.seek(set_cursor as i64, SeekSet));
1076 tell_pos_pre_read = check!(read_stream.tell());
1077 check!(read_stream.read(read_mem));
1078 tell_pos_post_read = check!(read_stream.tell());
1080 check!(unlink(filename));
1081 let read_str = str::from_utf8(read_mem).unwrap();
1082 assert_eq!(read_str, message.slice(4, 8));
1083 assert_eq!(tell_pos_pre_read, set_cursor);
1084 assert_eq!(tell_pos_post_read, message.len() as u64);
1087 iotest!(fn file_test_io_seek_and_write() {
1088 let initial_msg = "food-is-yummy";
1089 let overwrite_msg = "-the-bar!!";
1090 let final_msg = "foo-the-bar!!";
1092 let mut read_mem = [0, .. 13];
1093 let tmpdir = tmpdir();
1094 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1096 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1097 check!(rw_stream.write(initial_msg.as_bytes()));
1098 check!(rw_stream.seek(seek_idx as i64, SeekSet));
1099 check!(rw_stream.write(overwrite_msg.as_bytes()));
1102 let mut read_stream = File::open_mode(filename, Open, Read);
1103 check!(read_stream.read(read_mem));
1105 check!(unlink(filename));
1106 let read_str = str::from_utf8(read_mem).unwrap();
1107 assert!(read_str.as_slice() == final_msg.as_slice());
1110 iotest!(fn file_test_io_seek_shakedown() {
1111 use str; // 01234567890123
1112 let initial_msg = "qwer-asdf-zxcv";
1113 let chunk_one: &str = "qwer";
1114 let chunk_two: &str = "asdf";
1115 let chunk_three: &str = "zxcv";
1116 let mut read_mem = [0, .. 4];
1117 let tmpdir = tmpdir();
1118 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1120 let mut rw_stream = File::open_mode(filename, Open, ReadWrite);
1121 check!(rw_stream.write(initial_msg.as_bytes()));
1124 let mut read_stream = File::open_mode(filename, Open, Read);
1126 check!(read_stream.seek(-4, SeekEnd));
1127 check!(read_stream.read(read_mem));
1128 assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_three);
1130 check!(read_stream.seek(-9, SeekCur));
1131 check!(read_stream.read(read_mem));
1132 assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_two);
1134 check!(read_stream.seek(0, SeekSet));
1135 check!(read_stream.read(read_mem));
1136 assert_eq!(str::from_utf8(read_mem).unwrap(), chunk_one);
1138 check!(unlink(filename));
1141 iotest!(fn file_test_stat_is_correct_on_is_file() {
1142 let tmpdir = tmpdir();
1143 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1145 let mut fs = check!(File::open_mode(filename, Open, ReadWrite));
1147 fs.write(msg.as_bytes()).unwrap();
1149 let fstat_res = check!(fs.stat());
1150 assert_eq!(fstat_res.kind, io::TypeFile);
1152 let stat_res_fn = check!(stat(filename));
1153 assert_eq!(stat_res_fn.kind, io::TypeFile);
1154 let stat_res_meth = check!(filename.stat());
1155 assert_eq!(stat_res_meth.kind, io::TypeFile);
1156 check!(unlink(filename));
1159 iotest!(fn file_test_stat_is_correct_on_is_dir() {
1160 let tmpdir = tmpdir();
1161 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1162 check!(mkdir(filename, io::UserRWX));
1163 let stat_res_fn = check!(stat(filename));
1164 assert!(stat_res_fn.kind == io::TypeDirectory);
1165 let stat_res_meth = check!(filename.stat());
1166 assert!(stat_res_meth.kind == io::TypeDirectory);
1167 check!(rmdir(filename));
1170 iotest!(fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1171 let tmpdir = tmpdir();
1172 let dir = &tmpdir.join("fileinfo_false_on_dir");
1173 check!(mkdir(dir, io::UserRWX));
1174 assert!(dir.is_file() == false);
1178 iotest!(fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1179 let tmpdir = tmpdir();
1180 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1181 check!(File::create(file).write(b"foo"));
1182 assert!(file.exists());
1183 check!(unlink(file));
1184 assert!(!file.exists());
1187 iotest!(fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1188 let tmpdir = tmpdir();
1189 let dir = &tmpdir.join("before_and_after_dir");
1190 assert!(!dir.exists());
1191 check!(mkdir(dir, io::UserRWX));
1192 assert!(dir.exists());
1193 assert!(dir.is_dir());
1195 assert!(!dir.exists());
1198 iotest!(fn file_test_directoryinfo_readdir() {
1200 let tmpdir = tmpdir();
1201 let dir = &tmpdir.join("di_readdir");
1202 check!(mkdir(dir, io::UserRWX));
1204 for n in range(0i,3) {
1205 let f = dir.join(format!("{}.txt", n));
1206 let mut w = check!(File::create(&f));
1207 let msg_str = format!("{}{}", prefix, n.to_string());
1208 let msg = msg_str.as_slice().as_bytes();
1209 check!(w.write(msg));
1211 let files = check!(readdir(dir));
1212 let mut mem = [0u8, .. 4];
1213 for f in files.iter() {
1215 let n = f.filestem_str();
1216 check!(File::open(f).read(mem));
1217 let read_str = str::from_utf8(mem).unwrap();
1218 let expected = match n {
1219 None|Some("") => fail!("really shouldn't happen.."),
1220 Some(n) => format!("{}{}", prefix, n),
1222 assert_eq!(expected.as_slice(), read_str);
1229 iotest!(fn file_test_walk_dir() {
1230 let tmpdir = tmpdir();
1231 let dir = &tmpdir.join("walk_dir");
1232 check!(mkdir(dir, io::UserRWX));
1234 let dir1 = &dir.join("01/02/03");
1235 check!(mkdir_recursive(dir1, io::UserRWX));
1236 check!(File::create(&dir1.join("04")));
1238 let dir2 = &dir.join("11/12/13");
1239 check!(mkdir_recursive(dir2, io::UserRWX));
1240 check!(File::create(&dir2.join("14")));
1242 let mut files = check!(walk_dir(dir));
1243 let mut cur = [0u8, .. 2];
1245 let stem = f.filestem_str().unwrap();
1246 let root = stem.as_bytes()[0] - ('0' as u8);
1247 let name = stem.as_bytes()[1] - ('0' as u8);
1248 assert!(cur[root as uint] < name);
1249 cur[root as uint] = name;
1252 check!(rmdir_recursive(dir));
1255 iotest!(fn recursive_mkdir() {
1256 let tmpdir = tmpdir();
1257 let dir = tmpdir.join("d1/d2");
1258 check!(mkdir_recursive(&dir, io::UserRWX));
1259 assert!(dir.is_dir())
1262 iotest!(fn recursive_mkdir_failure() {
1263 let tmpdir = tmpdir();
1264 let dir = tmpdir.join("d1");
1265 let file = dir.join("f1");
1267 check!(mkdir_recursive(&dir, io::UserRWX));
1268 check!(File::create(&file));
1270 let result = mkdir_recursive(&file, io::UserRWX);
1272 error!(result, "couldn't recursively mkdir");
1273 error!(result, "couldn't create directory");
1274 error!(result, "mode=FilePermission { bits: 448 }");
1275 error!(result, format!("path={}", file.display()));
1278 iotest!(fn recursive_mkdir_slash() {
1279 check!(mkdir_recursive(&Path::new("/"), io::UserRWX));
1282 // FIXME(#12795) depends on lstat to work on windows
1283 #[cfg(not(windows))]
1284 iotest!(fn recursive_rmdir() {
1285 let tmpdir = tmpdir();
1286 let d1 = tmpdir.join("d1");
1287 let dt = d1.join("t");
1288 let dtt = dt.join("t");
1289 let d2 = tmpdir.join("d2");
1290 let canary = d2.join("do_not_delete");
1291 check!(mkdir_recursive(&dtt, io::UserRWX));
1292 check!(mkdir_recursive(&d2, io::UserRWX));
1293 check!(File::create(&canary).write(b"foo"));
1294 check!(symlink(&d2, &dt.join("d2")));
1295 check!(rmdir_recursive(&d1));
1297 assert!(!d1.is_dir());
1298 assert!(canary.exists());
1301 iotest!(fn unicode_path_is_dir() {
1302 assert!(Path::new(".").is_dir());
1303 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
1305 let tmpdir = tmpdir();
1307 let mut dirpath = tmpdir.path().clone();
1308 dirpath.push(format!("test-가一ー你好"));
1309 check!(mkdir(&dirpath, io::UserRWX));
1310 assert!(dirpath.is_dir());
1312 let mut filepath = dirpath;
1313 filepath.push("unicode-file-\uac00\u4e00\u30fc\u4f60\u597d.rs");
1314 check!(File::create(&filepath)); // ignore return; touch only
1315 assert!(!filepath.is_dir());
1316 assert!(filepath.exists());
1319 iotest!(fn unicode_path_exists() {
1320 assert!(Path::new(".").exists());
1321 assert!(!Path::new("test/nonexistent-bogus-path").exists());
1323 let tmpdir = tmpdir();
1324 let unicode = tmpdir.path();
1325 let unicode = unicode.join(format!("test-각丁ー再见"));
1326 check!(mkdir(&unicode, io::UserRWX));
1327 assert!(unicode.exists());
1328 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
1331 iotest!(fn copy_file_does_not_exist() {
1332 let from = Path::new("test/nonexistent-bogus-path");
1333 let to = Path::new("test/other-bogus-path");
1335 error!(copy(&from, &to),
1336 format!("couldn't copy path (the source path is not an \
1337 existing file; from={}; to={})",
1338 from.display(), to.display()));
1340 match copy(&from, &to) {
1343 assert!(!from.exists());
1344 assert!(!to.exists());
1349 iotest!(fn copy_file_ok() {
1350 let tmpdir = tmpdir();
1351 let input = tmpdir.join("in.txt");
1352 let out = tmpdir.join("out.txt");
1354 check!(File::create(&input).write(b"hello"));
1355 check!(copy(&input, &out));
1356 let contents = check!(File::open(&out).read_to_end());
1357 assert_eq!(contents.as_slice(), b"hello");
1359 assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
1362 iotest!(fn copy_file_dst_dir() {
1363 let tmpdir = tmpdir();
1364 let out = tmpdir.join("out");
1366 check!(File::create(&out));
1367 match copy(&out, tmpdir.path()) {
1368 Ok(..) => fail!(), Err(..) => {}
1372 iotest!(fn copy_file_dst_exists() {
1373 let tmpdir = tmpdir();
1374 let input = tmpdir.join("in");
1375 let output = tmpdir.join("out");
1377 check!(File::create(&input).write("foo".as_bytes()));
1378 check!(File::create(&output).write("bar".as_bytes()));
1379 check!(copy(&input, &output));
1381 assert_eq!(check!(File::open(&output).read_to_end()),
1382 (Vec::from_slice(b"foo")));
1385 iotest!(fn copy_file_src_dir() {
1386 let tmpdir = tmpdir();
1387 let out = tmpdir.join("out");
1389 match copy(tmpdir.path(), &out) {
1390 Ok(..) => fail!(), Err(..) => {}
1392 assert!(!out.exists());
1395 iotest!(fn copy_file_preserves_perm_bits() {
1396 let tmpdir = tmpdir();
1397 let input = tmpdir.join("in.txt");
1398 let out = tmpdir.join("out.txt");
1400 check!(File::create(&input));
1401 check!(chmod(&input, io::UserRead));
1402 check!(copy(&input, &out));
1403 assert!(!check!(out.stat()).perm.intersects(io::UserWrite));
1405 check!(chmod(&input, io::UserFile));
1406 check!(chmod(&out, io::UserFile));
1409 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1410 iotest!(fn symlinks_work() {
1411 let tmpdir = tmpdir();
1412 let input = tmpdir.join("in.txt");
1413 let out = tmpdir.join("out.txt");
1415 check!(File::create(&input).write("foobar".as_bytes()));
1416 check!(symlink(&input, &out));
1417 if cfg!(not(windows)) {
1418 assert_eq!(check!(lstat(&out)).kind, io::TypeSymlink);
1419 assert_eq!(check!(out.lstat()).kind, io::TypeSymlink);
1421 assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1422 assert_eq!(check!(File::open(&out).read_to_end()),
1423 (Vec::from_slice(b"foobar")));
1426 #[cfg(not(windows))] // apparently windows doesn't like symlinks
1427 iotest!(fn symlink_noexist() {
1428 let tmpdir = tmpdir();
1429 // symlinks can point to things that don't exist
1430 check!(symlink(&tmpdir.join("foo"), &tmpdir.join("bar")));
1431 assert!(check!(readlink(&tmpdir.join("bar"))) == tmpdir.join("foo"));
1434 iotest!(fn readlink_not_symlink() {
1435 let tmpdir = tmpdir();
1436 match readlink(tmpdir.path()) {
1437 Ok(..) => fail!("wanted a failure"),
1442 iotest!(fn links_work() {
1443 let tmpdir = tmpdir();
1444 let input = tmpdir.join("in.txt");
1445 let out = tmpdir.join("out.txt");
1447 check!(File::create(&input).write("foobar".as_bytes()));
1448 check!(link(&input, &out));
1449 if cfg!(not(windows)) {
1450 assert_eq!(check!(lstat(&out)).kind, io::TypeFile);
1451 assert_eq!(check!(out.lstat()).kind, io::TypeFile);
1452 assert_eq!(check!(stat(&out)).unstable.nlink, 2);
1453 assert_eq!(check!(out.stat()).unstable.nlink, 2);
1455 assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
1456 assert_eq!(check!(stat(&out)).size, check!(input.stat()).size);
1457 assert_eq!(check!(File::open(&out).read_to_end()),
1458 (Vec::from_slice(b"foobar")));
1460 // can't link to yourself
1461 match link(&input, &input) {
1462 Ok(..) => fail!("wanted a failure"),
1465 // can't link to something that doesn't exist
1466 match link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1467 Ok(..) => fail!("wanted a failure"),
1472 iotest!(fn chmod_works() {
1473 let tmpdir = tmpdir();
1474 let file = tmpdir.join("in.txt");
1476 check!(File::create(&file));
1477 assert!(check!(stat(&file)).perm.contains(io::UserWrite));
1478 check!(chmod(&file, io::UserRead));
1479 assert!(!check!(stat(&file)).perm.contains(io::UserWrite));
1481 match chmod(&tmpdir.join("foo"), io::UserRWX) {
1482 Ok(..) => fail!("wanted a failure"),
1486 check!(chmod(&file, io::UserFile));
1489 iotest!(fn sync_doesnt_kill_anything() {
1490 let tmpdir = tmpdir();
1491 let path = tmpdir.join("in.txt");
1493 let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1494 check!(file.fsync());
1495 check!(file.datasync());
1496 check!(file.write(b"foo"));
1497 check!(file.fsync());
1498 check!(file.datasync());
1502 iotest!(fn truncate_works() {
1503 let tmpdir = tmpdir();
1504 let path = tmpdir.join("in.txt");
1506 let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
1507 check!(file.write(b"foo"));
1508 check!(file.fsync());
1510 // Do some simple things with truncation
1511 assert_eq!(check!(file.stat()).size, 3);
1512 check!(file.truncate(10));
1513 assert_eq!(check!(file.stat()).size, 10);
1514 check!(file.write(b"bar"));
1515 check!(file.fsync());
1516 assert_eq!(check!(file.stat()).size, 10);
1517 assert_eq!(check!(File::open(&path).read_to_end()),
1518 (Vec::from_slice(b"foobar\0\0\0\0")));
1520 // Truncate to a smaller length, don't seek, and then write something.
1521 // Ensure that the intermediate zeroes are all filled in (we're seeked
1522 // past the end of the file).
1523 check!(file.truncate(2));
1524 assert_eq!(check!(file.stat()).size, 2);
1525 check!(file.write(b"wut"));
1526 check!(file.fsync());
1527 assert_eq!(check!(file.stat()).size, 9);
1528 assert_eq!(check!(File::open(&path).read_to_end()),
1529 (Vec::from_slice(b"fo\0\0\0\0wut")));
1533 iotest!(fn open_flavors() {
1534 let tmpdir = tmpdir();
1536 match File::open_mode(&tmpdir.join("a"), io::Open, io::Read) {
1537 Ok(..) => fail!(), Err(..) => {}
1540 // Perform each one twice to make sure that it succeeds the second time
1541 // (where the file exists)
1542 check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1543 assert!(tmpdir.join("b").exists());
1544 check!(File::open_mode(&tmpdir.join("b"), io::Open, io::Write));
1546 check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1547 assert!(tmpdir.join("c").exists());
1548 check!(File::open_mode(&tmpdir.join("c"), io::Open, io::ReadWrite));
1550 check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1551 assert!(tmpdir.join("d").exists());
1552 check!(File::open_mode(&tmpdir.join("d"), io::Append, io::Write));
1554 check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1555 assert!(tmpdir.join("e").exists());
1556 check!(File::open_mode(&tmpdir.join("e"), io::Append, io::ReadWrite));
1558 check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1559 assert!(tmpdir.join("f").exists());
1560 check!(File::open_mode(&tmpdir.join("f"), io::Truncate, io::Write));
1562 check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1563 assert!(tmpdir.join("g").exists());
1564 check!(File::open_mode(&tmpdir.join("g"), io::Truncate, io::ReadWrite));
1566 check!(File::create(&tmpdir.join("h")).write("foo".as_bytes()));
1567 check!(File::open_mode(&tmpdir.join("h"), io::Open, io::Read));
1569 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Open,
1571 match f.write("wut".as_bytes()) {
1572 Ok(..) => fail!(), Err(..) => {}
1575 assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1576 "write/stat failed");
1578 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Append,
1580 check!(f.write("bar".as_bytes()));
1582 assert!(check!(stat(&tmpdir.join("h"))).size == 6,
1583 "append didn't append");
1585 let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Truncate,
1587 check!(f.write("bar".as_bytes()));
1589 assert!(check!(stat(&tmpdir.join("h"))).size == 3,
1590 "truncate didn't truncate");
1595 let tmpdir = tmpdir();
1596 let path = tmpdir.join("a");
1597 check!(File::create(&path));
1599 check!(change_file_times(&path, 1000, 2000));
1600 assert_eq!(check!(path.stat()).accessed, 1000);
1601 assert_eq!(check!(path.stat()).modified, 2000);
1605 fn utime_noexist() {
1606 let tmpdir = tmpdir();
1608 match change_file_times(&tmpdir.join("a"), 100, 200) {
1614 iotest!(fn binary_file() {
1615 use rand::{StdRng, Rng};
1617 let mut bytes = [0, ..1024];
1618 StdRng::new().ok().unwrap().fill_bytes(bytes);
1620 let tmpdir = tmpdir();
1622 check!(File::create(&tmpdir.join("test")).write(bytes));
1623 let actual = check!(File::open(&tmpdir.join("test")).read_to_end());
1624 assert!(actual.as_slice() == bytes);
1627 iotest!(fn unlink_readonly() {
1628 let tmpdir = tmpdir();
1629 let path = tmpdir.join("file");
1630 check!(File::create(&path));
1631 check!(chmod(&path, io::UserRead));
1632 check!(unlink(&path));