1 //! Filesystem manipulation operations.
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
8 #![stable(feature = "rust1", since = "1.0.0")]
11 use crate::ffi::OsString;
12 use crate::io::{self, SeekFrom, Seek, Read, Initializer, Write};
13 use crate::path::{Path, PathBuf};
14 use crate::sys::fs as fs_imp;
15 use crate::sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
16 use crate::time::SystemTime;
18 /// A reference to an open file on the filesystem.
20 /// An instance of a `File` can be read and/or written depending on what options
21 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
22 /// that the file contains internally.
24 /// Files are automatically closed when they go out of scope. Errors detected
25 /// on closing are ignored by the implementation of `Drop`. Use the method
26 /// [`sync_all`] if these errors must be manually handled.
30 /// Creates a new file and write bytes to it:
33 /// use std::fs::File;
34 /// use std::io::prelude::*;
36 /// fn main() -> std::io::Result<()> {
37 /// let mut file = File::create("foo.txt")?;
38 /// file.write_all(b"Hello, world!")?;
43 /// Read the contents of a file into a [`String`]:
46 /// use std::fs::File;
47 /// use std::io::prelude::*;
49 /// fn main() -> std::io::Result<()> {
50 /// let mut file = File::open("foo.txt")?;
51 /// let mut contents = String::new();
52 /// file.read_to_string(&mut contents)?;
53 /// assert_eq!(contents, "Hello, world!");
58 /// It can be more efficient to read the contents of a file with a buffered
59 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
62 /// use std::fs::File;
63 /// use std::io::BufReader;
64 /// use std::io::prelude::*;
66 /// fn main() -> std::io::Result<()> {
67 /// let file = File::open("foo.txt")?;
68 /// let mut buf_reader = BufReader::new(file);
69 /// let mut contents = String::new();
70 /// buf_reader.read_to_string(&mut contents)?;
71 /// assert_eq!(contents, "Hello, world!");
76 /// Note that, although read and write methods require a `&mut File`, because
77 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
78 /// still modify the file, either through methods that take `&File` or by
79 /// retrieving the underlying OS object and modifying the file that way.
80 /// Additionally, many operating systems allow concurrent modification of files
81 /// by different processes. Avoid assuming that holding a `&File` means that the
82 /// file will not change.
84 /// [`Seek`]: ../io/trait.Seek.html
85 /// [`String`]: ../string/struct.String.html
86 /// [`Read`]: ../io/trait.Read.html
87 /// [`Write`]: ../io/trait.Write.html
88 /// [`BufReader<R>`]: ../io/struct.BufReader.html
89 /// [`sync_all`]: struct.File.html#method.sync_all
90 #[stable(feature = "rust1", since = "1.0.0")]
95 /// Metadata information about a file.
97 /// This structure is returned from the [`metadata`] or
98 /// [`symlink_metadata`] function or method and represents known
99 /// metadata about a file such as its permissions, size, modification
102 /// [`metadata`]: fn.metadata.html
103 /// [`symlink_metadata`]: fn.symlink_metadata.html
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct Metadata(fs_imp::FileAttr);
108 /// Iterator over the entries in a directory.
110 /// This iterator is returned from the [`read_dir`] function of this module and
111 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
112 /// information like the entry's path and possibly other metadata can be
117 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
118 /// IO error during iteration.
120 /// [`read_dir`]: fn.read_dir.html
121 /// [`DirEntry`]: struct.DirEntry.html
122 /// [`io::Result`]: ../io/type.Result.html
123 /// [`Err`]: ../result/enum.Result.html#variant.Err
124 #[stable(feature = "rust1", since = "1.0.0")]
126 pub struct ReadDir(fs_imp::ReadDir);
128 /// Entries returned by the [`ReadDir`] iterator.
130 /// [`ReadDir`]: struct.ReadDir.html
132 /// An instance of `DirEntry` represents an entry inside of a directory on the
133 /// filesystem. Each entry can be inspected via methods to learn about the full
134 /// path or possibly other metadata through per-platform extension traits.
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub struct DirEntry(fs_imp::DirEntry);
138 /// Options and flags which can be used to configure how a file is opened.
140 /// This builder exposes the ability to configure how a [`File`] is opened and
141 /// what operations are permitted on the open file. The [`File::open`] and
142 /// [`File::create`] methods are aliases for commonly used options using this
145 /// [`File`]: struct.File.html
146 /// [`File::open`]: struct.File.html#method.open
147 /// [`File::create`]: struct.File.html#method.create
149 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
150 /// then chain calls to methods to set each option, then call [`open`],
151 /// passing the path of the file you're trying to open. This will give you a
152 /// [`io::Result`][result] with a [`File`][file] inside that you can further
155 /// [`new`]: struct.OpenOptions.html#method.new
156 /// [`open`]: struct.OpenOptions.html#method.open
157 /// [result]: ../io/type.Result.html
158 /// [file]: struct.File.html
162 /// Opening a file to read:
165 /// use std::fs::OpenOptions;
167 /// let file = OpenOptions::new().read(true).open("foo.txt");
170 /// Opening a file for both reading and writing, as well as creating it if it
174 /// use std::fs::OpenOptions;
176 /// let file = OpenOptions::new()
180 /// .open("foo.txt");
182 #[derive(Clone, Debug)]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub struct OpenOptions(fs_imp::OpenOptions);
186 /// Representation of the various permissions on a file.
188 /// This module only currently provides one bit of information, [`readonly`],
189 /// which is exposed on all currently supported platforms. Unix-specific
190 /// functionality, such as mode bits, is available through the
191 /// [`PermissionsExt`] trait.
193 /// [`readonly`]: struct.Permissions.html#method.readonly
194 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
195 #[derive(Clone, PartialEq, Eq, Debug)]
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub struct Permissions(fs_imp::FilePermissions);
199 /// A structure representing a type of file with accessors for each file type.
200 /// It is returned by [`Metadata::file_type`] method.
202 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
203 #[stable(feature = "file_type", since = "1.1.0")]
204 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
205 pub struct FileType(fs_imp::FileType);
207 /// A builder used to create directories in various manners.
209 /// This builder also supports platform-specific options.
210 #[stable(feature = "dir_builder", since = "1.6.0")]
212 pub struct DirBuilder {
213 inner: fs_imp::DirBuilder,
217 /// Indicates how large a buffer to pre-allocate before reading the entire file.
218 fn initial_buffer_size(file: &File) -> usize {
219 // Allocate one extra byte so the buffer doesn't need to grow before the
220 // final `read` call at the end of the file. Don't worry about `usize`
221 // overflow because reading will fail regardless in that case.
222 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
225 /// Read the entire contents of a file into a bytes vector.
227 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
228 /// with fewer imports and without an intermediate variable. It pre-allocates a
229 /// buffer based on the file size when available, so it is generally faster than
230 /// reading into a vector created with `Vec::new()`.
232 /// [`File::open`]: struct.File.html#method.open
233 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
237 /// This function will return an error if `path` does not already exist.
238 /// Other errors may also be returned according to [`OpenOptions::open`].
240 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
242 /// It will also return an error if it encounters while reading an error
243 /// of a kind other than [`ErrorKind::Interrupted`].
245 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
251 /// use std::net::SocketAddr;
253 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
254 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
258 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
259 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
260 fn inner(path: &Path) -> io::Result<Vec<u8>> {
261 let mut file = File::open(path)?;
262 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
263 file.read_to_end(&mut bytes)?;
269 /// Read the entire contents of a file into a string.
271 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
272 /// with fewer imports and without an intermediate variable. It pre-allocates a
273 /// buffer based on the file size when available, so it is generally faster than
274 /// reading into a string created with `String::new()`.
276 /// [`File::open`]: struct.File.html#method.open
277 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
281 /// This function will return an error if `path` does not already exist.
282 /// Other errors may also be returned according to [`OpenOptions::open`].
284 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
286 /// It will also return an error if it encounters while reading an error
287 /// of a kind other than [`ErrorKind::Interrupted`],
288 /// or if the contents of the file are not valid UTF-8.
290 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
296 /// use std::net::SocketAddr;
298 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
299 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
303 #[stable(feature = "fs_read_write", since = "1.26.0")]
304 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
305 fn inner(path: &Path) -> io::Result<String> {
306 let mut file = File::open(path)?;
307 let mut string = String::with_capacity(initial_buffer_size(&file));
308 file.read_to_string(&mut string)?;
314 /// Write a slice as the entire contents of a file.
316 /// This function will create a file if it does not exist,
317 /// and will entirely replace its contents if it does.
319 /// This is a convenience function for using [`File::create`] and [`write_all`]
320 /// with fewer imports.
322 /// [`File::create`]: struct.File.html#method.create
323 /// [`write_all`]: ../io/trait.Write.html#method.write_all
330 /// fn main() -> std::io::Result<()> {
331 /// fs::write("foo.txt", b"Lorem ipsum")?;
332 /// fs::write("bar.txt", "dolor sit")?;
336 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
337 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
338 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
339 File::create(path)?.write_all(contents)
341 inner(path.as_ref(), contents.as_ref())
345 /// Attempts to open a file in read-only mode.
347 /// See the [`OpenOptions::open`] method for more details.
351 /// This function will return an error if `path` does not already exist.
352 /// Other errors may also be returned according to [`OpenOptions::open`].
354 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
359 /// use std::fs::File;
361 /// fn main() -> std::io::Result<()> {
362 /// let mut f = File::open("foo.txt")?;
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
368 OpenOptions::new().read(true).open(path.as_ref())
371 /// Opens a file in write-only mode.
373 /// This function will create a file if it does not exist,
374 /// and will truncate it if it does.
376 /// See the [`OpenOptions::open`] function for more details.
378 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
383 /// use std::fs::File;
385 /// fn main() -> std::io::Result<()> {
386 /// let mut f = File::create("foo.txt")?;
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
392 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
395 /// Attempts to sync all OS-internal metadata to disk.
397 /// This function will attempt to ensure that all in-core data reaches the
398 /// filesystem before returning.
403 /// use std::fs::File;
404 /// use std::io::prelude::*;
406 /// fn main() -> std::io::Result<()> {
407 /// let mut f = File::create("foo.txt")?;
408 /// f.write_all(b"Hello, world!")?;
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn sync_all(&self) -> io::Result<()> {
419 /// This function is similar to [`sync_all`], except that it may not
420 /// synchronize file metadata to the filesystem.
422 /// This is intended for use cases that must synchronize content, but don't
423 /// need the metadata on disk. The goal of this method is to reduce disk
426 /// Note that some platforms may simply implement this in terms of
429 /// [`sync_all`]: struct.File.html#method.sync_all
434 /// use std::fs::File;
435 /// use std::io::prelude::*;
437 /// fn main() -> std::io::Result<()> {
438 /// let mut f = File::create("foo.txt")?;
439 /// f.write_all(b"Hello, world!")?;
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn sync_data(&self) -> io::Result<()> {
447 self.inner.datasync()
450 /// Truncates or extends the underlying file, updating the size of
451 /// this file to become `size`.
453 /// If the `size` is less than the current file's size, then the file will
454 /// be shrunk. If it is greater than the current file's size, then the file
455 /// will be extended to `size` and have all of the intermediate data filled
458 /// The file's cursor isn't changed. In particular, if the cursor was at the
459 /// end and the file is shrunk using this operation, the cursor will now be
464 /// This function will return an error if the file is not opened for writing.
469 /// use std::fs::File;
471 /// fn main() -> std::io::Result<()> {
472 /// let mut f = File::create("foo.txt")?;
478 /// Note that this method alters the content of the underlying file, even
479 /// though it takes `&self` rather than `&mut self`.
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn set_len(&self, size: u64) -> io::Result<()> {
482 self.inner.truncate(size)
485 /// Queries metadata about the underlying file.
490 /// use std::fs::File;
492 /// fn main() -> std::io::Result<()> {
493 /// let mut f = File::open("foo.txt")?;
494 /// let metadata = f.metadata()?;
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn metadata(&self) -> io::Result<Metadata> {
500 self.inner.file_attr().map(Metadata)
503 /// Creates a new `File` instance that shares the same underlying file handle
504 /// as the existing `File` instance. Reads, writes, and seeks will affect
505 /// both `File` instances simultaneously.
509 /// Creates two handles for a file named `foo.txt`:
512 /// use std::fs::File;
514 /// fn main() -> std::io::Result<()> {
515 /// let mut file = File::open("foo.txt")?;
516 /// let file_copy = file.try_clone()?;
521 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
522 /// two handles, seek one of them, and read the remaining bytes from the
526 /// use std::fs::File;
527 /// use std::io::SeekFrom;
528 /// use std::io::prelude::*;
530 /// fn main() -> std::io::Result<()> {
531 /// let mut file = File::open("foo.txt")?;
532 /// let mut file_copy = file.try_clone()?;
534 /// file.seek(SeekFrom::Start(3))?;
536 /// let mut contents = vec![];
537 /// file_copy.read_to_end(&mut contents)?;
538 /// assert_eq!(contents, b"def\n");
542 #[stable(feature = "file_try_clone", since = "1.9.0")]
543 pub fn try_clone(&self) -> io::Result<File> {
545 inner: self.inner.duplicate()?
549 /// Changes the permissions on the underlying file.
551 /// # Platform-specific behavior
553 /// This function currently corresponds to the `fchmod` function on Unix and
554 /// the `SetFileInformationByHandle` function on Windows. Note that, this
555 /// [may change in the future][changes].
557 /// [changes]: ../io/index.html#platform-specific-behavior
561 /// This function will return an error if the user lacks permission change
562 /// attributes on the underlying file. It may also return an error in other
563 /// os-specific unspecified cases.
568 /// fn main() -> std::io::Result<()> {
569 /// use std::fs::File;
571 /// let file = File::open("foo.txt")?;
572 /// let mut perms = file.metadata()?.permissions();
573 /// perms.set_readonly(true);
574 /// file.set_permissions(perms)?;
579 /// Note that this method alters the permissions of the underlying file,
580 /// even though it takes `&self` rather than `&mut self`.
581 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
582 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
583 self.inner.set_permissions(perm.0)
587 impl AsInner<fs_imp::File> for File {
588 fn as_inner(&self) -> &fs_imp::File { &self.inner }
590 impl FromInner<fs_imp::File> for File {
591 fn from_inner(f: fs_imp::File) -> File {
595 impl IntoInner<fs_imp::File> for File {
596 fn into_inner(self) -> fs_imp::File {
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl fmt::Debug for File {
603 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
608 #[stable(feature = "rust1", since = "1.0.0")]
610 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
615 unsafe fn initializer(&self) -> Initializer {
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl Write for File {
621 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
622 self.inner.write(buf)
624 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
626 #[stable(feature = "rust1", since = "1.0.0")]
628 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl Read for &File {
634 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
639 unsafe fn initializer(&self) -> Initializer {
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl Write for &File {
645 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
646 self.inner.write(buf)
648 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl Seek for &File {
652 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
658 /// Creates a blank new set of options ready for configuration.
660 /// All options are initially set to `false`.
665 /// use std::fs::OpenOptions;
667 /// let mut options = OpenOptions::new();
668 /// let file = options.read(true).open("foo.txt");
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn new() -> OpenOptions {
672 OpenOptions(fs_imp::OpenOptions::new())
675 /// Sets the option for read access.
677 /// This option, when true, will indicate that the file should be
678 /// `read`-able if opened.
683 /// use std::fs::OpenOptions;
685 /// let file = OpenOptions::new().read(true).open("foo.txt");
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
689 self.0.read(read); self
692 /// Sets the option for write access.
694 /// This option, when true, will indicate that the file should be
695 /// `write`-able if opened.
697 /// If the file already exists, any write calls on it will overwrite its
698 /// contents, without truncating it.
703 /// use std::fs::OpenOptions;
705 /// let file = OpenOptions::new().write(true).open("foo.txt");
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
709 self.0.write(write); self
712 /// Sets the option for the append mode.
714 /// This option, when true, means that writes will append to a file instead
715 /// of overwriting previous contents.
716 /// Note that setting `.write(true).append(true)` has the same effect as
717 /// setting only `.append(true)`.
719 /// For most filesystems, the operating system guarantees that all writes are
720 /// atomic: no writes get mangled because another process writes at the same
723 /// One maybe obvious note when using append-mode: make sure that all data
724 /// that belongs together is written to the file in one operation. This
725 /// can be done by concatenating strings before passing them to [`write()`],
726 /// or using a buffered writer (with a buffer of adequate size),
727 /// and calling [`flush()`] when the message is complete.
729 /// If a file is opened with both read and append access, beware that after
730 /// opening, and after every write, the position for reading may be set at the
731 /// end of the file. So, before writing, save the current position (using
732 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
736 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
739 /// [`write()`]: ../../std/fs/struct.File.html#method.write
740 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
741 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
742 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
743 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
744 /// [`create`]: #method.create
749 /// use std::fs::OpenOptions;
751 /// let file = OpenOptions::new().append(true).open("foo.txt");
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
755 self.0.append(append); self
758 /// Sets the option for truncating a previous file.
760 /// If a file is successfully opened with this option set it will truncate
761 /// the file to 0 length if it already exists.
763 /// The file must be opened with write access for truncate to work.
768 /// use std::fs::OpenOptions;
770 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
774 self.0.truncate(truncate); self
777 /// Sets the option for creating a new file.
779 /// This option indicates whether a new file will be created if the file
780 /// does not yet already exist.
782 /// In order for the file to be created, [`write`] or [`append`] access must
785 /// [`write`]: #method.write
786 /// [`append`]: #method.append
791 /// use std::fs::OpenOptions;
793 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
797 self.0.create(create); self
800 /// Sets the option to always create a new file.
802 /// This option indicates whether a new file will be created.
803 /// No file is allowed to exist at the target location, also no (dangling)
806 /// This option is useful because it is atomic. Otherwise between checking
807 /// whether a file exists and creating a new one, the file may have been
808 /// created by another process (a TOCTOU race condition / attack).
810 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
813 /// The file must be opened with write or append access in order to create
816 /// [`.create()`]: #method.create
817 /// [`.truncate()`]: #method.truncate
822 /// use std::fs::OpenOptions;
824 /// let file = OpenOptions::new().write(true)
825 /// .create_new(true)
826 /// .open("foo.txt");
828 #[stable(feature = "expand_open_options2", since = "1.9.0")]
829 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
830 self.0.create_new(create_new); self
833 /// Opens a file at `path` with the options specified by `self`.
837 /// This function will return an error under a number of different
838 /// circumstances. Some of these error conditions are listed here, together
839 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
840 /// the compatibility contract of the function, especially the `Other` kind
841 /// might change to more specific kinds in the future.
843 /// * [`NotFound`]: The specified file does not exist and neither `create`
844 /// or `create_new` is set.
845 /// * [`NotFound`]: One of the directory components of the file path does
847 /// * [`PermissionDenied`]: The user lacks permission to get the specified
848 /// access rights for the file.
849 /// * [`PermissionDenied`]: The user lacks permission to open one of the
850 /// directory components of the specified path.
851 /// * [`AlreadyExists`]: `create_new` was specified and the file already
853 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
854 /// without write access, no access mode set, etc.).
855 /// * [`Other`]: One of the directory components of the specified file path
856 /// was not, in fact, a directory.
857 /// * [`Other`]: Filesystem-level errors: full disk, write permission
858 /// requested on a read-only file system, exceeded disk quota, too many
859 /// open files, too long filename, too many symbolic links in the
860 /// specified path (Unix-like systems only), etc.
865 /// use std::fs::OpenOptions;
867 /// let file = OpenOptions::new().open("foo.txt");
870 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
871 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
872 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
873 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
874 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
875 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
878 self._open(path.as_ref())
881 fn _open(&self, path: &Path) -> io::Result<File> {
882 let inner = fs_imp::File::open(path, &self.0)?;
887 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
888 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
892 /// Returns the file type for this metadata.
897 /// fn main() -> std::io::Result<()> {
900 /// let metadata = fs::metadata("foo.txt")?;
902 /// println!("{:?}", metadata.file_type());
906 #[stable(feature = "file_type", since = "1.1.0")]
907 pub fn file_type(&self) -> FileType {
908 FileType(self.0.file_type())
911 /// Returns `true` if this metadata is for a directory. The
912 /// result is mutually exclusive to the result of
913 /// [`is_file`], and will be false for symlink metadata
914 /// obtained from [`symlink_metadata`].
916 /// [`is_file`]: struct.Metadata.html#method.is_file
917 /// [`symlink_metadata`]: fn.symlink_metadata.html
922 /// fn main() -> std::io::Result<()> {
925 /// let metadata = fs::metadata("foo.txt")?;
927 /// assert!(!metadata.is_dir());
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
934 /// Returns `true` if this metadata is for a regular file. The
935 /// result is mutually exclusive to the result of
936 /// [`is_dir`], and will be false for symlink metadata
937 /// obtained from [`symlink_metadata`].
939 /// [`is_dir`]: struct.Metadata.html#method.is_dir
940 /// [`symlink_metadata`]: fn.symlink_metadata.html
947 /// fn main() -> std::io::Result<()> {
948 /// let metadata = fs::metadata("foo.txt")?;
950 /// assert!(metadata.is_file());
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn is_file(&self) -> bool { self.file_type().is_file() }
957 /// Returns the size of the file, in bytes, this metadata is for.
964 /// fn main() -> std::io::Result<()> {
965 /// let metadata = fs::metadata("foo.txt")?;
967 /// assert_eq!(0, metadata.len());
971 #[stable(feature = "rust1", since = "1.0.0")]
972 pub fn len(&self) -> u64 { self.0.size() }
974 /// Returns the permissions of the file this metadata is for.
981 /// fn main() -> std::io::Result<()> {
982 /// let metadata = fs::metadata("foo.txt")?;
984 /// assert!(!metadata.permissions().readonly());
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn permissions(&self) -> Permissions {
990 Permissions(self.0.perm())
993 /// Returns the last modification time listed in this metadata.
995 /// The returned value corresponds to the `mtime` field of `stat` on Unix
996 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1000 /// This field may not be available on all platforms, and will return an
1001 /// `Err` on platforms where it is not available.
1008 /// fn main() -> std::io::Result<()> {
1009 /// let metadata = fs::metadata("foo.txt")?;
1011 /// if let Ok(time) = metadata.modified() {
1012 /// println!("{:?}", time);
1014 /// println!("Not supported on this platform");
1019 #[stable(feature = "fs_time", since = "1.10.0")]
1020 pub fn modified(&self) -> io::Result<SystemTime> {
1021 self.0.modified().map(FromInner::from_inner)
1024 /// Returns the last access time of this metadata.
1026 /// The returned value corresponds to the `atime` field of `stat` on Unix
1027 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1029 /// Note that not all platforms will keep this field update in a file's
1030 /// metadata, for example Windows has an option to disable updating this
1031 /// time when files are accessed and Linux similarly has `noatime`.
1035 /// This field may not be available on all platforms, and will return an
1036 /// `Err` on platforms where it is not available.
1043 /// fn main() -> std::io::Result<()> {
1044 /// let metadata = fs::metadata("foo.txt")?;
1046 /// if let Ok(time) = metadata.accessed() {
1047 /// println!("{:?}", time);
1049 /// println!("Not supported on this platform");
1054 #[stable(feature = "fs_time", since = "1.10.0")]
1055 pub fn accessed(&self) -> io::Result<SystemTime> {
1056 self.0.accessed().map(FromInner::from_inner)
1059 /// Returns the creation time listed in this metadata.
1061 /// The returned value corresponds to the `birthtime` field of `stat` on
1062 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1066 /// This field may not be available on all platforms, and will return an
1067 /// `Err` on platforms where it is not available.
1074 /// fn main() -> std::io::Result<()> {
1075 /// let metadata = fs::metadata("foo.txt")?;
1077 /// if let Ok(time) = metadata.created() {
1078 /// println!("{:?}", time);
1080 /// println!("Not supported on this platform");
1085 #[stable(feature = "fs_time", since = "1.10.0")]
1086 pub fn created(&self) -> io::Result<SystemTime> {
1087 self.0.created().map(FromInner::from_inner)
1091 #[stable(feature = "std_debug", since = "1.16.0")]
1092 impl fmt::Debug for Metadata {
1093 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1094 f.debug_struct("Metadata")
1095 .field("file_type", &self.file_type())
1096 .field("is_dir", &self.is_dir())
1097 .field("is_file", &self.is_file())
1098 .field("permissions", &self.permissions())
1099 .field("modified", &self.modified())
1100 .field("accessed", &self.accessed())
1101 .field("created", &self.created())
1106 impl AsInner<fs_imp::FileAttr> for Metadata {
1107 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1111 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1116 /// use std::fs::File;
1118 /// fn main() -> std::io::Result<()> {
1119 /// let mut f = File::create("foo.txt")?;
1120 /// let metadata = f.metadata()?;
1122 /// assert_eq!(false, metadata.permissions().readonly());
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub fn readonly(&self) -> bool { self.0.readonly() }
1129 /// Modifies the readonly flag for this set of permissions. If the
1130 /// `readonly` argument is `true`, using the resulting `Permission` will
1131 /// update file permissions to forbid writing. Conversely, if it's `false`,
1132 /// using the resulting `Permission` will update file permissions to allow
1135 /// This operation does **not** modify the filesystem. To modify the
1136 /// filesystem use the [`fs::set_permissions`] function.
1138 /// [`fs::set_permissions`]: fn.set_permissions.html
1143 /// use std::fs::File;
1145 /// fn main() -> std::io::Result<()> {
1146 /// let f = File::create("foo.txt")?;
1147 /// let metadata = f.metadata()?;
1148 /// let mut permissions = metadata.permissions();
1150 /// permissions.set_readonly(true);
1152 /// // filesystem doesn't change
1153 /// assert_eq!(false, metadata.permissions().readonly());
1155 /// // just this particular `permissions`.
1156 /// assert_eq!(true, permissions.readonly());
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn set_readonly(&mut self, readonly: bool) {
1162 self.0.set_readonly(readonly)
1167 /// Tests whether this file type represents a directory. The
1168 /// result is mutually exclusive to the results of
1169 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1172 /// [`is_file`]: struct.FileType.html#method.is_file
1173 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1178 /// fn main() -> std::io::Result<()> {
1181 /// let metadata = fs::metadata("foo.txt")?;
1182 /// let file_type = metadata.file_type();
1184 /// assert_eq!(file_type.is_dir(), false);
1188 #[stable(feature = "file_type", since = "1.1.0")]
1189 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1191 /// Tests whether this file type represents a regular file.
1192 /// The result is mutually exclusive to the results of
1193 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1196 /// [`is_dir`]: struct.FileType.html#method.is_dir
1197 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1202 /// fn main() -> std::io::Result<()> {
1205 /// let metadata = fs::metadata("foo.txt")?;
1206 /// let file_type = metadata.file_type();
1208 /// assert_eq!(file_type.is_file(), true);
1212 #[stable(feature = "file_type", since = "1.1.0")]
1213 pub fn is_file(&self) -> bool { self.0.is_file() }
1215 /// Tests whether this file type represents a symbolic link.
1216 /// The result is mutually exclusive to the results of
1217 /// [`is_dir`] and [`is_file`]; only zero or one of these
1220 /// The underlying [`Metadata`] struct needs to be retrieved
1221 /// with the [`fs::symlink_metadata`] function and not the
1222 /// [`fs::metadata`] function. The [`fs::metadata`] function
1223 /// follows symbolic links, so [`is_symlink`] would always
1224 /// return `false` for the target file.
1226 /// [`Metadata`]: struct.Metadata.html
1227 /// [`fs::metadata`]: fn.metadata.html
1228 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1229 /// [`is_dir`]: struct.FileType.html#method.is_dir
1230 /// [`is_file`]: struct.FileType.html#method.is_file
1231 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1238 /// fn main() -> std::io::Result<()> {
1239 /// let metadata = fs::symlink_metadata("foo.txt")?;
1240 /// let file_type = metadata.file_type();
1242 /// assert_eq!(file_type.is_symlink(), false);
1246 #[stable(feature = "file_type", since = "1.1.0")]
1247 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1250 impl AsInner<fs_imp::FileType> for FileType {
1251 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1254 impl FromInner<fs_imp::FilePermissions> for Permissions {
1255 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1260 impl AsInner<fs_imp::FilePermissions> for Permissions {
1261 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl Iterator for ReadDir {
1266 type Item = io::Result<DirEntry>;
1268 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1269 self.0.next().map(|entry| entry.map(DirEntry))
1274 /// Returns the full path to the file that this entry represents.
1276 /// The full path is created by joining the original path to `read_dir`
1277 /// with the filename of this entry.
1284 /// fn main() -> std::io::Result<()> {
1285 /// for entry in fs::read_dir(".")? {
1286 /// let dir = entry?;
1287 /// println!("{:?}", dir.path());
1293 /// This prints output like:
1296 /// "./whatever.txt"
1298 /// "./hello_world.rs"
1301 /// The exact text, of course, depends on what files you have in `.`.
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 pub fn path(&self) -> PathBuf { self.0.path() }
1305 /// Returns the metadata for the file that this entry points at.
1307 /// This function will not traverse symlinks if this entry points at a
1310 /// # Platform-specific behavior
1312 /// On Windows this function is cheap to call (no extra system calls
1313 /// needed), but on Unix platforms this function is the equivalent of
1314 /// calling `symlink_metadata` on the path.
1321 /// if let Ok(entries) = fs::read_dir(".") {
1322 /// for entry in entries {
1323 /// if let Ok(entry) = entry {
1324 /// // Here, `entry` is a `DirEntry`.
1325 /// if let Ok(metadata) = entry.metadata() {
1326 /// // Now let's show our entry's permissions!
1327 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1329 /// println!("Couldn't get metadata for {:?}", entry.path());
1335 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1336 pub fn metadata(&self) -> io::Result<Metadata> {
1337 self.0.metadata().map(Metadata)
1340 /// Returns the file type for the file that this entry points at.
1342 /// This function will not traverse symlinks if this entry points at a
1345 /// # Platform-specific behavior
1347 /// On Windows and most Unix platforms this function is free (no extra
1348 /// system calls needed), but some Unix platforms may require the equivalent
1349 /// call to `symlink_metadata` to learn about the target file type.
1356 /// if let Ok(entries) = fs::read_dir(".") {
1357 /// for entry in entries {
1358 /// if let Ok(entry) = entry {
1359 /// // Here, `entry` is a `DirEntry`.
1360 /// if let Ok(file_type) = entry.file_type() {
1361 /// // Now let's show our entry's file type!
1362 /// println!("{:?}: {:?}", entry.path(), file_type);
1364 /// println!("Couldn't get file type for {:?}", entry.path());
1370 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1371 pub fn file_type(&self) -> io::Result<FileType> {
1372 self.0.file_type().map(FileType)
1375 /// Returns the bare file name of this directory entry without any other
1376 /// leading path component.
1383 /// if let Ok(entries) = fs::read_dir(".") {
1384 /// for entry in entries {
1385 /// if let Ok(entry) = entry {
1386 /// // Here, `entry` is a `DirEntry`.
1387 /// println!("{:?}", entry.file_name());
1392 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1393 pub fn file_name(&self) -> OsString {
1398 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1399 impl fmt::Debug for DirEntry {
1400 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1401 f.debug_tuple("DirEntry")
1402 .field(&self.path())
1407 impl AsInner<fs_imp::DirEntry> for DirEntry {
1408 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1411 /// Removes a file from the filesystem.
1413 /// Note that there is no
1414 /// guarantee that the file is immediately deleted (e.g., depending on
1415 /// platform, other open file descriptors may prevent immediate removal).
1417 /// # Platform-specific behavior
1419 /// This function currently corresponds to the `unlink` function on Unix
1420 /// and the `DeleteFile` function on Windows.
1421 /// Note that, this [may change in the future][changes].
1423 /// [changes]: ../io/index.html#platform-specific-behavior
1427 /// This function will return an error in the following situations, but is not
1428 /// limited to just these cases:
1430 /// * `path` points to a directory.
1431 /// * The user lacks permissions to remove the file.
1438 /// fn main() -> std::io::Result<()> {
1439 /// fs::remove_file("a.txt")?;
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1445 fs_imp::unlink(path.as_ref())
1448 /// Given a path, query the file system to get information about a file,
1451 /// This function will traverse symbolic links to query information about the
1452 /// destination file.
1454 /// # Platform-specific behavior
1456 /// This function currently corresponds to the `stat` function on Unix
1457 /// and the `GetFileAttributesEx` function on Windows.
1458 /// Note that, this [may change in the future][changes].
1460 /// [changes]: ../io/index.html#platform-specific-behavior
1464 /// This function will return an error in the following situations, but is not
1465 /// limited to just these cases:
1467 /// * The user lacks permissions to perform `metadata` call on `path`.
1468 /// * `path` does not exist.
1475 /// fn main() -> std::io::Result<()> {
1476 /// let attr = fs::metadata("/some/file/path.txt")?;
1477 /// // inspect attr ...
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1483 fs_imp::stat(path.as_ref()).map(Metadata)
1486 /// Query the metadata about a file without following symlinks.
1488 /// # Platform-specific behavior
1490 /// This function currently corresponds to the `lstat` function on Unix
1491 /// and the `GetFileAttributesEx` function on Windows.
1492 /// Note that, this [may change in the future][changes].
1494 /// [changes]: ../io/index.html#platform-specific-behavior
1498 /// This function will return an error in the following situations, but is not
1499 /// limited to just these cases:
1501 /// * The user lacks permissions to perform `metadata` call on `path`.
1502 /// * `path` does not exist.
1509 /// fn main() -> std::io::Result<()> {
1510 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1511 /// // inspect attr ...
1515 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1516 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1517 fs_imp::lstat(path.as_ref()).map(Metadata)
1520 /// Rename a file or directory to a new name, replacing the original file if
1521 /// `to` already exists.
1523 /// This will not work if the new name is on a different mount point.
1525 /// # Platform-specific behavior
1527 /// This function currently corresponds to the `rename` function on Unix
1528 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1530 /// Because of this, the behavior when both `from` and `to` exist differs. On
1531 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1532 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1533 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1535 /// Note that, this [may change in the future][changes].
1537 /// [changes]: ../io/index.html#platform-specific-behavior
1541 /// This function will return an error in the following situations, but is not
1542 /// limited to just these cases:
1544 /// * `from` does not exist.
1545 /// * The user lacks permissions to view contents.
1546 /// * `from` and `to` are on separate filesystems.
1553 /// fn main() -> std::io::Result<()> {
1554 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1560 fs_imp::rename(from.as_ref(), to.as_ref())
1563 /// Copies the contents of one file to another. This function will also
1564 /// copy the permission bits of the original file to the destination file.
1566 /// This function will **overwrite** the contents of `to`.
1568 /// Note that if `from` and `to` both point to the same file, then the file
1569 /// will likely get truncated by this operation.
1571 /// On success, the total number of bytes copied is returned and it is equal to
1572 /// the length of the `to` file as reported by `metadata`.
1574 /// If you’re wanting to copy the contents of one file to another and you’re
1575 /// working with [`File`]s, see the [`io::copy`] function.
1577 /// [`io::copy`]: ../io/fn.copy.html
1578 /// [`File`]: ./struct.File.html
1580 /// # Platform-specific behavior
1582 /// This function currently corresponds to the `open` function in Unix
1583 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1584 /// `O_CLOEXEC` is set for returned file descriptors.
1585 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1586 /// NTFS streams are copied but only the size of the main stream is returned by
1587 /// this function. On MacOS, this function corresponds to `copyfile` with
1589 /// Note that, this [may change in the future][changes].
1591 /// [changes]: ../io/index.html#platform-specific-behavior
1595 /// This function will return an error in the following situations, but is not
1596 /// limited to just these cases:
1598 /// * The `from` path is not a file.
1599 /// * The `from` file does not exist.
1600 /// * The current process does not have the permission rights to access
1601 /// `from` or write `to`.
1608 /// fn main() -> std::io::Result<()> {
1609 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1615 fs_imp::copy(from.as_ref(), to.as_ref())
1618 /// Creates a new hard link on the filesystem.
1620 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1621 /// often require these two paths to both be located on the same filesystem.
1623 /// # Platform-specific behavior
1625 /// This function currently corresponds to the `link` function on Unix
1626 /// and the `CreateHardLink` function on Windows.
1627 /// Note that, this [may change in the future][changes].
1629 /// [changes]: ../io/index.html#platform-specific-behavior
1633 /// This function will return an error in the following situations, but is not
1634 /// limited to just these cases:
1636 /// * The `src` path is not a file or doesn't exist.
1643 /// fn main() -> std::io::Result<()> {
1644 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1650 fs_imp::link(src.as_ref(), dst.as_ref())
1653 /// Creates a new symbolic link on the filesystem.
1655 /// The `dst` path will be a symbolic link pointing to the `src` path.
1656 /// On Windows, this will be a file symlink, not a directory symlink;
1657 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1658 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1659 /// used instead to make the intent explicit.
1661 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1662 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1663 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1671 /// fn main() -> std::io::Result<()> {
1672 /// fs::soft_link("a.txt", "b.txt")?;
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 #[rustc_deprecated(since = "1.1.0",
1678 reason = "replaced with std::os::unix::fs::symlink and \
1679 std::os::windows::fs::{symlink_file, symlink_dir}")]
1680 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1681 fs_imp::symlink(src.as_ref(), dst.as_ref())
1684 /// Reads a symbolic link, returning the file that the link points to.
1686 /// # Platform-specific behavior
1688 /// This function currently corresponds to the `readlink` function on Unix
1689 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1690 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1691 /// Note that, this [may change in the future][changes].
1693 /// [changes]: ../io/index.html#platform-specific-behavior
1697 /// This function will return an error in the following situations, but is not
1698 /// limited to just these cases:
1700 /// * `path` is not a symbolic link.
1701 /// * `path` does not exist.
1708 /// fn main() -> std::io::Result<()> {
1709 /// let path = fs::read_link("a.txt")?;
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1715 fs_imp::readlink(path.as_ref())
1718 /// Returns the canonical, absolute form of a path with all intermediate
1719 /// components normalized and symbolic links resolved.
1721 /// # Platform-specific behavior
1723 /// This function currently corresponds to the `realpath` function on Unix
1724 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1725 /// Note that, this [may change in the future][changes].
1727 /// On Windows, this converts the path to use [extended length path][path]
1728 /// syntax, which allows your program to use longer path names, but means you
1729 /// can only join backslash-delimited paths to it, and it may be incompatible
1730 /// with other applications (if passed to the application on the command-line,
1731 /// or written to a file another application may read).
1733 /// [changes]: ../io/index.html#platform-specific-behavior
1734 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1738 /// This function will return an error in the following situations, but is not
1739 /// limited to just these cases:
1741 /// * `path` does not exist.
1742 /// * A non-final component in path is not a directory.
1749 /// fn main() -> std::io::Result<()> {
1750 /// let path = fs::canonicalize("../a/../foo.txt")?;
1754 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1755 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1756 fs_imp::canonicalize(path.as_ref())
1759 /// Creates a new, empty directory at the provided path
1761 /// # Platform-specific behavior
1763 /// This function currently corresponds to the `mkdir` function on Unix
1764 /// and the `CreateDirectory` function on Windows.
1765 /// Note that, this [may change in the future][changes].
1767 /// [changes]: ../io/index.html#platform-specific-behavior
1769 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1770 /// return an error. To create a directory and all its missing parents at the
1771 /// same time, use the [`create_dir_all`] function.
1775 /// This function will return an error in the following situations, but is not
1776 /// limited to just these cases:
1778 /// * User lacks permissions to create directory at `path`.
1779 /// * A parent of the given path doesn't exist. (To create a directory and all
1780 /// its missing parents at the same time, use the [`create_dir_all`]
1782 /// * `path` already exists.
1789 /// fn main() -> std::io::Result<()> {
1790 /// fs::create_dir("/some/dir")?;
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1796 DirBuilder::new().create(path.as_ref())
1799 /// Recursively create a directory and all of its parent components if they
1802 /// # Platform-specific behavior
1804 /// This function currently corresponds to the `mkdir` function on Unix
1805 /// and the `CreateDirectory` function on Windows.
1806 /// Note that, this [may change in the future][changes].
1808 /// [changes]: ../io/index.html#platform-specific-behavior
1812 /// This function will return an error in the following situations, but is not
1813 /// limited to just these cases:
1815 /// * If any directory in the path specified by `path`
1816 /// does not already exist and it could not be created otherwise. The specific
1817 /// error conditions for when a directory is being created (after it is
1818 /// determined to not exist) are outlined by [`fs::create_dir`].
1820 /// Notable exception is made for situations where any of the directories
1821 /// specified in the `path` could not be created as it was being created concurrently.
1822 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1823 /// concurrently from multiple threads or processes is guaranteed not to fail
1824 /// due to a race condition with itself.
1826 /// [`fs::create_dir`]: fn.create_dir.html
1833 /// fn main() -> std::io::Result<()> {
1834 /// fs::create_dir_all("/some/dir")?;
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1840 DirBuilder::new().recursive(true).create(path.as_ref())
1843 /// Removes an existing, empty directory.
1845 /// # Platform-specific behavior
1847 /// This function currently corresponds to the `rmdir` function on Unix
1848 /// and the `RemoveDirectory` function on Windows.
1849 /// Note that, this [may change in the future][changes].
1851 /// [changes]: ../io/index.html#platform-specific-behavior
1855 /// This function will return an error in the following situations, but is not
1856 /// limited to just these cases:
1858 /// * The user lacks permissions to remove the directory at the provided `path`.
1859 /// * The directory isn't empty.
1866 /// fn main() -> std::io::Result<()> {
1867 /// fs::remove_dir("/some/dir")?;
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1873 fs_imp::rmdir(path.as_ref())
1876 /// Removes a directory at this path, after removing all its contents. Use
1879 /// This function does **not** follow symbolic links and it will simply remove the
1880 /// symbolic link itself.
1882 /// # Platform-specific behavior
1884 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1885 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1887 /// Note that, this [may change in the future][changes].
1889 /// [changes]: ../io/index.html#platform-specific-behavior
1893 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1895 /// [`fs::remove_file`]: fn.remove_file.html
1896 /// [`fs::remove_dir`]: fn.remove_dir.html
1903 /// fn main() -> std::io::Result<()> {
1904 /// fs::remove_dir_all("/some/dir")?;
1908 #[stable(feature = "rust1", since = "1.0.0")]
1909 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1910 fs_imp::remove_dir_all(path.as_ref())
1913 /// Returns an iterator over the entries within a directory.
1915 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1916 /// New errors may be encountered after an iterator is initially constructed.
1918 /// [`io::Result`]: ../io/type.Result.html
1919 /// [`DirEntry`]: struct.DirEntry.html
1921 /// # Platform-specific behavior
1923 /// This function currently corresponds to the `opendir` function on Unix
1924 /// and the `FindFirstFile` function on Windows.
1925 /// Note that, this [may change in the future][changes].
1927 /// [changes]: ../io/index.html#platform-specific-behavior
1931 /// This function will return an error in the following situations, but is not
1932 /// limited to just these cases:
1934 /// * The provided `path` doesn't exist.
1935 /// * The process lacks permissions to view the contents.
1936 /// * The `path` points at a non-directory file.
1942 /// use std::fs::{self, DirEntry};
1943 /// use std::path::Path;
1945 /// // one possible implementation of walking a directory only visiting files
1946 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1947 /// if dir.is_dir() {
1948 /// for entry in fs::read_dir(dir)? {
1949 /// let entry = entry?;
1950 /// let path = entry.path();
1951 /// if path.is_dir() {
1952 /// visit_dirs(&path, cb)?;
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1963 fs_imp::readdir(path.as_ref()).map(ReadDir)
1966 /// Changes the permissions found on a file or a directory.
1968 /// # Platform-specific behavior
1970 /// This function currently corresponds to the `chmod` function on Unix
1971 /// and the `SetFileAttributes` function on Windows.
1972 /// Note that, this [may change in the future][changes].
1974 /// [changes]: ../io/index.html#platform-specific-behavior
1978 /// This function will return an error in the following situations, but is not
1979 /// limited to just these cases:
1981 /// * `path` does not exist.
1982 /// * The user lacks the permission to change attributes of the file.
1989 /// fn main() -> std::io::Result<()> {
1990 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1991 /// perms.set_readonly(true);
1992 /// fs::set_permissions("foo.txt", perms)?;
1996 #[stable(feature = "set_permissions", since = "1.1.0")]
1997 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1999 fs_imp::set_perm(path.as_ref(), perm.0)
2003 /// Creates a new set of options with default mode/security settings for all
2004 /// platforms and also non-recursive.
2009 /// use std::fs::DirBuilder;
2011 /// let builder = DirBuilder::new();
2013 #[stable(feature = "dir_builder", since = "1.6.0")]
2014 pub fn new() -> DirBuilder {
2016 inner: fs_imp::DirBuilder::new(),
2021 /// Indicates that directories should be created recursively, creating all
2022 /// parent directories. Parents that do not exist are created with the same
2023 /// security and permissions settings.
2025 /// This option defaults to `false`.
2030 /// use std::fs::DirBuilder;
2032 /// let mut builder = DirBuilder::new();
2033 /// builder.recursive(true);
2035 #[stable(feature = "dir_builder", since = "1.6.0")]
2036 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2037 self.recursive = recursive;
2041 /// Creates the specified directory with the options configured in this
2044 /// It is considered an error if the directory already exists unless
2045 /// recursive mode is enabled.
2050 /// use std::fs::{self, DirBuilder};
2052 /// let path = "/tmp/foo/bar/baz";
2053 /// DirBuilder::new()
2054 /// .recursive(true)
2055 /// .create(path).unwrap();
2057 /// assert!(fs::metadata(path).unwrap().is_dir());
2059 #[stable(feature = "dir_builder", since = "1.6.0")]
2060 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2061 self._create(path.as_ref())
2064 fn _create(&self, path: &Path) -> io::Result<()> {
2066 self.create_dir_all(path)
2068 self.inner.mkdir(path)
2072 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2073 if path == Path::new("") {
2077 match self.inner.mkdir(path) {
2078 Ok(()) => return Ok(()),
2079 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2080 Err(_) if path.is_dir() => return Ok(()),
2081 Err(e) => return Err(e),
2083 match path.parent() {
2084 Some(p) => self.create_dir_all(p)?,
2085 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2087 match self.inner.mkdir(path) {
2089 Err(_) if path.is_dir() => Ok(()),
2095 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2096 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2101 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2103 use crate::io::prelude::*;
2105 use crate::fs::{self, File, OpenOptions};
2106 use crate::io::{ErrorKind, SeekFrom};
2107 use crate::path::Path;
2109 use crate::sys_common::io::test::{TempDir, tmpdir};
2112 use rand::{rngs::StdRng, FromEntropy, RngCore};
2115 use crate::os::windows::fs::{symlink_dir, symlink_file};
2117 use crate::sys::fs::symlink_junction;
2119 use crate::os::unix::fs::symlink as symlink_dir;
2121 use crate::os::unix::fs::symlink as symlink_file;
2123 use crate::os::unix::fs::symlink as symlink_junction;
2125 macro_rules! check { ($e:expr) => (
2128 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2133 macro_rules! error { ($e:expr, $s:expr) => (
2135 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2136 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2137 format!("`{}` did not have a code of `{}`", err, $s))
2142 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2144 macro_rules! error_contains { ($e:expr, $s:expr) => (
2146 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2147 Err(ref err) => assert!(err.to_string().contains($s),
2148 format!("`{}` did not contain `{}`", err, $s))
2152 // Several test fail on windows if the user does not have permission to
2153 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2154 // disabling these test on Windows, use this function to test whether we
2155 // have permission, and return otherwise. This way, we still don't run these
2156 // tests most of the time, but at least we do if the user has the right
2158 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2159 if cfg!(unix) { return true }
2160 let link = tmpdir.join("some_hopefully_unique_link_name");
2162 match symlink_file(r"nonexisting_target", link) {
2164 // ERROR_PRIVILEGE_NOT_HELD = 1314
2165 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2171 fn file_test_io_smoke_test() {
2172 let message = "it's alright. have a good time";
2173 let tmpdir = tmpdir();
2174 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2176 let mut write_stream = check!(File::create(filename));
2177 check!(write_stream.write(message.as_bytes()));
2180 let mut read_stream = check!(File::open(filename));
2181 let mut read_buf = [0; 1028];
2182 let read_str = match check!(read_stream.read(&mut read_buf)) {
2183 0 => panic!("shouldn't happen"),
2184 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2186 assert_eq!(read_str, message);
2188 check!(fs::remove_file(filename));
2192 fn invalid_path_raises() {
2193 let tmpdir = tmpdir();
2194 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2195 let result = File::open(filename);
2198 error!(result, "No such file or directory");
2200 error!(result, 2); // ERROR_FILE_NOT_FOUND
2204 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2205 let tmpdir = tmpdir();
2206 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2208 let result = fs::remove_file(filename);
2211 error!(result, "No such file or directory");
2213 error!(result, 2); // ERROR_FILE_NOT_FOUND
2217 fn file_test_io_non_positional_read() {
2218 let message: &str = "ten-four";
2219 let mut read_mem = [0; 8];
2220 let tmpdir = tmpdir();
2221 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2223 let mut rw_stream = check!(File::create(filename));
2224 check!(rw_stream.write(message.as_bytes()));
2227 let mut read_stream = check!(File::open(filename));
2229 let read_buf = &mut read_mem[0..4];
2230 check!(read_stream.read(read_buf));
2233 let read_buf = &mut read_mem[4..8];
2234 check!(read_stream.read(read_buf));
2237 check!(fs::remove_file(filename));
2238 let read_str = str::from_utf8(&read_mem).unwrap();
2239 assert_eq!(read_str, message);
2243 fn file_test_io_seek_and_tell_smoke_test() {
2244 let message = "ten-four";
2245 let mut read_mem = [0; 4];
2246 let set_cursor = 4 as u64;
2247 let tell_pos_pre_read;
2248 let tell_pos_post_read;
2249 let tmpdir = tmpdir();
2250 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2252 let mut rw_stream = check!(File::create(filename));
2253 check!(rw_stream.write(message.as_bytes()));
2256 let mut read_stream = check!(File::open(filename));
2257 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2258 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2259 check!(read_stream.read(&mut read_mem));
2260 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2262 check!(fs::remove_file(filename));
2263 let read_str = str::from_utf8(&read_mem).unwrap();
2264 assert_eq!(read_str, &message[4..8]);
2265 assert_eq!(tell_pos_pre_read, set_cursor);
2266 assert_eq!(tell_pos_post_read, message.len() as u64);
2270 fn file_test_io_seek_and_write() {
2271 let initial_msg = "food-is-yummy";
2272 let overwrite_msg = "-the-bar!!";
2273 let final_msg = "foo-the-bar!!";
2275 let mut read_mem = [0; 13];
2276 let tmpdir = tmpdir();
2277 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2279 let mut rw_stream = check!(File::create(filename));
2280 check!(rw_stream.write(initial_msg.as_bytes()));
2281 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2282 check!(rw_stream.write(overwrite_msg.as_bytes()));
2285 let mut read_stream = check!(File::open(filename));
2286 check!(read_stream.read(&mut read_mem));
2288 check!(fs::remove_file(filename));
2289 let read_str = str::from_utf8(&read_mem).unwrap();
2290 assert!(read_str == final_msg);
2294 fn file_test_io_seek_shakedown() {
2296 let initial_msg = "qwer-asdf-zxcv";
2297 let chunk_one: &str = "qwer";
2298 let chunk_two: &str = "asdf";
2299 let chunk_three: &str = "zxcv";
2300 let mut read_mem = [0; 4];
2301 let tmpdir = tmpdir();
2302 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2304 let mut rw_stream = check!(File::create(filename));
2305 check!(rw_stream.write(initial_msg.as_bytes()));
2308 let mut read_stream = check!(File::open(filename));
2310 check!(read_stream.seek(SeekFrom::End(-4)));
2311 check!(read_stream.read(&mut read_mem));
2312 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2314 check!(read_stream.seek(SeekFrom::Current(-9)));
2315 check!(read_stream.read(&mut read_mem));
2316 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2318 check!(read_stream.seek(SeekFrom::Start(0)));
2319 check!(read_stream.read(&mut read_mem));
2320 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2322 check!(fs::remove_file(filename));
2326 fn file_test_io_eof() {
2327 let tmpdir = tmpdir();
2328 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2329 let mut buf = [0; 256];
2331 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2332 let mut rw = check!(oo.open(&filename));
2333 assert_eq!(check!(rw.read(&mut buf)), 0);
2334 assert_eq!(check!(rw.read(&mut buf)), 0);
2336 check!(fs::remove_file(&filename));
2341 fn file_test_io_read_write_at() {
2342 use crate::os::unix::fs::FileExt;
2344 let tmpdir = tmpdir();
2345 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2346 let mut buf = [0; 256];
2347 let write1 = "asdf";
2348 let write2 = "qwer-";
2349 let write3 = "-zxcv";
2350 let content = "qwer-asdf-zxcv";
2352 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2353 let mut rw = check!(oo.open(&filename));
2354 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2355 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2356 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2357 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2358 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2359 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2360 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2361 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2362 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2363 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2364 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2365 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2366 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2367 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2368 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2369 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2370 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2371 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2374 let mut read = check!(File::open(&filename));
2375 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2376 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2377 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2378 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2379 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2380 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2381 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2382 assert_eq!(check!(read.read(&mut buf)), write3.len());
2383 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2384 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2385 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2386 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2387 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2388 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2389 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2390 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2392 check!(fs::remove_file(&filename));
2397 fn set_get_unix_permissions() {
2398 use crate::os::unix::fs::PermissionsExt;
2400 let tmpdir = tmpdir();
2401 let filename = &tmpdir.join("set_get_unix_permissions");
2402 check!(fs::create_dir(filename));
2405 check!(fs::set_permissions(filename,
2406 fs::Permissions::from_mode(0)));
2407 let metadata0 = check!(fs::metadata(filename));
2408 assert_eq!(mask & metadata0.permissions().mode(), 0);
2410 check!(fs::set_permissions(filename,
2411 fs::Permissions::from_mode(0o1777)));
2412 let metadata1 = check!(fs::metadata(filename));
2413 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2418 fn file_test_io_seek_read_write() {
2419 use crate::os::windows::fs::FileExt;
2421 let tmpdir = tmpdir();
2422 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2423 let mut buf = [0; 256];
2424 let write1 = "asdf";
2425 let write2 = "qwer-";
2426 let write3 = "-zxcv";
2427 let content = "qwer-asdf-zxcv";
2429 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2430 let mut rw = check!(oo.open(&filename));
2431 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2432 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2433 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2434 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2435 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2436 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2437 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2438 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2439 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2440 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2441 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2442 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2443 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2444 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2445 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2446 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2449 let mut read = check!(File::open(&filename));
2450 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2451 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2452 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2453 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2454 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2455 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2456 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2457 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2458 assert_eq!(check!(read.read(&mut buf)), write3.len());
2459 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2460 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2461 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2462 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2463 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2464 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2465 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2467 check!(fs::remove_file(&filename));
2471 fn file_test_stat_is_correct_on_is_file() {
2472 let tmpdir = tmpdir();
2473 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2475 let mut opts = OpenOptions::new();
2476 let mut fs = check!(opts.read(true).write(true)
2477 .create(true).open(filename));
2479 fs.write(msg.as_bytes()).unwrap();
2481 let fstat_res = check!(fs.metadata());
2482 assert!(fstat_res.is_file());
2484 let stat_res_fn = check!(fs::metadata(filename));
2485 assert!(stat_res_fn.is_file());
2486 let stat_res_meth = check!(filename.metadata());
2487 assert!(stat_res_meth.is_file());
2488 check!(fs::remove_file(filename));
2492 fn file_test_stat_is_correct_on_is_dir() {
2493 let tmpdir = tmpdir();
2494 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2495 check!(fs::create_dir(filename));
2496 let stat_res_fn = check!(fs::metadata(filename));
2497 assert!(stat_res_fn.is_dir());
2498 let stat_res_meth = check!(filename.metadata());
2499 assert!(stat_res_meth.is_dir());
2500 check!(fs::remove_dir(filename));
2504 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2505 let tmpdir = tmpdir();
2506 let dir = &tmpdir.join("fileinfo_false_on_dir");
2507 check!(fs::create_dir(dir));
2508 assert!(!dir.is_file());
2509 check!(fs::remove_dir(dir));
2513 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2514 let tmpdir = tmpdir();
2515 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2516 check!(check!(File::create(file)).write(b"foo"));
2517 assert!(file.exists());
2518 check!(fs::remove_file(file));
2519 assert!(!file.exists());
2523 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2524 let tmpdir = tmpdir();
2525 let dir = &tmpdir.join("before_and_after_dir");
2526 assert!(!dir.exists());
2527 check!(fs::create_dir(dir));
2528 assert!(dir.exists());
2529 assert!(dir.is_dir());
2530 check!(fs::remove_dir(dir));
2531 assert!(!dir.exists());
2535 fn file_test_directoryinfo_readdir() {
2536 let tmpdir = tmpdir();
2537 let dir = &tmpdir.join("di_readdir");
2538 check!(fs::create_dir(dir));
2541 let f = dir.join(&format!("{}.txt", n));
2542 let mut w = check!(File::create(&f));
2543 let msg_str = format!("{}{}", prefix, n.to_string());
2544 let msg = msg_str.as_bytes();
2545 check!(w.write(msg));
2547 let files = check!(fs::read_dir(dir));
2548 let mut mem = [0; 4];
2550 let f = f.unwrap().path();
2552 let n = f.file_stem().unwrap();
2553 check!(check!(File::open(&f)).read(&mut mem));
2554 let read_str = str::from_utf8(&mem).unwrap();
2555 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2556 assert_eq!(expected, read_str);
2558 check!(fs::remove_file(&f));
2560 check!(fs::remove_dir(dir));
2564 fn file_create_new_already_exists_error() {
2565 let tmpdir = tmpdir();
2566 let file = &tmpdir.join("file_create_new_error_exists");
2567 check!(fs::File::create(file));
2568 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2569 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2573 fn mkdir_path_already_exists_error() {
2574 let tmpdir = tmpdir();
2575 let dir = &tmpdir.join("mkdir_error_twice");
2576 check!(fs::create_dir(dir));
2577 let e = fs::create_dir(dir).unwrap_err();
2578 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2582 fn recursive_mkdir() {
2583 let tmpdir = tmpdir();
2584 let dir = tmpdir.join("d1/d2");
2585 check!(fs::create_dir_all(&dir));
2586 assert!(dir.is_dir())
2590 fn recursive_mkdir_failure() {
2591 let tmpdir = tmpdir();
2592 let dir = tmpdir.join("d1");
2593 let file = dir.join("f1");
2595 check!(fs::create_dir_all(&dir));
2596 check!(File::create(&file));
2598 let result = fs::create_dir_all(&file);
2600 assert!(result.is_err());
2604 fn concurrent_recursive_mkdir() {
2607 let mut dir = dir.join("a");
2609 dir = dir.join("a");
2611 let mut join = vec!();
2613 let dir = dir.clone();
2614 join.push(thread::spawn(move || {
2615 check!(fs::create_dir_all(&dir));
2619 // No `Display` on result of `join()`
2620 join.drain(..).map(|join| join.join().unwrap()).count();
2625 fn recursive_mkdir_slash() {
2626 check!(fs::create_dir_all(Path::new("/")));
2630 fn recursive_mkdir_dot() {
2631 check!(fs::create_dir_all(Path::new(".")));
2635 fn recursive_mkdir_empty() {
2636 check!(fs::create_dir_all(Path::new("")));
2640 fn recursive_rmdir() {
2641 let tmpdir = tmpdir();
2642 let d1 = tmpdir.join("d1");
2643 let dt = d1.join("t");
2644 let dtt = dt.join("t");
2645 let d2 = tmpdir.join("d2");
2646 let canary = d2.join("do_not_delete");
2647 check!(fs::create_dir_all(&dtt));
2648 check!(fs::create_dir_all(&d2));
2649 check!(check!(File::create(&canary)).write(b"foo"));
2650 check!(symlink_junction(&d2, &dt.join("d2")));
2651 let _ = symlink_file(&canary, &d1.join("canary"));
2652 check!(fs::remove_dir_all(&d1));
2654 assert!(!d1.is_dir());
2655 assert!(canary.exists());
2659 fn recursive_rmdir_of_symlink() {
2660 // test we do not recursively delete a symlink but only dirs.
2661 let tmpdir = tmpdir();
2662 let link = tmpdir.join("d1");
2663 let dir = tmpdir.join("d2");
2664 let canary = dir.join("do_not_delete");
2665 check!(fs::create_dir_all(&dir));
2666 check!(check!(File::create(&canary)).write(b"foo"));
2667 check!(symlink_junction(&dir, &link));
2668 check!(fs::remove_dir_all(&link));
2670 assert!(!link.is_dir());
2671 assert!(canary.exists());
2675 // only Windows makes a distinction between file and directory symlinks.
2677 fn recursive_rmdir_of_file_symlink() {
2678 let tmpdir = tmpdir();
2679 if !got_symlink_permission(&tmpdir) { return };
2681 let f1 = tmpdir.join("f1");
2682 let f2 = tmpdir.join("f2");
2683 check!(check!(File::create(&f1)).write(b"foo"));
2684 check!(symlink_file(&f1, &f2));
2685 match fs::remove_dir_all(&f2) {
2686 Ok(..) => panic!("wanted a failure"),
2692 fn unicode_path_is_dir() {
2693 assert!(Path::new(".").is_dir());
2694 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2696 let tmpdir = tmpdir();
2698 let mut dirpath = tmpdir.path().to_path_buf();
2699 dirpath.push("test-가一ー你好");
2700 check!(fs::create_dir(&dirpath));
2701 assert!(dirpath.is_dir());
2703 let mut filepath = dirpath;
2704 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2705 check!(File::create(&filepath)); // ignore return; touch only
2706 assert!(!filepath.is_dir());
2707 assert!(filepath.exists());
2711 fn unicode_path_exists() {
2712 assert!(Path::new(".").exists());
2713 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2715 let tmpdir = tmpdir();
2716 let unicode = tmpdir.path();
2717 let unicode = unicode.join("test-각丁ー再见");
2718 check!(fs::create_dir(&unicode));
2719 assert!(unicode.exists());
2720 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2724 fn copy_file_does_not_exist() {
2725 let from = Path::new("test/nonexistent-bogus-path");
2726 let to = Path::new("test/other-bogus-path");
2728 match fs::copy(&from, &to) {
2731 assert!(!from.exists());
2732 assert!(!to.exists());
2738 fn copy_src_does_not_exist() {
2739 let tmpdir = tmpdir();
2740 let from = Path::new("test/nonexistent-bogus-path");
2741 let to = tmpdir.join("out.txt");
2742 check!(check!(File::create(&to)).write(b"hello"));
2743 assert!(fs::copy(&from, &to).is_err());
2744 assert!(!from.exists());
2745 let mut v = Vec::new();
2746 check!(check!(File::open(&to)).read_to_end(&mut v));
2747 assert_eq!(v, b"hello");
2752 let tmpdir = tmpdir();
2753 let input = tmpdir.join("in.txt");
2754 let out = tmpdir.join("out.txt");
2756 check!(check!(File::create(&input)).write(b"hello"));
2757 check!(fs::copy(&input, &out));
2758 let mut v = Vec::new();
2759 check!(check!(File::open(&out)).read_to_end(&mut v));
2760 assert_eq!(v, b"hello");
2762 assert_eq!(check!(input.metadata()).permissions(),
2763 check!(out.metadata()).permissions());
2767 fn copy_file_dst_dir() {
2768 let tmpdir = tmpdir();
2769 let out = tmpdir.join("out");
2771 check!(File::create(&out));
2772 match fs::copy(&*out, tmpdir.path()) {
2773 Ok(..) => panic!(), Err(..) => {}
2778 fn copy_file_dst_exists() {
2779 let tmpdir = tmpdir();
2780 let input = tmpdir.join("in");
2781 let output = tmpdir.join("out");
2783 check!(check!(File::create(&input)).write("foo".as_bytes()));
2784 check!(check!(File::create(&output)).write("bar".as_bytes()));
2785 check!(fs::copy(&input, &output));
2787 let mut v = Vec::new();
2788 check!(check!(File::open(&output)).read_to_end(&mut v));
2789 assert_eq!(v, b"foo".to_vec());
2793 fn copy_file_src_dir() {
2794 let tmpdir = tmpdir();
2795 let out = tmpdir.join("out");
2797 match fs::copy(tmpdir.path(), &out) {
2798 Ok(..) => panic!(), Err(..) => {}
2800 assert!(!out.exists());
2804 fn copy_file_preserves_perm_bits() {
2805 let tmpdir = tmpdir();
2806 let input = tmpdir.join("in.txt");
2807 let out = tmpdir.join("out.txt");
2809 let attr = check!(check!(File::create(&input)).metadata());
2810 let mut p = attr.permissions();
2811 p.set_readonly(true);
2812 check!(fs::set_permissions(&input, p));
2813 check!(fs::copy(&input, &out));
2814 assert!(check!(out.metadata()).permissions().readonly());
2815 check!(fs::set_permissions(&input, attr.permissions()));
2816 check!(fs::set_permissions(&out, attr.permissions()));
2821 fn copy_file_preserves_streams() {
2823 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2824 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2825 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2826 let mut v = Vec::new();
2827 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2828 assert_eq!(v, b"carrot".to_vec());
2832 fn copy_file_returns_metadata_len() {
2834 let in_path = tmp.join("in.txt");
2835 let out_path = tmp.join("out.txt");
2836 check!(check!(File::create(&in_path)).write(b"lettuce"));
2838 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2839 let copied_len = check!(fs::copy(&in_path, &out_path));
2840 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2844 fn copy_file_follows_dst_symlink() {
2846 if !got_symlink_permission(&tmp) { return };
2848 let in_path = tmp.join("in.txt");
2849 let out_path = tmp.join("out.txt");
2850 let out_path_symlink = tmp.join("out_symlink.txt");
2852 check!(fs::write(&in_path, "foo"));
2853 check!(fs::write(&out_path, "bar"));
2854 check!(symlink_file(&out_path, &out_path_symlink));
2856 check!(fs::copy(&in_path, &out_path_symlink));
2858 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
2859 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
2860 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
2864 fn symlinks_work() {
2865 let tmpdir = tmpdir();
2866 if !got_symlink_permission(&tmpdir) { return };
2868 let input = tmpdir.join("in.txt");
2869 let out = tmpdir.join("out.txt");
2871 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2872 check!(symlink_file(&input, &out));
2873 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2874 assert_eq!(check!(fs::metadata(&out)).len(),
2875 check!(fs::metadata(&input)).len());
2876 let mut v = Vec::new();
2877 check!(check!(File::open(&out)).read_to_end(&mut v));
2878 assert_eq!(v, b"foobar".to_vec());
2882 fn symlink_noexist() {
2883 // Symlinks can point to things that don't exist
2884 let tmpdir = tmpdir();
2885 if !got_symlink_permission(&tmpdir) { return };
2887 // Use a relative path for testing. Symlinks get normalized by Windows,
2888 // so we may not get the same path back for absolute paths
2889 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2890 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2897 // directory symlink
2898 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2901 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2902 r"C:\Users\Default");
2903 // junction with special permissions
2904 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2907 let tmpdir = tmpdir();
2908 let link = tmpdir.join("link");
2909 if !got_symlink_permission(&tmpdir) { return };
2910 check!(symlink_file(&"foo", &link));
2911 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2915 fn readlink_not_symlink() {
2916 let tmpdir = tmpdir();
2917 match fs::read_link(tmpdir.path()) {
2918 Ok(..) => panic!("wanted a failure"),
2925 let tmpdir = tmpdir();
2926 let input = tmpdir.join("in.txt");
2927 let out = tmpdir.join("out.txt");
2929 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2930 check!(fs::hard_link(&input, &out));
2931 assert_eq!(check!(fs::metadata(&out)).len(),
2932 check!(fs::metadata(&input)).len());
2933 assert_eq!(check!(fs::metadata(&out)).len(),
2934 check!(input.metadata()).len());
2935 let mut v = Vec::new();
2936 check!(check!(File::open(&out)).read_to_end(&mut v));
2937 assert_eq!(v, b"foobar".to_vec());
2939 // can't link to yourself
2940 match fs::hard_link(&input, &input) {
2941 Ok(..) => panic!("wanted a failure"),
2944 // can't link to something that doesn't exist
2945 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2946 Ok(..) => panic!("wanted a failure"),
2953 let tmpdir = tmpdir();
2954 let file = tmpdir.join("in.txt");
2956 check!(File::create(&file));
2957 let attr = check!(fs::metadata(&file));
2958 assert!(!attr.permissions().readonly());
2959 let mut p = attr.permissions();
2960 p.set_readonly(true);
2961 check!(fs::set_permissions(&file, p.clone()));
2962 let attr = check!(fs::metadata(&file));
2963 assert!(attr.permissions().readonly());
2965 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2966 Ok(..) => panic!("wanted an error"),
2970 p.set_readonly(false);
2971 check!(fs::set_permissions(&file, p));
2976 let tmpdir = tmpdir();
2977 let path = tmpdir.join("in.txt");
2979 let file = check!(File::create(&path));
2980 let attr = check!(fs::metadata(&path));
2981 assert!(!attr.permissions().readonly());
2982 let mut p = attr.permissions();
2983 p.set_readonly(true);
2984 check!(file.set_permissions(p.clone()));
2985 let attr = check!(fs::metadata(&path));
2986 assert!(attr.permissions().readonly());
2988 p.set_readonly(false);
2989 check!(file.set_permissions(p));
2993 fn sync_doesnt_kill_anything() {
2994 let tmpdir = tmpdir();
2995 let path = tmpdir.join("in.txt");
2997 let mut file = check!(File::create(&path));
2998 check!(file.sync_all());
2999 check!(file.sync_data());
3000 check!(file.write(b"foo"));
3001 check!(file.sync_all());
3002 check!(file.sync_data());
3006 fn truncate_works() {
3007 let tmpdir = tmpdir();
3008 let path = tmpdir.join("in.txt");
3010 let mut file = check!(File::create(&path));
3011 check!(file.write(b"foo"));
3012 check!(file.sync_all());
3014 // Do some simple things with truncation
3015 assert_eq!(check!(file.metadata()).len(), 3);
3016 check!(file.set_len(10));
3017 assert_eq!(check!(file.metadata()).len(), 10);
3018 check!(file.write(b"bar"));
3019 check!(file.sync_all());
3020 assert_eq!(check!(file.metadata()).len(), 10);
3022 let mut v = Vec::new();
3023 check!(check!(File::open(&path)).read_to_end(&mut v));
3024 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3026 // Truncate to a smaller length, don't seek, and then write something.
3027 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3028 // past the end of the file).
3029 check!(file.set_len(2));
3030 assert_eq!(check!(file.metadata()).len(), 2);
3031 check!(file.write(b"wut"));
3032 check!(file.sync_all());
3033 assert_eq!(check!(file.metadata()).len(), 9);
3034 let mut v = Vec::new();
3035 check!(check!(File::open(&path)).read_to_end(&mut v));
3036 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3041 use crate::fs::OpenOptions as OO;
3042 fn c<T: Clone>(t: &T) -> T { t.clone() }
3044 let tmpdir = tmpdir();
3046 let mut r = OO::new(); r.read(true);
3047 let mut w = OO::new(); w.write(true);
3048 let mut rw = OO::new(); rw.read(true).write(true);
3049 let mut a = OO::new(); a.append(true);
3050 let mut ra = OO::new(); ra.read(true).append(true);
3053 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3055 let invalid_options = "Invalid argument";
3057 // Test various combinations of creation modes and access modes.
3060 // creation mode | read | write | read-write | append | read-append |
3061 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3062 // not set (open existing) | X | X | X | X | X |
3063 // create | | X | X | X | X |
3064 // truncate | | X | X | | |
3065 // create and truncate | | X | X | | |
3066 // create_new | | X | X | X | X |
3068 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3071 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3072 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3073 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3074 check!(c(&w).create(true).open(&tmpdir.join("a")));
3075 check!(c(&w).open(&tmpdir.join("a")));
3078 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3079 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3080 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3081 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3082 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3085 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3086 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3087 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3088 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3089 check!(c(&rw).open(&tmpdir.join("c")));
3092 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3093 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3094 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3095 check!(c(&a).create(true).open(&tmpdir.join("d")));
3096 check!(c(&a).open(&tmpdir.join("d")));
3099 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3100 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3101 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3102 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3103 check!(c(&ra).open(&tmpdir.join("e")));
3105 // Test opening a file without setting an access mode
3106 let mut blank = OO::new();
3107 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3110 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3112 // Test write fails for read-only
3113 check!(r.open(&tmpdir.join("h")));
3115 let mut f = check!(r.open(&tmpdir.join("h")));
3116 assert!(f.write("wut".as_bytes()).is_err());
3119 // Test write overwrites
3121 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3122 check!(f.write("baz".as_bytes()));
3125 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3126 let mut b = vec![0; 6];
3127 check!(f.read(&mut b));
3128 assert_eq!(b, "bazbar".as_bytes());
3131 // Test truncate works
3133 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3134 check!(f.write("foo".as_bytes()));
3136 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3138 // Test append works
3139 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3141 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3142 check!(f.write("bar".as_bytes()));
3144 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3146 // Test .append(true) equals .write(true).append(true)
3148 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3149 check!(f.write("baz".as_bytes()));
3151 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3155 fn _assert_send_sync() {
3156 fn _assert_send_sync<T: Send + Sync>() {}
3157 _assert_send_sync::<OpenOptions>();
3162 let mut bytes = [0; 1024];
3163 StdRng::from_entropy().fill_bytes(&mut bytes);
3165 let tmpdir = tmpdir();
3167 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3168 let mut v = Vec::new();
3169 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3170 assert!(v == &bytes[..]);
3174 fn write_then_read() {
3175 let mut bytes = [0; 1024];
3176 StdRng::from_entropy().fill_bytes(&mut bytes);
3178 let tmpdir = tmpdir();
3180 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3181 let v = check!(fs::read(&tmpdir.join("test")));
3182 assert!(v == &bytes[..]);
3184 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3185 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3186 "stream did not contain valid UTF-8");
3189 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3190 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3191 assert_eq!(string, s);
3195 fn file_try_clone() {
3196 let tmpdir = tmpdir();
3198 let mut f1 = check!(OpenOptions::new()
3202 .open(&tmpdir.join("test")));
3203 let mut f2 = check!(f1.try_clone());
3205 check!(f1.write_all(b"hello world"));
3206 check!(f1.seek(SeekFrom::Start(2)));
3208 let mut buf = vec![];
3209 check!(f2.read_to_end(&mut buf));
3210 assert_eq!(buf, b"llo world");
3213 check!(f1.write_all(b"!"));
3217 #[cfg(not(windows))]
3218 fn unlink_readonly() {
3219 let tmpdir = tmpdir();
3220 let path = tmpdir.join("file");
3221 check!(File::create(&path));
3222 let mut perm = check!(fs::metadata(&path)).permissions();
3223 perm.set_readonly(true);
3224 check!(fs::set_permissions(&path, perm));
3225 check!(fs::remove_file(&path));
3229 fn mkdir_trailing_slash() {
3230 let tmpdir = tmpdir();
3231 let path = tmpdir.join("file");
3232 check!(fs::create_dir_all(&path.join("a/")));
3236 fn canonicalize_works_simple() {
3237 let tmpdir = tmpdir();
3238 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3239 let file = tmpdir.join("test");
3240 File::create(&file).unwrap();
3241 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3245 fn realpath_works() {
3246 let tmpdir = tmpdir();
3247 if !got_symlink_permission(&tmpdir) { return };
3249 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3250 let file = tmpdir.join("test");
3251 let dir = tmpdir.join("test2");
3252 let link = dir.join("link");
3253 let linkdir = tmpdir.join("test3");
3255 File::create(&file).unwrap();
3256 fs::create_dir(&dir).unwrap();
3257 symlink_file(&file, &link).unwrap();
3258 symlink_dir(&dir, &linkdir).unwrap();
3260 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3262 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3263 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3264 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3265 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3266 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3270 fn realpath_works_tricky() {
3271 let tmpdir = tmpdir();
3272 if !got_symlink_permission(&tmpdir) { return };
3274 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3275 let a = tmpdir.join("a");
3276 let b = a.join("b");
3277 let c = b.join("c");
3278 let d = a.join("d");
3279 let e = d.join("e");
3280 let f = a.join("f");
3282 fs::create_dir_all(&b).unwrap();
3283 fs::create_dir_all(&d).unwrap();
3284 File::create(&f).unwrap();
3285 if cfg!(not(windows)) {
3286 symlink_dir("../d/e", &c).unwrap();
3287 symlink_file("../f", &e).unwrap();
3290 symlink_dir(r"..\d\e", &c).unwrap();
3291 symlink_file(r"..\f", &e).unwrap();
3294 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3295 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3299 fn dir_entry_methods() {
3300 let tmpdir = tmpdir();
3302 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3303 File::create(&tmpdir.join("b")).unwrap();
3305 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3306 let fname = file.file_name();
3307 match fname.to_str() {
3309 assert!(file.file_type().unwrap().is_dir());
3310 assert!(file.metadata().unwrap().is_dir());
3313 assert!(file.file_type().unwrap().is_file());
3314 assert!(file.metadata().unwrap().is_file());
3316 f => panic!("unknown file name: {:?}", f),
3322 fn dir_entry_debug() {
3323 let tmpdir = tmpdir();
3324 File::create(&tmpdir.join("b")).unwrap();
3325 let mut read_dir = tmpdir.path().read_dir().unwrap();
3326 let dir_entry = read_dir.next().unwrap().unwrap();
3327 let actual = format!("{:?}", dir_entry);
3328 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3329 assert_eq!(actual, expected);
3333 fn read_dir_not_found() {
3334 let res = fs::read_dir("/path/that/does/not/exist");
3335 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3339 fn create_dir_all_with_junctions() {
3340 let tmpdir = tmpdir();
3341 let target = tmpdir.join("target");
3343 let junction = tmpdir.join("junction");
3344 let b = junction.join("a/b");
3346 let link = tmpdir.join("link");
3347 let d = link.join("c/d");
3349 fs::create_dir(&target).unwrap();
3351 check!(symlink_junction(&target, &junction));
3352 check!(fs::create_dir_all(&b));
3353 // the junction itself is not a directory, but `is_dir()` on a Path
3355 assert!(junction.is_dir());
3356 assert!(b.exists());
3358 if !got_symlink_permission(&tmpdir) { return };
3359 check!(symlink_dir(&target, &link));
3360 check!(fs::create_dir_all(&d));
3361 assert!(link.is_dir());
3362 assert!(d.exists());
3366 fn metadata_access_times() {
3367 let tmpdir = tmpdir();
3369 let b = tmpdir.join("b");
3370 File::create(&b).unwrap();
3372 let a = check!(fs::metadata(&tmpdir.path()));
3373 let b = check!(fs::metadata(&b));
3375 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3376 assert_eq!(check!(a.modified()), check!(a.modified()));
3377 assert_eq!(check!(b.accessed()), check!(b.modified()));
3379 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3380 check!(a.created());
3381 check!(b.created());