1 // ignore-tidy-filelength
3 //! Filesystem manipulation operations.
5 //! This module contains basic methods to manipulate the contents of the local
6 //! filesystem. All methods in this module represent cross-platform filesystem
7 //! operations. Extra platform-specific functionality can be found in the
8 //! extension traits of `std::os::$platform`.
10 #![stable(feature = "rust1", since = "1.0.0")]
11 #![deny(unsafe_op_in_unsafe_fn)]
13 use crate::ffi::OsString;
15 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
16 use crate::path::{Path, PathBuf};
17 use crate::sys::fs as fs_imp;
18 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
19 use crate::time::SystemTime;
21 /// A reference to an open file on the filesystem.
23 /// An instance of a `File` can be read and/or written depending on what options
24 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
25 /// that the file contains internally.
27 /// Files are automatically closed when they go out of scope. Errors detected
28 /// on closing are ignored by the implementation of `Drop`. Use the method
29 /// [`sync_all`] if these errors must be manually handled.
33 /// Creates a new file and write bytes to it (you can also use [`write`]):
36 /// use std::fs::File;
37 /// use std::io::prelude::*;
39 /// fn main() -> std::io::Result<()> {
40 /// let mut file = File::create("foo.txt")?;
41 /// file.write_all(b"Hello, world!")?;
46 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
49 /// use std::fs::File;
50 /// use std::io::prelude::*;
52 /// fn main() -> std::io::Result<()> {
53 /// let mut file = File::open("foo.txt")?;
54 /// let mut contents = String::new();
55 /// file.read_to_string(&mut contents)?;
56 /// assert_eq!(contents, "Hello, world!");
61 /// It can be more efficient to read the contents of a file with a buffered
62 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
65 /// use std::fs::File;
66 /// use std::io::BufReader;
67 /// use std::io::prelude::*;
69 /// fn main() -> std::io::Result<()> {
70 /// let file = File::open("foo.txt")?;
71 /// let mut buf_reader = BufReader::new(file);
72 /// let mut contents = String::new();
73 /// buf_reader.read_to_string(&mut contents)?;
74 /// assert_eq!(contents, "Hello, world!");
79 /// Note that, although read and write methods require a `&mut File`, because
80 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
81 /// still modify the file, either through methods that take `&File` or by
82 /// retrieving the underlying OS object and modifying the file that way.
83 /// Additionally, many operating systems allow concurrent modification of files
84 /// by different processes. Avoid assuming that holding a `&File` means that the
85 /// file will not change.
87 /// [`Seek`]: ../io/trait.Seek.html
88 /// [`String`]: ../string/struct.String.html
89 /// [`Read`]: ../io/trait.Read.html
90 /// [`Write`]: ../io/trait.Write.html
91 /// [`BufReader<R>`]: ../io/struct.BufReader.html
92 /// [`sync_all`]: struct.File.html#method.sync_all
93 /// [`read`]: fn.read.html
94 /// [`write`]: fn.write.html
95 #[stable(feature = "rust1", since = "1.0.0")]
100 /// Metadata information about a file.
102 /// This structure is returned from the [`metadata`] or
103 /// [`symlink_metadata`] function or method and represents known
104 /// metadata about a file such as its permissions, size, modification
107 /// [`metadata`]: fn.metadata.html
108 /// [`symlink_metadata`]: fn.symlink_metadata.html
109 #[stable(feature = "rust1", since = "1.0.0")]
111 pub struct Metadata(fs_imp::FileAttr);
113 /// Iterator over the entries in a directory.
115 /// This iterator is returned from the [`read_dir`] function of this module and
116 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
117 /// information like the entry's path and possibly other metadata can be
120 /// The order in which this iterator returns entries is platform and filesystem
125 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
126 /// IO error during iteration.
128 /// [`read_dir`]: fn.read_dir.html
129 /// [`DirEntry`]: struct.DirEntry.html
130 /// [`io::Result`]: ../io/type.Result.html
131 /// [`Err`]: ../result/enum.Result.html#variant.Err
132 #[stable(feature = "rust1", since = "1.0.0")]
134 pub struct ReadDir(fs_imp::ReadDir);
136 /// Entries returned by the [`ReadDir`] iterator.
138 /// [`ReadDir`]: struct.ReadDir.html
140 /// An instance of `DirEntry` represents an entry inside of a directory on the
141 /// filesystem. Each entry can be inspected via methods to learn about the full
142 /// path or possibly other metadata through per-platform extension traits.
143 #[stable(feature = "rust1", since = "1.0.0")]
144 pub struct DirEntry(fs_imp::DirEntry);
146 /// Options and flags which can be used to configure how a file is opened.
148 /// This builder exposes the ability to configure how a [`File`] is opened and
149 /// what operations are permitted on the open file. The [`File::open`] and
150 /// [`File::create`] methods are aliases for commonly used options using this
153 /// [`File`]: struct.File.html
154 /// [`File::open`]: struct.File.html#method.open
155 /// [`File::create`]: struct.File.html#method.create
157 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
158 /// then chain calls to methods to set each option, then call [`open`],
159 /// passing the path of the file you're trying to open. This will give you a
160 /// [`io::Result`][result] with a [`File`][file] inside that you can further
163 /// [`new`]: struct.OpenOptions.html#method.new
164 /// [`open`]: struct.OpenOptions.html#method.open
165 /// [result]: ../io/type.Result.html
166 /// [file]: struct.File.html
170 /// Opening a file to read:
173 /// use std::fs::OpenOptions;
175 /// let file = OpenOptions::new().read(true).open("foo.txt");
178 /// Opening a file for both reading and writing, as well as creating it if it
182 /// use std::fs::OpenOptions;
184 /// let file = OpenOptions::new()
188 /// .open("foo.txt");
190 #[derive(Clone, Debug)]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct OpenOptions(fs_imp::OpenOptions);
194 /// Representation of the various permissions on a file.
196 /// This module only currently provides one bit of information, [`readonly`],
197 /// which is exposed on all currently supported platforms. Unix-specific
198 /// functionality, such as mode bits, is available through the
199 /// [`PermissionsExt`] trait.
201 /// [`readonly`]: struct.Permissions.html#method.readonly
202 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Permissions(fs_imp::FilePermissions);
207 /// A structure representing a type of file with accessors for each file type.
208 /// It is returned by [`Metadata::file_type`] method.
210 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
211 #[stable(feature = "file_type", since = "1.1.0")]
212 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
213 pub struct FileType(fs_imp::FileType);
215 /// A builder used to create directories in various manners.
217 /// This builder also supports platform-specific options.
218 #[stable(feature = "dir_builder", since = "1.6.0")]
220 pub struct DirBuilder {
221 inner: fs_imp::DirBuilder,
225 /// Indicates how large a buffer to pre-allocate before reading the entire file.
226 fn initial_buffer_size(file: &File) -> usize {
227 // Allocate one extra byte so the buffer doesn't need to grow before the
228 // final `read` call at the end of the file. Don't worry about `usize`
229 // overflow because reading will fail regardless in that case.
230 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
233 /// Read the entire contents of a file into a bytes vector.
235 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
236 /// with fewer imports and without an intermediate variable. It pre-allocates a
237 /// buffer based on the file size when available, so it is generally faster than
238 /// reading into a vector created with `Vec::new()`.
240 /// [`File::open`]: struct.File.html#method.open
241 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
245 /// This function will return an error if `path` does not already exist.
246 /// Other errors may also be returned according to [`OpenOptions::open`].
248 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
250 /// It will also return an error if it encounters while reading an error
251 /// of a kind other than [`ErrorKind::Interrupted`].
253 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
259 /// use std::net::SocketAddr;
261 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
262 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
266 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
267 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
268 fn inner(path: &Path) -> io::Result<Vec<u8>> {
269 let mut file = File::open(path)?;
270 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
271 file.read_to_end(&mut bytes)?;
277 /// Read the entire contents of a file into a string.
279 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
280 /// with fewer imports and without an intermediate variable. It pre-allocates a
281 /// buffer based on the file size when available, so it is generally faster than
282 /// reading into a string created with `String::new()`.
284 /// [`File::open`]: struct.File.html#method.open
285 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
289 /// This function will return an error if `path` does not already exist.
290 /// Other errors may also be returned according to [`OpenOptions::open`].
292 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
294 /// It will also return an error if it encounters while reading an error
295 /// of a kind other than [`ErrorKind::Interrupted`],
296 /// or if the contents of the file are not valid UTF-8.
298 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
304 /// use std::net::SocketAddr;
306 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
307 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
311 #[stable(feature = "fs_read_write", since = "1.26.0")]
312 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
313 fn inner(path: &Path) -> io::Result<String> {
314 let mut file = File::open(path)?;
315 let mut string = String::with_capacity(initial_buffer_size(&file));
316 file.read_to_string(&mut string)?;
322 /// Write a slice as the entire contents of a file.
324 /// This function will create a file if it does not exist,
325 /// and will entirely replace its contents if it does.
327 /// This is a convenience function for using [`File::create`] and [`write_all`]
328 /// with fewer imports.
330 /// [`File::create`]: struct.File.html#method.create
331 /// [`write_all`]: ../io/trait.Write.html#method.write_all
338 /// fn main() -> std::io::Result<()> {
339 /// fs::write("foo.txt", b"Lorem ipsum")?;
340 /// fs::write("bar.txt", "dolor sit")?;
344 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
345 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
346 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
347 File::create(path)?.write_all(contents)
349 inner(path.as_ref(), contents.as_ref())
353 /// Attempts to open a file in read-only mode.
355 /// See the [`OpenOptions::open`] method for more details.
359 /// This function will return an error if `path` does not already exist.
360 /// Other errors may also be returned according to [`OpenOptions::open`].
362 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
367 /// use std::fs::File;
369 /// fn main() -> std::io::Result<()> {
370 /// let mut f = File::open("foo.txt")?;
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
376 OpenOptions::new().read(true).open(path.as_ref())
379 /// Opens a file in write-only mode.
381 /// This function will create a file if it does not exist,
382 /// and will truncate it if it does.
384 /// See the [`OpenOptions::open`] function for more details.
386 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
391 /// use std::fs::File;
393 /// fn main() -> std::io::Result<()> {
394 /// let mut f = File::create("foo.txt")?;
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
400 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
403 /// Returns a new OpenOptions object.
405 /// This function returns a new OpenOptions object that you can use to
406 /// open or create a file with specific options if `open()` or `create()`
407 /// are not appropriate.
409 /// It is equivalent to `OpenOptions::new()` but allows you to write more
410 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
411 /// you can write `File::with_options().read(true).open("foo.txt")`. This
412 /// also avoids the need to import `OpenOptions`.
414 /// See the [`OpenOptions::new`] function for more details.
416 /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
421 /// #![feature(with_options)]
422 /// use std::fs::File;
424 /// fn main() -> std::io::Result<()> {
425 /// let mut f = File::with_options().read(true).open("foo.txt")?;
429 #[unstable(feature = "with_options", issue = "65439")]
430 pub fn with_options() -> OpenOptions {
434 /// Attempts to sync all OS-internal metadata to disk.
436 /// This function will attempt to ensure that all in-memory data reaches the
437 /// filesystem before returning.
439 /// This can be used to handle errors that would otherwise only be caught
440 /// when the `File` is closed. Dropping a file will ignore errors in
441 /// synchronizing this in-memory data.
446 /// use std::fs::File;
447 /// use std::io::prelude::*;
449 /// fn main() -> std::io::Result<()> {
450 /// let mut f = File::create("foo.txt")?;
451 /// f.write_all(b"Hello, world!")?;
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn sync_all(&self) -> io::Result<()> {
462 /// This function is similar to [`sync_all`], except that it may not
463 /// synchronize file metadata to the filesystem.
465 /// This is intended for use cases that must synchronize content, but don't
466 /// need the metadata on disk. The goal of this method is to reduce disk
469 /// Note that some platforms may simply implement this in terms of
472 /// [`sync_all`]: struct.File.html#method.sync_all
477 /// use std::fs::File;
478 /// use std::io::prelude::*;
480 /// fn main() -> std::io::Result<()> {
481 /// let mut f = File::create("foo.txt")?;
482 /// f.write_all(b"Hello, world!")?;
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn sync_data(&self) -> io::Result<()> {
490 self.inner.datasync()
493 /// Truncates or extends the underlying file, updating the size of
494 /// this file to become `size`.
496 /// If the `size` is less than the current file's size, then the file will
497 /// be shrunk. If it is greater than the current file's size, then the file
498 /// will be extended to `size` and have all of the intermediate data filled
501 /// The file's cursor isn't changed. In particular, if the cursor was at the
502 /// end and the file is shrunk using this operation, the cursor will now be
507 /// This function will return an error if the file is not opened for writing.
508 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
509 /// length would cause an overflow due to the implementation specifics.
514 /// use std::fs::File;
516 /// fn main() -> std::io::Result<()> {
517 /// let mut f = File::create("foo.txt")?;
523 /// Note that this method alters the content of the underlying file, even
524 /// though it takes `&self` rather than `&mut self`.
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn set_len(&self, size: u64) -> io::Result<()> {
527 self.inner.truncate(size)
530 /// Queries metadata about the underlying file.
535 /// use std::fs::File;
537 /// fn main() -> std::io::Result<()> {
538 /// let mut f = File::open("foo.txt")?;
539 /// let metadata = f.metadata()?;
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn metadata(&self) -> io::Result<Metadata> {
545 self.inner.file_attr().map(Metadata)
548 /// Creates a new `File` instance that shares the same underlying file handle
549 /// as the existing `File` instance. Reads, writes, and seeks will affect
550 /// both `File` instances simultaneously.
554 /// Creates two handles for a file named `foo.txt`:
557 /// use std::fs::File;
559 /// fn main() -> std::io::Result<()> {
560 /// let mut file = File::open("foo.txt")?;
561 /// let file_copy = file.try_clone()?;
566 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
567 /// two handles, seek one of them, and read the remaining bytes from the
571 /// use std::fs::File;
572 /// use std::io::SeekFrom;
573 /// use std::io::prelude::*;
575 /// fn main() -> std::io::Result<()> {
576 /// let mut file = File::open("foo.txt")?;
577 /// let mut file_copy = file.try_clone()?;
579 /// file.seek(SeekFrom::Start(3))?;
581 /// let mut contents = vec![];
582 /// file_copy.read_to_end(&mut contents)?;
583 /// assert_eq!(contents, b"def\n");
587 #[stable(feature = "file_try_clone", since = "1.9.0")]
588 pub fn try_clone(&self) -> io::Result<File> {
589 Ok(File { inner: self.inner.duplicate()? })
592 /// Changes the permissions on the underlying file.
594 /// # Platform-specific behavior
596 /// This function currently corresponds to the `fchmod` function on Unix and
597 /// the `SetFileInformationByHandle` function on Windows. Note that, this
598 /// [may change in the future][changes].
600 /// [changes]: ../io/index.html#platform-specific-behavior
604 /// This function will return an error if the user lacks permission change
605 /// attributes on the underlying file. It may also return an error in other
606 /// os-specific unspecified cases.
611 /// fn main() -> std::io::Result<()> {
612 /// use std::fs::File;
614 /// let file = File::open("foo.txt")?;
615 /// let mut perms = file.metadata()?.permissions();
616 /// perms.set_readonly(true);
617 /// file.set_permissions(perms)?;
622 /// Note that this method alters the permissions of the underlying file,
623 /// even though it takes `&self` rather than `&mut self`.
624 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
625 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
626 self.inner.set_permissions(perm.0)
630 impl AsInner<fs_imp::File> for File {
631 fn as_inner(&self) -> &fs_imp::File {
635 impl FromInner<fs_imp::File> for File {
636 fn from_inner(f: fs_imp::File) -> File {
640 impl IntoInner<fs_imp::File> for File {
641 fn into_inner(self) -> fs_imp::File {
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl fmt::Debug for File {
648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 #[stable(feature = "rust1", since = "1.0.0")]
655 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
659 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
660 self.inner.read_vectored(bufs)
664 fn is_read_vectored(&self) -> bool {
665 self.inner.is_read_vectored()
669 unsafe fn initializer(&self) -> Initializer {
670 // SAFETY: Read is guaranteed to work on uninitialized memory
671 unsafe { Initializer::nop() }
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl Write for File {
676 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
677 self.inner.write(buf)
680 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
681 self.inner.write_vectored(bufs)
685 fn is_write_vectored(&self) -> bool {
686 self.inner.is_write_vectored()
689 fn flush(&mut self) -> io::Result<()> {
693 #[stable(feature = "rust1", since = "1.0.0")]
695 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl Read for &File {
701 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
705 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
706 self.inner.read_vectored(bufs)
710 fn is_read_vectored(&self) -> bool {
711 self.inner.is_read_vectored()
715 unsafe fn initializer(&self) -> Initializer {
716 // SAFETY: Read is guaranteed to work on uninitialized memory
717 unsafe { Initializer::nop() }
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Write for &File {
722 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
723 self.inner.write(buf)
726 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
727 self.inner.write_vectored(bufs)
731 fn is_write_vectored(&self) -> bool {
732 self.inner.is_write_vectored()
735 fn flush(&mut self) -> io::Result<()> {
739 #[stable(feature = "rust1", since = "1.0.0")]
740 impl Seek for &File {
741 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
747 /// Creates a blank new set of options ready for configuration.
749 /// All options are initially set to `false`.
754 /// use std::fs::OpenOptions;
756 /// let mut options = OpenOptions::new();
757 /// let file = options.read(true).open("foo.txt");
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn new() -> Self {
761 OpenOptions(fs_imp::OpenOptions::new())
764 /// Sets the option for read access.
766 /// This option, when true, will indicate that the file should be
767 /// `read`-able if opened.
772 /// use std::fs::OpenOptions;
774 /// let file = OpenOptions::new().read(true).open("foo.txt");
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn read(&mut self, read: bool) -> &mut Self {
782 /// Sets the option for write access.
784 /// This option, when true, will indicate that the file should be
785 /// `write`-able if opened.
787 /// If the file already exists, any write calls on it will overwrite its
788 /// contents, without truncating it.
793 /// use std::fs::OpenOptions;
795 /// let file = OpenOptions::new().write(true).open("foo.txt");
797 #[stable(feature = "rust1", since = "1.0.0")]
798 pub fn write(&mut self, write: bool) -> &mut Self {
803 /// Sets the option for the append mode.
805 /// This option, when true, means that writes will append to a file instead
806 /// of overwriting previous contents.
807 /// Note that setting `.write(true).append(true)` has the same effect as
808 /// setting only `.append(true)`.
810 /// For most filesystems, the operating system guarantees that all writes are
811 /// atomic: no writes get mangled because another process writes at the same
814 /// One maybe obvious note when using append-mode: make sure that all data
815 /// that belongs together is written to the file in one operation. This
816 /// can be done by concatenating strings before passing them to [`write()`],
817 /// or using a buffered writer (with a buffer of adequate size),
818 /// and calling [`flush()`] when the message is complete.
820 /// If a file is opened with both read and append access, beware that after
821 /// opening, and after every write, the position for reading may be set at the
822 /// end of the file. So, before writing, save the current position (using
823 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
827 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
830 /// [`write()`]: ../../std/fs/struct.File.html#method.write
831 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
832 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
833 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
834 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
835 /// [`create`]: #method.create
840 /// use std::fs::OpenOptions;
842 /// let file = OpenOptions::new().append(true).open("foo.txt");
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn append(&mut self, append: bool) -> &mut Self {
846 self.0.append(append);
850 /// Sets the option for truncating a previous file.
852 /// If a file is successfully opened with this option set it will truncate
853 /// the file to 0 length if it already exists.
855 /// The file must be opened with write access for truncate to work.
860 /// use std::fs::OpenOptions;
862 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
866 self.0.truncate(truncate);
870 /// Sets the option to create a new file, or open it if it already exists.
872 /// In order for the file to be created, [`write`] or [`append`] access must
875 /// [`write`]: #method.write
876 /// [`append`]: #method.append
881 /// use std::fs::OpenOptions;
883 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn create(&mut self, create: bool) -> &mut Self {
887 self.0.create(create);
891 /// Sets the option to create a new file, failing if it already exists.
893 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
894 /// way, if the call succeeds, the file returned is guaranteed to be new.
896 /// This option is useful because it is atomic. Otherwise between checking
897 /// whether a file exists and creating a new one, the file may have been
898 /// created by another process (a TOCTOU race condition / attack).
900 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
903 /// The file must be opened with write or append access in order to create
906 /// [`.create()`]: #method.create
907 /// [`.truncate()`]: #method.truncate
912 /// use std::fs::OpenOptions;
914 /// let file = OpenOptions::new().write(true)
915 /// .create_new(true)
916 /// .open("foo.txt");
918 #[stable(feature = "expand_open_options2", since = "1.9.0")]
919 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
920 self.0.create_new(create_new);
924 /// Opens a file at `path` with the options specified by `self`.
928 /// This function will return an error under a number of different
929 /// circumstances. Some of these error conditions are listed here, together
930 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
931 /// the compatibility contract of the function, especially the `Other` kind
932 /// might change to more specific kinds in the future.
934 /// * [`NotFound`]: The specified file does not exist and neither `create`
935 /// or `create_new` is set.
936 /// * [`NotFound`]: One of the directory components of the file path does
938 /// * [`PermissionDenied`]: The user lacks permission to get the specified
939 /// access rights for the file.
940 /// * [`PermissionDenied`]: The user lacks permission to open one of the
941 /// directory components of the specified path.
942 /// * [`AlreadyExists`]: `create_new` was specified and the file already
944 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
945 /// without write access, no access mode set, etc.).
946 /// * [`Other`]: One of the directory components of the specified file path
947 /// was not, in fact, a directory.
948 /// * [`Other`]: Filesystem-level errors: full disk, write permission
949 /// requested on a read-only file system, exceeded disk quota, too many
950 /// open files, too long filename, too many symbolic links in the
951 /// specified path (Unix-like systems only), etc.
956 /// use std::fs::OpenOptions;
958 /// let file = OpenOptions::new().read(true).open("foo.txt");
961 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
962 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
963 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
964 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
965 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
966 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
969 self._open(path.as_ref())
972 fn _open(&self, path: &Path) -> io::Result<File> {
973 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
977 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
978 fn as_inner(&self) -> &fs_imp::OpenOptions {
983 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
984 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
990 /// Returns the file type for this metadata.
995 /// fn main() -> std::io::Result<()> {
998 /// let metadata = fs::metadata("foo.txt")?;
1000 /// println!("{:?}", metadata.file_type());
1004 #[stable(feature = "file_type", since = "1.1.0")]
1005 pub fn file_type(&self) -> FileType {
1006 FileType(self.0.file_type())
1009 /// Returns `true` if this metadata is for a directory. The
1010 /// result is mutually exclusive to the result of
1011 /// [`is_file`], and will be false for symlink metadata
1012 /// obtained from [`symlink_metadata`].
1014 /// [`is_file`]: struct.Metadata.html#method.is_file
1015 /// [`symlink_metadata`]: fn.symlink_metadata.html
1020 /// fn main() -> std::io::Result<()> {
1023 /// let metadata = fs::metadata("foo.txt")?;
1025 /// assert!(!metadata.is_dir());
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn is_dir(&self) -> bool {
1031 self.file_type().is_dir()
1034 /// Returns `true` if this metadata is for a regular file. The
1035 /// result is mutually exclusive to the result of
1036 /// [`is_dir`], and will be false for symlink metadata
1037 /// obtained from [`symlink_metadata`].
1039 /// When the goal is simply to read from (or write to) the source, the most
1040 /// reliable way to test the source can be read (or written to) is to open
1041 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1042 /// a Unix-like system for example. See [`File::open`] or
1043 /// [`OpenOptions::open`] for more information.
1045 /// [`is_dir`]: struct.Metadata.html#method.is_dir
1046 /// [`symlink_metadata`]: fn.symlink_metadata.html
1047 /// [`File::open`]: struct.File.html#method.open
1048 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1055 /// fn main() -> std::io::Result<()> {
1056 /// let metadata = fs::metadata("foo.txt")?;
1058 /// assert!(metadata.is_file());
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub fn is_file(&self) -> bool {
1064 self.file_type().is_file()
1067 /// Returns the size of the file, in bytes, this metadata is for.
1074 /// fn main() -> std::io::Result<()> {
1075 /// let metadata = fs::metadata("foo.txt")?;
1077 /// assert_eq!(0, metadata.len());
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn len(&self) -> u64 {
1086 /// Returns the permissions of the file this metadata is for.
1093 /// fn main() -> std::io::Result<()> {
1094 /// let metadata = fs::metadata("foo.txt")?;
1096 /// assert!(!metadata.permissions().readonly());
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn permissions(&self) -> Permissions {
1102 Permissions(self.0.perm())
1105 /// Returns the last modification time listed in this metadata.
1107 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1108 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1112 /// This field may not be available on all platforms, and will return an
1113 /// `Err` on platforms where it is not available.
1120 /// fn main() -> std::io::Result<()> {
1121 /// let metadata = fs::metadata("foo.txt")?;
1123 /// if let Ok(time) = metadata.modified() {
1124 /// println!("{:?}", time);
1126 /// println!("Not supported on this platform");
1131 #[stable(feature = "fs_time", since = "1.10.0")]
1132 pub fn modified(&self) -> io::Result<SystemTime> {
1133 self.0.modified().map(FromInner::from_inner)
1136 /// Returns the last access time of this metadata.
1138 /// The returned value corresponds to the `atime` field of `stat` on Unix
1139 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1141 /// Note that not all platforms will keep this field update in a file's
1142 /// metadata, for example Windows has an option to disable updating this
1143 /// time when files are accessed and Linux similarly has `noatime`.
1147 /// This field may not be available on all platforms, and will return an
1148 /// `Err` on platforms where it is not available.
1155 /// fn main() -> std::io::Result<()> {
1156 /// let metadata = fs::metadata("foo.txt")?;
1158 /// if let Ok(time) = metadata.accessed() {
1159 /// println!("{:?}", time);
1161 /// println!("Not supported on this platform");
1166 #[stable(feature = "fs_time", since = "1.10.0")]
1167 pub fn accessed(&self) -> io::Result<SystemTime> {
1168 self.0.accessed().map(FromInner::from_inner)
1171 /// Returns the creation time listed in this metadata.
1173 /// The returned value corresponds to the `btime` field of `statx` on
1174 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1175 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1179 /// This field may not be available on all platforms, and will return an
1180 /// `Err` on platforms or filesystems where it is not available.
1187 /// fn main() -> std::io::Result<()> {
1188 /// let metadata = fs::metadata("foo.txt")?;
1190 /// if let Ok(time) = metadata.created() {
1191 /// println!("{:?}", time);
1193 /// println!("Not supported on this platform or filesystem");
1198 #[stable(feature = "fs_time", since = "1.10.0")]
1199 pub fn created(&self) -> io::Result<SystemTime> {
1200 self.0.created().map(FromInner::from_inner)
1204 #[stable(feature = "std_debug", since = "1.16.0")]
1205 impl fmt::Debug for Metadata {
1206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207 f.debug_struct("Metadata")
1208 .field("file_type", &self.file_type())
1209 .field("is_dir", &self.is_dir())
1210 .field("is_file", &self.is_file())
1211 .field("permissions", &self.permissions())
1212 .field("modified", &self.modified())
1213 .field("accessed", &self.accessed())
1214 .field("created", &self.created())
1219 impl AsInner<fs_imp::FileAttr> for Metadata {
1220 fn as_inner(&self) -> &fs_imp::FileAttr {
1225 impl FromInner<fs_imp::FileAttr> for Metadata {
1226 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1232 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1237 /// use std::fs::File;
1239 /// fn main() -> std::io::Result<()> {
1240 /// let mut f = File::create("foo.txt")?;
1241 /// let metadata = f.metadata()?;
1243 /// assert_eq!(false, metadata.permissions().readonly());
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 pub fn readonly(&self) -> bool {
1252 /// Modifies the readonly flag for this set of permissions. If the
1253 /// `readonly` argument is `true`, using the resulting `Permission` will
1254 /// update file permissions to forbid writing. Conversely, if it's `false`,
1255 /// using the resulting `Permission` will update file permissions to allow
1258 /// This operation does **not** modify the filesystem. To modify the
1259 /// filesystem use the [`fs::set_permissions`] function.
1261 /// [`fs::set_permissions`]: fn.set_permissions.html
1266 /// use std::fs::File;
1268 /// fn main() -> std::io::Result<()> {
1269 /// let f = File::create("foo.txt")?;
1270 /// let metadata = f.metadata()?;
1271 /// let mut permissions = metadata.permissions();
1273 /// permissions.set_readonly(true);
1275 /// // filesystem doesn't change
1276 /// assert_eq!(false, metadata.permissions().readonly());
1278 /// // just this particular `permissions`.
1279 /// assert_eq!(true, permissions.readonly());
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn set_readonly(&mut self, readonly: bool) {
1285 self.0.set_readonly(readonly)
1290 /// Tests whether this file type represents a directory. The
1291 /// result is mutually exclusive to the results of
1292 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1295 /// [`is_file`]: struct.FileType.html#method.is_file
1296 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1301 /// fn main() -> std::io::Result<()> {
1304 /// let metadata = fs::metadata("foo.txt")?;
1305 /// let file_type = metadata.file_type();
1307 /// assert_eq!(file_type.is_dir(), false);
1311 #[stable(feature = "file_type", since = "1.1.0")]
1312 pub fn is_dir(&self) -> bool {
1316 /// Tests whether this file type represents a regular file.
1317 /// The result is mutually exclusive to the results of
1318 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1321 /// When the goal is simply to read from (or write to) the source, the most
1322 /// reliable way to test the source can be read (or written to) is to open
1323 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1324 /// a Unix-like system for example. See [`File::open`] or
1325 /// [`OpenOptions::open`] for more information.
1327 /// [`is_dir`]: struct.FileType.html#method.is_dir
1328 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1329 /// [`File::open`]: struct.File.html#method.open
1330 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1335 /// fn main() -> std::io::Result<()> {
1338 /// let metadata = fs::metadata("foo.txt")?;
1339 /// let file_type = metadata.file_type();
1341 /// assert_eq!(file_type.is_file(), true);
1345 #[stable(feature = "file_type", since = "1.1.0")]
1346 pub fn is_file(&self) -> bool {
1350 /// Tests whether this file type represents a symbolic link.
1351 /// The result is mutually exclusive to the results of
1352 /// [`is_dir`] and [`is_file`]; only zero or one of these
1355 /// The underlying [`Metadata`] struct needs to be retrieved
1356 /// with the [`fs::symlink_metadata`] function and not the
1357 /// [`fs::metadata`] function. The [`fs::metadata`] function
1358 /// follows symbolic links, so [`is_symlink`] would always
1359 /// return `false` for the target file.
1361 /// [`Metadata`]: struct.Metadata.html
1362 /// [`fs::metadata`]: fn.metadata.html
1363 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1364 /// [`is_dir`]: struct.FileType.html#method.is_dir
1365 /// [`is_file`]: struct.FileType.html#method.is_file
1366 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1373 /// fn main() -> std::io::Result<()> {
1374 /// let metadata = fs::symlink_metadata("foo.txt")?;
1375 /// let file_type = metadata.file_type();
1377 /// assert_eq!(file_type.is_symlink(), false);
1381 #[stable(feature = "file_type", since = "1.1.0")]
1382 pub fn is_symlink(&self) -> bool {
1387 impl AsInner<fs_imp::FileType> for FileType {
1388 fn as_inner(&self) -> &fs_imp::FileType {
1393 impl FromInner<fs_imp::FilePermissions> for Permissions {
1394 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1399 impl AsInner<fs_imp::FilePermissions> for Permissions {
1400 fn as_inner(&self) -> &fs_imp::FilePermissions {
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl Iterator for ReadDir {
1407 type Item = io::Result<DirEntry>;
1409 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1410 self.0.next().map(|entry| entry.map(DirEntry))
1415 /// Returns the full path to the file that this entry represents.
1417 /// The full path is created by joining the original path to `read_dir`
1418 /// with the filename of this entry.
1425 /// fn main() -> std::io::Result<()> {
1426 /// for entry in fs::read_dir(".")? {
1427 /// let dir = entry?;
1428 /// println!("{:?}", dir.path());
1434 /// This prints output like:
1437 /// "./whatever.txt"
1439 /// "./hello_world.rs"
1442 /// The exact text, of course, depends on what files you have in `.`.
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn path(&self) -> PathBuf {
1448 /// Returns the metadata for the file that this entry points at.
1450 /// This function will not traverse symlinks if this entry points at a
1451 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1453 /// [`fs::metadata`]: fn.metadata.html
1454 /// [`fs::File::metadata`]: struct.File.html#method.metadata
1456 /// # Platform-specific behavior
1458 /// On Windows this function is cheap to call (no extra system calls
1459 /// needed), but on Unix platforms this function is the equivalent of
1460 /// calling `symlink_metadata` on the path.
1467 /// if let Ok(entries) = fs::read_dir(".") {
1468 /// for entry in entries {
1469 /// if let Ok(entry) = entry {
1470 /// // Here, `entry` is a `DirEntry`.
1471 /// if let Ok(metadata) = entry.metadata() {
1472 /// // Now let's show our entry's permissions!
1473 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1475 /// println!("Couldn't get metadata for {:?}", entry.path());
1481 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1482 pub fn metadata(&self) -> io::Result<Metadata> {
1483 self.0.metadata().map(Metadata)
1486 /// Returns the file type for the file that this entry points at.
1488 /// This function will not traverse symlinks if this entry points at a
1491 /// # Platform-specific behavior
1493 /// On Windows and most Unix platforms this function is free (no extra
1494 /// system calls needed), but some Unix platforms may require the equivalent
1495 /// call to `symlink_metadata` to learn about the target file type.
1502 /// if let Ok(entries) = fs::read_dir(".") {
1503 /// for entry in entries {
1504 /// if let Ok(entry) = entry {
1505 /// // Here, `entry` is a `DirEntry`.
1506 /// if let Ok(file_type) = entry.file_type() {
1507 /// // Now let's show our entry's file type!
1508 /// println!("{:?}: {:?}", entry.path(), file_type);
1510 /// println!("Couldn't get file type for {:?}", entry.path());
1516 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1517 pub fn file_type(&self) -> io::Result<FileType> {
1518 self.0.file_type().map(FileType)
1521 /// Returns the bare file name of this directory entry without any other
1522 /// leading path component.
1529 /// if let Ok(entries) = fs::read_dir(".") {
1530 /// for entry in entries {
1531 /// if let Ok(entry) = entry {
1532 /// // Here, `entry` is a `DirEntry`.
1533 /// println!("{:?}", entry.file_name());
1538 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1539 pub fn file_name(&self) -> OsString {
1544 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1545 impl fmt::Debug for DirEntry {
1546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547 f.debug_tuple("DirEntry").field(&self.path()).finish()
1551 impl AsInner<fs_imp::DirEntry> for DirEntry {
1552 fn as_inner(&self) -> &fs_imp::DirEntry {
1557 /// Removes a file from the filesystem.
1559 /// Note that there is no
1560 /// guarantee that the file is immediately deleted (e.g., depending on
1561 /// platform, other open file descriptors may prevent immediate removal).
1563 /// # Platform-specific behavior
1565 /// This function currently corresponds to the `unlink` function on Unix
1566 /// and the `DeleteFile` function on Windows.
1567 /// Note that, this [may change in the future][changes].
1569 /// [changes]: ../io/index.html#platform-specific-behavior
1573 /// This function will return an error in the following situations, but is not
1574 /// limited to just these cases:
1576 /// * `path` points to a directory.
1577 /// * The user lacks permissions to remove the file.
1584 /// fn main() -> std::io::Result<()> {
1585 /// fs::remove_file("a.txt")?;
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1591 fs_imp::unlink(path.as_ref())
1594 /// Given a path, query the file system to get information about a file,
1597 /// This function will traverse symbolic links to query information about the
1598 /// destination file.
1600 /// # Platform-specific behavior
1602 /// This function currently corresponds to the `stat` function on Unix
1603 /// and the `GetFileAttributesEx` function on Windows.
1604 /// Note that, this [may change in the future][changes].
1606 /// [changes]: ../io/index.html#platform-specific-behavior
1610 /// This function will return an error in the following situations, but is not
1611 /// limited to just these cases:
1613 /// * The user lacks permissions to perform `metadata` call on `path`.
1614 /// * `path` does not exist.
1621 /// fn main() -> std::io::Result<()> {
1622 /// let attr = fs::metadata("/some/file/path.txt")?;
1623 /// // inspect attr ...
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1629 fs_imp::stat(path.as_ref()).map(Metadata)
1632 /// Query the metadata about a file without following symlinks.
1634 /// # Platform-specific behavior
1636 /// This function currently corresponds to the `lstat` function on Unix
1637 /// and the `GetFileAttributesEx` function on Windows.
1638 /// Note that, this [may change in the future][changes].
1640 /// [changes]: ../io/index.html#platform-specific-behavior
1644 /// This function will return an error in the following situations, but is not
1645 /// limited to just these cases:
1647 /// * The user lacks permissions to perform `metadata` call on `path`.
1648 /// * `path` does not exist.
1655 /// fn main() -> std::io::Result<()> {
1656 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1657 /// // inspect attr ...
1661 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1662 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1663 fs_imp::lstat(path.as_ref()).map(Metadata)
1666 /// Rename a file or directory to a new name, replacing the original file if
1667 /// `to` already exists.
1669 /// This will not work if the new name is on a different mount point.
1671 /// # Platform-specific behavior
1673 /// This function currently corresponds to the `rename` function on Unix
1674 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1676 /// Because of this, the behavior when both `from` and `to` exist differs. On
1677 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1678 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1679 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1681 /// Note that, this [may change in the future][changes].
1683 /// [changes]: ../io/index.html#platform-specific-behavior
1687 /// This function will return an error in the following situations, but is not
1688 /// limited to just these cases:
1690 /// * `from` does not exist.
1691 /// * The user lacks permissions to view contents.
1692 /// * `from` and `to` are on separate filesystems.
1699 /// fn main() -> std::io::Result<()> {
1700 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1706 fs_imp::rename(from.as_ref(), to.as_ref())
1709 /// Copies the contents of one file to another. This function will also
1710 /// copy the permission bits of the original file to the destination file.
1712 /// This function will **overwrite** the contents of `to`.
1714 /// Note that if `from` and `to` both point to the same file, then the file
1715 /// will likely get truncated by this operation.
1717 /// On success, the total number of bytes copied is returned and it is equal to
1718 /// the length of the `to` file as reported by `metadata`.
1720 /// If you’re wanting to copy the contents of one file to another and you’re
1721 /// working with [`File`]s, see the [`io::copy`] function.
1723 /// [`io::copy`]: ../io/fn.copy.html
1724 /// [`File`]: ./struct.File.html
1726 /// # Platform-specific behavior
1728 /// This function currently corresponds to the `open` function in Unix
1729 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1730 /// `O_CLOEXEC` is set for returned file descriptors.
1731 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1732 /// NTFS streams are copied but only the size of the main stream is returned by
1733 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1735 /// Note that, this [may change in the future][changes].
1737 /// [changes]: ../io/index.html#platform-specific-behavior
1741 /// This function will return an error in the following situations, but is not
1742 /// limited to just these cases:
1744 /// * The `from` path is not a file.
1745 /// * The `from` file does not exist.
1746 /// * The current process does not have the permission rights to access
1747 /// `from` or write `to`.
1754 /// fn main() -> std::io::Result<()> {
1755 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1761 fs_imp::copy(from.as_ref(), to.as_ref())
1764 /// Creates a new hard link on the filesystem.
1766 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1767 /// often require these two paths to both be located on the same filesystem.
1769 /// # Platform-specific behavior
1771 /// This function currently corresponds to the `link` function on Unix
1772 /// and the `CreateHardLink` function on Windows.
1773 /// Note that, this [may change in the future][changes].
1775 /// [changes]: ../io/index.html#platform-specific-behavior
1779 /// This function will return an error in the following situations, but is not
1780 /// limited to just these cases:
1782 /// * The `src` path is not a file or doesn't exist.
1789 /// fn main() -> std::io::Result<()> {
1790 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1796 fs_imp::link(src.as_ref(), dst.as_ref())
1799 /// Creates a new symbolic link on the filesystem.
1801 /// The `dst` path will be a symbolic link pointing to the `src` path.
1802 /// On Windows, this will be a file symlink, not a directory symlink;
1803 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1804 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1805 /// used instead to make the intent explicit.
1807 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1808 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1809 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1817 /// fn main() -> std::io::Result<()> {
1818 /// fs::soft_link("a.txt", "b.txt")?;
1822 #[stable(feature = "rust1", since = "1.0.0")]
1825 reason = "replaced with std::os::unix::fs::symlink and \
1826 std::os::windows::fs::{symlink_file, symlink_dir}"
1828 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1829 fs_imp::symlink(src.as_ref(), dst.as_ref())
1832 /// Reads a symbolic link, returning the file that the link points to.
1834 /// # Platform-specific behavior
1836 /// This function currently corresponds to the `readlink` function on Unix
1837 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1838 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1839 /// Note that, this [may change in the future][changes].
1841 /// [changes]: ../io/index.html#platform-specific-behavior
1845 /// This function will return an error in the following situations, but is not
1846 /// limited to just these cases:
1848 /// * `path` is not a symbolic link.
1849 /// * `path` does not exist.
1856 /// fn main() -> std::io::Result<()> {
1857 /// let path = fs::read_link("a.txt")?;
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1863 fs_imp::readlink(path.as_ref())
1866 /// Returns the canonical, absolute form of a path with all intermediate
1867 /// components normalized and symbolic links resolved.
1869 /// # Platform-specific behavior
1871 /// This function currently corresponds to the `realpath` function on Unix
1872 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1873 /// Note that, this [may change in the future][changes].
1875 /// On Windows, this converts the path to use [extended length path][path]
1876 /// syntax, which allows your program to use longer path names, but means you
1877 /// can only join backslash-delimited paths to it, and it may be incompatible
1878 /// with other applications (if passed to the application on the command-line,
1879 /// or written to a file another application may read).
1881 /// [changes]: ../io/index.html#platform-specific-behavior
1882 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1886 /// This function will return an error in the following situations, but is not
1887 /// limited to just these cases:
1889 /// * `path` does not exist.
1890 /// * A non-final component in path is not a directory.
1897 /// fn main() -> std::io::Result<()> {
1898 /// let path = fs::canonicalize("../a/../foo.txt")?;
1902 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1903 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1904 fs_imp::canonicalize(path.as_ref())
1907 /// Creates a new, empty directory at the provided path
1909 /// # Platform-specific behavior
1911 /// This function currently corresponds to the `mkdir` function on Unix
1912 /// and the `CreateDirectory` function on Windows.
1913 /// Note that, this [may change in the future][changes].
1915 /// [changes]: ../io/index.html#platform-specific-behavior
1917 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1918 /// return an error. To create a directory and all its missing parents at the
1919 /// same time, use the [`create_dir_all`] function.
1923 /// This function will return an error in the following situations, but is not
1924 /// limited to just these cases:
1926 /// * User lacks permissions to create directory at `path`.
1927 /// * A parent of the given path doesn't exist. (To create a directory and all
1928 /// its missing parents at the same time, use the [`create_dir_all`]
1930 /// * `path` already exists.
1932 /// [`create_dir_all`]: fn.create_dir_all.html
1939 /// fn main() -> std::io::Result<()> {
1940 /// fs::create_dir("/some/dir")?;
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1946 DirBuilder::new().create(path.as_ref())
1949 /// Recursively create a directory and all of its parent components if they
1952 /// # Platform-specific behavior
1954 /// This function currently corresponds to the `mkdir` function on Unix
1955 /// and the `CreateDirectory` function on Windows.
1956 /// Note that, this [may change in the future][changes].
1958 /// [changes]: ../io/index.html#platform-specific-behavior
1962 /// This function will return an error in the following situations, but is not
1963 /// limited to just these cases:
1965 /// * If any directory in the path specified by `path`
1966 /// does not already exist and it could not be created otherwise. The specific
1967 /// error conditions for when a directory is being created (after it is
1968 /// determined to not exist) are outlined by [`fs::create_dir`].
1970 /// Notable exception is made for situations where any of the directories
1971 /// specified in the `path` could not be created as it was being created concurrently.
1972 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1973 /// concurrently from multiple threads or processes is guaranteed not to fail
1974 /// due to a race condition with itself.
1976 /// [`fs::create_dir`]: fn.create_dir.html
1983 /// fn main() -> std::io::Result<()> {
1984 /// fs::create_dir_all("/some/dir")?;
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1990 DirBuilder::new().recursive(true).create(path.as_ref())
1993 /// Removes an existing, empty directory.
1995 /// # Platform-specific behavior
1997 /// This function currently corresponds to the `rmdir` function on Unix
1998 /// and the `RemoveDirectory` function on Windows.
1999 /// Note that, this [may change in the future][changes].
2001 /// [changes]: ../io/index.html#platform-specific-behavior
2005 /// This function will return an error in the following situations, but is not
2006 /// limited to just these cases:
2008 /// * The user lacks permissions to remove the directory at the provided `path`.
2009 /// * The directory isn't empty.
2016 /// fn main() -> std::io::Result<()> {
2017 /// fs::remove_dir("/some/dir")?;
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2023 fs_imp::rmdir(path.as_ref())
2026 /// Removes a directory at this path, after removing all its contents. Use
2029 /// This function does **not** follow symbolic links and it will simply remove the
2030 /// symbolic link itself.
2032 /// # Platform-specific behavior
2034 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2035 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2037 /// Note that, this [may change in the future][changes].
2039 /// [changes]: ../io/index.html#platform-specific-behavior
2043 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2045 /// [`fs::remove_file`]: fn.remove_file.html
2046 /// [`fs::remove_dir`]: fn.remove_dir.html
2053 /// fn main() -> std::io::Result<()> {
2054 /// fs::remove_dir_all("/some/dir")?;
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2060 fs_imp::remove_dir_all(path.as_ref())
2063 /// Returns an iterator over the entries within a directory.
2065 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2066 /// New errors may be encountered after an iterator is initially constructed.
2068 /// [`io::Result`]: ../io/type.Result.html
2069 /// [`DirEntry`]: struct.DirEntry.html
2071 /// # Platform-specific behavior
2073 /// This function currently corresponds to the `opendir` function on Unix
2074 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2075 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2076 /// Note that, this [may change in the future][changes].
2078 /// [changes]: ../io/index.html#platform-specific-behavior
2080 /// The order in which this iterator returns entries is platform and filesystem
2085 /// This function will return an error in the following situations, but is not
2086 /// limited to just these cases:
2088 /// * The provided `path` doesn't exist.
2089 /// * The process lacks permissions to view the contents.
2090 /// * The `path` points at a non-directory file.
2096 /// use std::fs::{self, DirEntry};
2097 /// use std::path::Path;
2099 /// // one possible implementation of walking a directory only visiting files
2100 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2101 /// if dir.is_dir() {
2102 /// for entry in fs::read_dir(dir)? {
2103 /// let entry = entry?;
2104 /// let path = entry.path();
2105 /// if path.is_dir() {
2106 /// visit_dirs(&path, cb)?;
2117 /// use std::{fs, io};
2119 /// fn main() -> io::Result<()> {
2120 /// let mut entries = fs::read_dir(".")?
2121 /// .map(|res| res.map(|e| e.path()))
2122 /// .collect::<Result<Vec<_>, io::Error>>()?;
2124 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2125 /// // ordering is required the entries should be explicitly sorted.
2129 /// // The entries have now been sorted by their path.
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2136 fs_imp::readdir(path.as_ref()).map(ReadDir)
2139 /// Changes the permissions found on a file or a directory.
2141 /// # Platform-specific behavior
2143 /// This function currently corresponds to the `chmod` function on Unix
2144 /// and the `SetFileAttributes` function on Windows.
2145 /// Note that, this [may change in the future][changes].
2147 /// [changes]: ../io/index.html#platform-specific-behavior
2151 /// This function will return an error in the following situations, but is not
2152 /// limited to just these cases:
2154 /// * `path` does not exist.
2155 /// * The user lacks the permission to change attributes of the file.
2162 /// fn main() -> std::io::Result<()> {
2163 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2164 /// perms.set_readonly(true);
2165 /// fs::set_permissions("foo.txt", perms)?;
2169 #[stable(feature = "set_permissions", since = "1.1.0")]
2170 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2171 fs_imp::set_perm(path.as_ref(), perm.0)
2175 /// Creates a new set of options with default mode/security settings for all
2176 /// platforms and also non-recursive.
2181 /// use std::fs::DirBuilder;
2183 /// let builder = DirBuilder::new();
2185 #[stable(feature = "dir_builder", since = "1.6.0")]
2186 pub fn new() -> DirBuilder {
2187 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2190 /// Indicates that directories should be created recursively, creating all
2191 /// parent directories. Parents that do not exist are created with the same
2192 /// security and permissions settings.
2194 /// This option defaults to `false`.
2199 /// use std::fs::DirBuilder;
2201 /// let mut builder = DirBuilder::new();
2202 /// builder.recursive(true);
2204 #[stable(feature = "dir_builder", since = "1.6.0")]
2205 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2206 self.recursive = recursive;
2210 /// Creates the specified directory with the options configured in this
2213 /// It is considered an error if the directory already exists unless
2214 /// recursive mode is enabled.
2219 /// use std::fs::{self, DirBuilder};
2221 /// let path = "/tmp/foo/bar/baz";
2222 /// DirBuilder::new()
2223 /// .recursive(true)
2224 /// .create(path).unwrap();
2226 /// assert!(fs::metadata(path).unwrap().is_dir());
2228 #[stable(feature = "dir_builder", since = "1.6.0")]
2229 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2230 self._create(path.as_ref())
2233 fn _create(&self, path: &Path) -> io::Result<()> {
2234 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2237 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2238 if path == Path::new("") {
2242 match self.inner.mkdir(path) {
2243 Ok(()) => return Ok(()),
2244 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2245 Err(_) if path.is_dir() => return Ok(()),
2246 Err(e) => return Err(e),
2248 match path.parent() {
2249 Some(p) => self.create_dir_all(p)?,
2251 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2254 match self.inner.mkdir(path) {
2256 Err(_) if path.is_dir() => Ok(()),
2262 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2263 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2268 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2270 use crate::io::prelude::*;
2272 use crate::fs::{self, File, OpenOptions};
2273 use crate::io::{ErrorKind, SeekFrom};
2274 use crate::path::Path;
2276 use crate::sys_common::io::test::{tmpdir, TempDir};
2279 use rand::{rngs::StdRng, RngCore, SeedableRng};
2282 use crate::os::unix::fs::symlink as symlink_dir;
2284 use crate::os::unix::fs::symlink as symlink_file;
2286 use crate::os::unix::fs::symlink as symlink_junction;
2288 use crate::os::windows::fs::{symlink_dir, symlink_file};
2290 use crate::sys::fs::symlink_junction;
2292 macro_rules! check {
2296 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2302 macro_rules! error {
2303 ($e:expr, $s:expr) => {
2305 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2306 Err(ref err) => assert!(
2307 err.raw_os_error() == Some($s),
2308 format!("`{}` did not have a code of `{}`", err, $s)
2315 macro_rules! error {
2316 ($e:expr, $s:expr) => {
2317 error_contains!($e, $s)
2321 macro_rules! error_contains {
2322 ($e:expr, $s:expr) => {
2324 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2325 Err(ref err) => assert!(
2326 err.to_string().contains($s),
2327 format!("`{}` did not contain `{}`", err, $s)
2333 // Several test fail on windows if the user does not have permission to
2334 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2335 // disabling these test on Windows, use this function to test whether we
2336 // have permission, and return otherwise. This way, we still don't run these
2337 // tests most of the time, but at least we do if the user has the right
2339 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2343 let link = tmpdir.join("some_hopefully_unique_link_name");
2345 match symlink_file(r"nonexisting_target", link) {
2347 // ERROR_PRIVILEGE_NOT_HELD = 1314
2348 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2354 fn file_test_io_smoke_test() {
2355 let message = "it's alright. have a good time";
2356 let tmpdir = tmpdir();
2357 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2359 let mut write_stream = check!(File::create(filename));
2360 check!(write_stream.write(message.as_bytes()));
2363 let mut read_stream = check!(File::open(filename));
2364 let mut read_buf = [0; 1028];
2365 let read_str = match check!(read_stream.read(&mut read_buf)) {
2366 0 => panic!("shouldn't happen"),
2367 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2369 assert_eq!(read_str, message);
2371 check!(fs::remove_file(filename));
2375 fn invalid_path_raises() {
2376 let tmpdir = tmpdir();
2377 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2378 let result = File::open(filename);
2380 #[cfg(all(unix, not(target_os = "vxworks")))]
2381 error!(result, "No such file or directory");
2382 #[cfg(target_os = "vxworks")]
2383 error!(result, "no such file or directory");
2385 error!(result, 2); // ERROR_FILE_NOT_FOUND
2389 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2390 let tmpdir = tmpdir();
2391 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2393 let result = fs::remove_file(filename);
2395 #[cfg(all(unix, not(target_os = "vxworks")))]
2396 error!(result, "No such file or directory");
2397 #[cfg(target_os = "vxworks")]
2398 error!(result, "no such file or directory");
2400 error!(result, 2); // ERROR_FILE_NOT_FOUND
2404 fn file_test_io_non_positional_read() {
2405 let message: &str = "ten-four";
2406 let mut read_mem = [0; 8];
2407 let tmpdir = tmpdir();
2408 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2410 let mut rw_stream = check!(File::create(filename));
2411 check!(rw_stream.write(message.as_bytes()));
2414 let mut read_stream = check!(File::open(filename));
2416 let read_buf = &mut read_mem[0..4];
2417 check!(read_stream.read(read_buf));
2420 let read_buf = &mut read_mem[4..8];
2421 check!(read_stream.read(read_buf));
2424 check!(fs::remove_file(filename));
2425 let read_str = str::from_utf8(&read_mem).unwrap();
2426 assert_eq!(read_str, message);
2430 fn file_test_io_seek_and_tell_smoke_test() {
2431 let message = "ten-four";
2432 let mut read_mem = [0; 4];
2433 let set_cursor = 4 as u64;
2434 let tell_pos_pre_read;
2435 let tell_pos_post_read;
2436 let tmpdir = tmpdir();
2437 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2439 let mut rw_stream = check!(File::create(filename));
2440 check!(rw_stream.write(message.as_bytes()));
2443 let mut read_stream = check!(File::open(filename));
2444 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2445 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2446 check!(read_stream.read(&mut read_mem));
2447 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2449 check!(fs::remove_file(filename));
2450 let read_str = str::from_utf8(&read_mem).unwrap();
2451 assert_eq!(read_str, &message[4..8]);
2452 assert_eq!(tell_pos_pre_read, set_cursor);
2453 assert_eq!(tell_pos_post_read, message.len() as u64);
2457 fn file_test_io_seek_and_write() {
2458 let initial_msg = "food-is-yummy";
2459 let overwrite_msg = "-the-bar!!";
2460 let final_msg = "foo-the-bar!!";
2462 let mut read_mem = [0; 13];
2463 let tmpdir = tmpdir();
2464 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2466 let mut rw_stream = check!(File::create(filename));
2467 check!(rw_stream.write(initial_msg.as_bytes()));
2468 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2469 check!(rw_stream.write(overwrite_msg.as_bytes()));
2472 let mut read_stream = check!(File::open(filename));
2473 check!(read_stream.read(&mut read_mem));
2475 check!(fs::remove_file(filename));
2476 let read_str = str::from_utf8(&read_mem).unwrap();
2477 assert!(read_str == final_msg);
2481 fn file_test_io_seek_shakedown() {
2483 let initial_msg = "qwer-asdf-zxcv";
2484 let chunk_one: &str = "qwer";
2485 let chunk_two: &str = "asdf";
2486 let chunk_three: &str = "zxcv";
2487 let mut read_mem = [0; 4];
2488 let tmpdir = tmpdir();
2489 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2491 let mut rw_stream = check!(File::create(filename));
2492 check!(rw_stream.write(initial_msg.as_bytes()));
2495 let mut read_stream = check!(File::open(filename));
2497 check!(read_stream.seek(SeekFrom::End(-4)));
2498 check!(read_stream.read(&mut read_mem));
2499 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2501 check!(read_stream.seek(SeekFrom::Current(-9)));
2502 check!(read_stream.read(&mut read_mem));
2503 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2505 check!(read_stream.seek(SeekFrom::Start(0)));
2506 check!(read_stream.read(&mut read_mem));
2507 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2509 check!(fs::remove_file(filename));
2513 fn file_test_io_eof() {
2514 let tmpdir = tmpdir();
2515 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2516 let mut buf = [0; 256];
2518 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2519 let mut rw = check!(oo.open(&filename));
2520 assert_eq!(check!(rw.read(&mut buf)), 0);
2521 assert_eq!(check!(rw.read(&mut buf)), 0);
2523 check!(fs::remove_file(&filename));
2528 fn file_test_io_read_write_at() {
2529 use crate::os::unix::fs::FileExt;
2531 let tmpdir = tmpdir();
2532 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2533 let mut buf = [0; 256];
2534 let write1 = "asdf";
2535 let write2 = "qwer-";
2536 let write3 = "-zxcv";
2537 let content = "qwer-asdf-zxcv";
2539 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2540 let mut rw = check!(oo.open(&filename));
2541 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2542 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2543 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2544 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2545 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2546 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2547 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2548 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2549 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2550 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2551 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2552 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2553 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2554 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2555 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2556 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2557 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2558 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2561 let mut read = check!(File::open(&filename));
2562 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2563 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2564 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2565 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2566 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2567 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2568 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2569 assert_eq!(check!(read.read(&mut buf)), write3.len());
2570 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2571 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2572 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2573 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2574 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2575 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2576 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2577 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2579 check!(fs::remove_file(&filename));
2584 fn set_get_unix_permissions() {
2585 use crate::os::unix::fs::PermissionsExt;
2587 let tmpdir = tmpdir();
2588 let filename = &tmpdir.join("set_get_unix_permissions");
2589 check!(fs::create_dir(filename));
2592 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2593 let metadata0 = check!(fs::metadata(filename));
2594 assert_eq!(mask & metadata0.permissions().mode(), 0);
2596 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2597 let metadata1 = check!(fs::metadata(filename));
2598 #[cfg(all(unix, not(target_os = "vxworks")))]
2599 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2600 #[cfg(target_os = "vxworks")]
2601 assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2606 fn file_test_io_seek_read_write() {
2607 use crate::os::windows::fs::FileExt;
2609 let tmpdir = tmpdir();
2610 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2611 let mut buf = [0; 256];
2612 let write1 = "asdf";
2613 let write2 = "qwer-";
2614 let write3 = "-zxcv";
2615 let content = "qwer-asdf-zxcv";
2617 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2618 let mut rw = check!(oo.open(&filename));
2619 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2620 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2621 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2622 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2623 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2624 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2625 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2626 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2627 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2628 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2629 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2630 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2631 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2632 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2633 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2634 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2637 let mut read = check!(File::open(&filename));
2638 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2639 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2640 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2641 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2642 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2643 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2644 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2645 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2646 assert_eq!(check!(read.read(&mut buf)), write3.len());
2647 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2648 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2649 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2650 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2651 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2652 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2653 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2655 check!(fs::remove_file(&filename));
2659 fn file_test_stat_is_correct_on_is_file() {
2660 let tmpdir = tmpdir();
2661 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2663 let mut opts = OpenOptions::new();
2664 let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2666 fs.write(msg.as_bytes()).unwrap();
2668 let fstat_res = check!(fs.metadata());
2669 assert!(fstat_res.is_file());
2671 let stat_res_fn = check!(fs::metadata(filename));
2672 assert!(stat_res_fn.is_file());
2673 let stat_res_meth = check!(filename.metadata());
2674 assert!(stat_res_meth.is_file());
2675 check!(fs::remove_file(filename));
2679 fn file_test_stat_is_correct_on_is_dir() {
2680 let tmpdir = tmpdir();
2681 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2682 check!(fs::create_dir(filename));
2683 let stat_res_fn = check!(fs::metadata(filename));
2684 assert!(stat_res_fn.is_dir());
2685 let stat_res_meth = check!(filename.metadata());
2686 assert!(stat_res_meth.is_dir());
2687 check!(fs::remove_dir(filename));
2691 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2692 let tmpdir = tmpdir();
2693 let dir = &tmpdir.join("fileinfo_false_on_dir");
2694 check!(fs::create_dir(dir));
2695 assert!(!dir.is_file());
2696 check!(fs::remove_dir(dir));
2700 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2701 let tmpdir = tmpdir();
2702 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2703 check!(check!(File::create(file)).write(b"foo"));
2704 assert!(file.exists());
2705 check!(fs::remove_file(file));
2706 assert!(!file.exists());
2710 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2711 let tmpdir = tmpdir();
2712 let dir = &tmpdir.join("before_and_after_dir");
2713 assert!(!dir.exists());
2714 check!(fs::create_dir(dir));
2715 assert!(dir.exists());
2716 assert!(dir.is_dir());
2717 check!(fs::remove_dir(dir));
2718 assert!(!dir.exists());
2722 fn file_test_directoryinfo_readdir() {
2723 let tmpdir = tmpdir();
2724 let dir = &tmpdir.join("di_readdir");
2725 check!(fs::create_dir(dir));
2728 let f = dir.join(&format!("{}.txt", n));
2729 let mut w = check!(File::create(&f));
2730 let msg_str = format!("{}{}", prefix, n.to_string());
2731 let msg = msg_str.as_bytes();
2732 check!(w.write(msg));
2734 let files = check!(fs::read_dir(dir));
2735 let mut mem = [0; 4];
2737 let f = f.unwrap().path();
2739 let n = f.file_stem().unwrap();
2740 check!(check!(File::open(&f)).read(&mut mem));
2741 let read_str = str::from_utf8(&mem).unwrap();
2742 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2743 assert_eq!(expected, read_str);
2745 check!(fs::remove_file(&f));
2747 check!(fs::remove_dir(dir));
2751 fn file_create_new_already_exists_error() {
2752 let tmpdir = tmpdir();
2753 let file = &tmpdir.join("file_create_new_error_exists");
2754 check!(fs::File::create(file));
2755 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2756 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2760 fn mkdir_path_already_exists_error() {
2761 let tmpdir = tmpdir();
2762 let dir = &tmpdir.join("mkdir_error_twice");
2763 check!(fs::create_dir(dir));
2764 let e = fs::create_dir(dir).unwrap_err();
2765 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2769 fn recursive_mkdir() {
2770 let tmpdir = tmpdir();
2771 let dir = tmpdir.join("d1/d2");
2772 check!(fs::create_dir_all(&dir));
2773 assert!(dir.is_dir())
2777 fn recursive_mkdir_failure() {
2778 let tmpdir = tmpdir();
2779 let dir = tmpdir.join("d1");
2780 let file = dir.join("f1");
2782 check!(fs::create_dir_all(&dir));
2783 check!(File::create(&file));
2785 let result = fs::create_dir_all(&file);
2787 assert!(result.is_err());
2791 fn concurrent_recursive_mkdir() {
2794 let mut dir = dir.join("a");
2796 dir = dir.join("a");
2798 let mut join = vec![];
2800 let dir = dir.clone();
2801 join.push(thread::spawn(move || {
2802 check!(fs::create_dir_all(&dir));
2806 // No `Display` on result of `join()`
2807 join.drain(..).map(|join| join.join().unwrap()).count();
2812 fn recursive_mkdir_slash() {
2813 check!(fs::create_dir_all(Path::new("/")));
2817 fn recursive_mkdir_dot() {
2818 check!(fs::create_dir_all(Path::new(".")));
2822 fn recursive_mkdir_empty() {
2823 check!(fs::create_dir_all(Path::new("")));
2827 fn recursive_rmdir() {
2828 let tmpdir = tmpdir();
2829 let d1 = tmpdir.join("d1");
2830 let dt = d1.join("t");
2831 let dtt = dt.join("t");
2832 let d2 = tmpdir.join("d2");
2833 let canary = d2.join("do_not_delete");
2834 check!(fs::create_dir_all(&dtt));
2835 check!(fs::create_dir_all(&d2));
2836 check!(check!(File::create(&canary)).write(b"foo"));
2837 check!(symlink_junction(&d2, &dt.join("d2")));
2838 let _ = symlink_file(&canary, &d1.join("canary"));
2839 check!(fs::remove_dir_all(&d1));
2841 assert!(!d1.is_dir());
2842 assert!(canary.exists());
2846 fn recursive_rmdir_of_symlink() {
2847 // test we do not recursively delete a symlink but only dirs.
2848 let tmpdir = tmpdir();
2849 let link = tmpdir.join("d1");
2850 let dir = tmpdir.join("d2");
2851 let canary = dir.join("do_not_delete");
2852 check!(fs::create_dir_all(&dir));
2853 check!(check!(File::create(&canary)).write(b"foo"));
2854 check!(symlink_junction(&dir, &link));
2855 check!(fs::remove_dir_all(&link));
2857 assert!(!link.is_dir());
2858 assert!(canary.exists());
2862 // only Windows makes a distinction between file and directory symlinks.
2864 fn recursive_rmdir_of_file_symlink() {
2865 let tmpdir = tmpdir();
2866 if !got_symlink_permission(&tmpdir) {
2870 let f1 = tmpdir.join("f1");
2871 let f2 = tmpdir.join("f2");
2872 check!(check!(File::create(&f1)).write(b"foo"));
2873 check!(symlink_file(&f1, &f2));
2874 match fs::remove_dir_all(&f2) {
2875 Ok(..) => panic!("wanted a failure"),
2881 fn unicode_path_is_dir() {
2882 assert!(Path::new(".").is_dir());
2883 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2885 let tmpdir = tmpdir();
2887 let mut dirpath = tmpdir.path().to_path_buf();
2888 dirpath.push("test-가一ー你好");
2889 check!(fs::create_dir(&dirpath));
2890 assert!(dirpath.is_dir());
2892 let mut filepath = dirpath;
2893 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2894 check!(File::create(&filepath)); // ignore return; touch only
2895 assert!(!filepath.is_dir());
2896 assert!(filepath.exists());
2900 fn unicode_path_exists() {
2901 assert!(Path::new(".").exists());
2902 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2904 let tmpdir = tmpdir();
2905 let unicode = tmpdir.path();
2906 let unicode = unicode.join("test-각丁ー再见");
2907 check!(fs::create_dir(&unicode));
2908 assert!(unicode.exists());
2909 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2913 fn copy_file_does_not_exist() {
2914 let from = Path::new("test/nonexistent-bogus-path");
2915 let to = Path::new("test/other-bogus-path");
2917 match fs::copy(&from, &to) {
2920 assert!(!from.exists());
2921 assert!(!to.exists());
2927 fn copy_src_does_not_exist() {
2928 let tmpdir = tmpdir();
2929 let from = Path::new("test/nonexistent-bogus-path");
2930 let to = tmpdir.join("out.txt");
2931 check!(check!(File::create(&to)).write(b"hello"));
2932 assert!(fs::copy(&from, &to).is_err());
2933 assert!(!from.exists());
2934 let mut v = Vec::new();
2935 check!(check!(File::open(&to)).read_to_end(&mut v));
2936 assert_eq!(v, b"hello");
2941 let tmpdir = tmpdir();
2942 let input = tmpdir.join("in.txt");
2943 let out = tmpdir.join("out.txt");
2945 check!(check!(File::create(&input)).write(b"hello"));
2946 check!(fs::copy(&input, &out));
2947 let mut v = Vec::new();
2948 check!(check!(File::open(&out)).read_to_end(&mut v));
2949 assert_eq!(v, b"hello");
2951 assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2955 fn copy_file_dst_dir() {
2956 let tmpdir = tmpdir();
2957 let out = tmpdir.join("out");
2959 check!(File::create(&out));
2960 match fs::copy(&*out, tmpdir.path()) {
2967 fn copy_file_dst_exists() {
2968 let tmpdir = tmpdir();
2969 let input = tmpdir.join("in");
2970 let output = tmpdir.join("out");
2972 check!(check!(File::create(&input)).write("foo".as_bytes()));
2973 check!(check!(File::create(&output)).write("bar".as_bytes()));
2974 check!(fs::copy(&input, &output));
2976 let mut v = Vec::new();
2977 check!(check!(File::open(&output)).read_to_end(&mut v));
2978 assert_eq!(v, b"foo".to_vec());
2982 fn copy_file_src_dir() {
2983 let tmpdir = tmpdir();
2984 let out = tmpdir.join("out");
2986 match fs::copy(tmpdir.path(), &out) {
2990 assert!(!out.exists());
2994 fn copy_file_preserves_perm_bits() {
2995 let tmpdir = tmpdir();
2996 let input = tmpdir.join("in.txt");
2997 let out = tmpdir.join("out.txt");
2999 let attr = check!(check!(File::create(&input)).metadata());
3000 let mut p = attr.permissions();
3001 p.set_readonly(true);
3002 check!(fs::set_permissions(&input, p));
3003 check!(fs::copy(&input, &out));
3004 assert!(check!(out.metadata()).permissions().readonly());
3005 check!(fs::set_permissions(&input, attr.permissions()));
3006 check!(fs::set_permissions(&out, attr.permissions()));
3011 fn copy_file_preserves_streams() {
3013 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
3014 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
3015 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
3016 let mut v = Vec::new();
3017 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
3018 assert_eq!(v, b"carrot".to_vec());
3022 fn copy_file_returns_metadata_len() {
3024 let in_path = tmp.join("in.txt");
3025 let out_path = tmp.join("out.txt");
3026 check!(check!(File::create(&in_path)).write(b"lettuce"));
3028 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
3029 let copied_len = check!(fs::copy(&in_path, &out_path));
3030 assert_eq!(check!(out_path.metadata()).len(), copied_len);
3034 fn copy_file_follows_dst_symlink() {
3036 if !got_symlink_permission(&tmp) {
3040 let in_path = tmp.join("in.txt");
3041 let out_path = tmp.join("out.txt");
3042 let out_path_symlink = tmp.join("out_symlink.txt");
3044 check!(fs::write(&in_path, "foo"));
3045 check!(fs::write(&out_path, "bar"));
3046 check!(symlink_file(&out_path, &out_path_symlink));
3048 check!(fs::copy(&in_path, &out_path_symlink));
3050 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
3051 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
3052 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
3056 fn symlinks_work() {
3057 let tmpdir = tmpdir();
3058 if !got_symlink_permission(&tmpdir) {
3062 let input = tmpdir.join("in.txt");
3063 let out = tmpdir.join("out.txt");
3065 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3066 check!(symlink_file(&input, &out));
3067 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
3068 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3069 let mut v = Vec::new();
3070 check!(check!(File::open(&out)).read_to_end(&mut v));
3071 assert_eq!(v, b"foobar".to_vec());
3075 fn symlink_noexist() {
3076 // Symlinks can point to things that don't exist
3077 let tmpdir = tmpdir();
3078 if !got_symlink_permission(&tmpdir) {
3082 // Use a relative path for testing. Symlinks get normalized by Windows,
3083 // so we may not get the same path back for absolute paths
3084 check!(symlink_file(&"foo", &tmpdir.join("bar")));
3085 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3091 // directory symlink
3093 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3098 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3101 // junction with special permissions
3103 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3107 let tmpdir = tmpdir();
3108 let link = tmpdir.join("link");
3109 if !got_symlink_permission(&tmpdir) {
3112 check!(symlink_file(&"foo", &link));
3113 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3117 fn readlink_not_symlink() {
3118 let tmpdir = tmpdir();
3119 match fs::read_link(tmpdir.path()) {
3120 Ok(..) => panic!("wanted a failure"),
3127 let tmpdir = tmpdir();
3128 let input = tmpdir.join("in.txt");
3129 let out = tmpdir.join("out.txt");
3131 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3132 check!(fs::hard_link(&input, &out));
3133 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3134 assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3135 let mut v = Vec::new();
3136 check!(check!(File::open(&out)).read_to_end(&mut v));
3137 assert_eq!(v, b"foobar".to_vec());
3139 // can't link to yourself
3140 match fs::hard_link(&input, &input) {
3141 Ok(..) => panic!("wanted a failure"),
3144 // can't link to something that doesn't exist
3145 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3146 Ok(..) => panic!("wanted a failure"),
3153 let tmpdir = tmpdir();
3154 let file = tmpdir.join("in.txt");
3156 check!(File::create(&file));
3157 let attr = check!(fs::metadata(&file));
3158 assert!(!attr.permissions().readonly());
3159 let mut p = attr.permissions();
3160 p.set_readonly(true);
3161 check!(fs::set_permissions(&file, p.clone()));
3162 let attr = check!(fs::metadata(&file));
3163 assert!(attr.permissions().readonly());
3165 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3166 Ok(..) => panic!("wanted an error"),
3170 p.set_readonly(false);
3171 check!(fs::set_permissions(&file, p));
3176 let tmpdir = tmpdir();
3177 let path = tmpdir.join("in.txt");
3179 let file = check!(File::create(&path));
3180 let attr = check!(fs::metadata(&path));
3181 assert!(!attr.permissions().readonly());
3182 let mut p = attr.permissions();
3183 p.set_readonly(true);
3184 check!(file.set_permissions(p.clone()));
3185 let attr = check!(fs::metadata(&path));
3186 assert!(attr.permissions().readonly());
3188 p.set_readonly(false);
3189 check!(file.set_permissions(p));
3193 fn sync_doesnt_kill_anything() {
3194 let tmpdir = tmpdir();
3195 let path = tmpdir.join("in.txt");
3197 let mut file = check!(File::create(&path));
3198 check!(file.sync_all());
3199 check!(file.sync_data());
3200 check!(file.write(b"foo"));
3201 check!(file.sync_all());
3202 check!(file.sync_data());
3206 fn truncate_works() {
3207 let tmpdir = tmpdir();
3208 let path = tmpdir.join("in.txt");
3210 let mut file = check!(File::create(&path));
3211 check!(file.write(b"foo"));
3212 check!(file.sync_all());
3214 // Do some simple things with truncation
3215 assert_eq!(check!(file.metadata()).len(), 3);
3216 check!(file.set_len(10));
3217 assert_eq!(check!(file.metadata()).len(), 10);
3218 check!(file.write(b"bar"));
3219 check!(file.sync_all());
3220 assert_eq!(check!(file.metadata()).len(), 10);
3222 let mut v = Vec::new();
3223 check!(check!(File::open(&path)).read_to_end(&mut v));
3224 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3226 // Truncate to a smaller length, don't seek, and then write something.
3227 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3228 // past the end of the file).
3229 check!(file.set_len(2));
3230 assert_eq!(check!(file.metadata()).len(), 2);
3231 check!(file.write(b"wut"));
3232 check!(file.sync_all());
3233 assert_eq!(check!(file.metadata()).len(), 9);
3234 let mut v = Vec::new();
3235 check!(check!(File::open(&path)).read_to_end(&mut v));
3236 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3241 use crate::fs::OpenOptions as OO;
3242 fn c<T: Clone>(t: &T) -> T {
3246 let tmpdir = tmpdir();
3248 let mut r = OO::new();
3250 let mut w = OO::new();
3252 let mut rw = OO::new();
3253 rw.read(true).write(true);
3254 let mut a = OO::new();
3256 let mut ra = OO::new();
3257 ra.read(true).append(true);
3260 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3261 #[cfg(all(unix, not(target_os = "vxworks")))]
3262 let invalid_options = "Invalid argument";
3263 #[cfg(target_os = "vxworks")]
3264 let invalid_options = "invalid argument";
3266 // Test various combinations of creation modes and access modes.
3269 // creation mode | read | write | read-write | append | read-append |
3270 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3271 // not set (open existing) | X | X | X | X | X |
3272 // create | | X | X | X | X |
3273 // truncate | | X | X | | |
3274 // create and truncate | | X | X | | |
3275 // create_new | | X | X | X | X |
3277 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3280 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3281 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3282 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3283 check!(c(&w).create(true).open(&tmpdir.join("a")));
3284 check!(c(&w).open(&tmpdir.join("a")));
3287 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3288 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3289 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3290 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3291 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3294 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3295 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3296 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3297 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3298 check!(c(&rw).open(&tmpdir.join("c")));
3301 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3302 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3303 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3304 check!(c(&a).create(true).open(&tmpdir.join("d")));
3305 check!(c(&a).open(&tmpdir.join("d")));
3308 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3309 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3310 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3311 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3312 check!(c(&ra).open(&tmpdir.join("e")));
3314 // Test opening a file without setting an access mode
3315 let mut blank = OO::new();
3316 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3319 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3321 // Test write fails for read-only
3322 check!(r.open(&tmpdir.join("h")));
3324 let mut f = check!(r.open(&tmpdir.join("h")));
3325 assert!(f.write("wut".as_bytes()).is_err());
3328 // Test write overwrites
3330 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3331 check!(f.write("baz".as_bytes()));
3334 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3335 let mut b = vec![0; 6];
3336 check!(f.read(&mut b));
3337 assert_eq!(b, "bazbar".as_bytes());
3340 // Test truncate works
3342 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3343 check!(f.write("foo".as_bytes()));
3345 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3347 // Test append works
3348 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3350 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3351 check!(f.write("bar".as_bytes()));
3353 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3355 // Test .append(true) equals .write(true).append(true)
3357 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3358 check!(f.write("baz".as_bytes()));
3360 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3364 fn _assert_send_sync() {
3365 fn _assert_send_sync<T: Send + Sync>() {}
3366 _assert_send_sync::<OpenOptions>();
3371 let mut bytes = [0; 1024];
3372 StdRng::from_entropy().fill_bytes(&mut bytes);
3374 let tmpdir = tmpdir();
3376 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3377 let mut v = Vec::new();
3378 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3379 assert!(v == &bytes[..]);
3383 fn write_then_read() {
3384 let mut bytes = [0; 1024];
3385 StdRng::from_entropy().fill_bytes(&mut bytes);
3387 let tmpdir = tmpdir();
3389 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3390 let v = check!(fs::read(&tmpdir.join("test")));
3391 assert!(v == &bytes[..]);
3393 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3395 fs::read_to_string(&tmpdir.join("not-utf8")),
3396 "stream did not contain valid UTF-8"
3400 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3401 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3402 assert_eq!(string, s);
3406 fn file_try_clone() {
3407 let tmpdir = tmpdir();
3409 let mut f1 = check!(
3410 OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3412 let mut f2 = check!(f1.try_clone());
3414 check!(f1.write_all(b"hello world"));
3415 check!(f1.seek(SeekFrom::Start(2)));
3417 let mut buf = vec![];
3418 check!(f2.read_to_end(&mut buf));
3419 assert_eq!(buf, b"llo world");
3422 check!(f1.write_all(b"!"));
3426 #[cfg(not(windows))]
3427 fn unlink_readonly() {
3428 let tmpdir = tmpdir();
3429 let path = tmpdir.join("file");
3430 check!(File::create(&path));
3431 let mut perm = check!(fs::metadata(&path)).permissions();
3432 perm.set_readonly(true);
3433 check!(fs::set_permissions(&path, perm));
3434 check!(fs::remove_file(&path));
3438 fn mkdir_trailing_slash() {
3439 let tmpdir = tmpdir();
3440 let path = tmpdir.join("file");
3441 check!(fs::create_dir_all(&path.join("a/")));
3445 fn canonicalize_works_simple() {
3446 let tmpdir = tmpdir();
3447 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3448 let file = tmpdir.join("test");
3449 File::create(&file).unwrap();
3450 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3454 fn realpath_works() {
3455 let tmpdir = tmpdir();
3456 if !got_symlink_permission(&tmpdir) {
3460 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3461 let file = tmpdir.join("test");
3462 let dir = tmpdir.join("test2");
3463 let link = dir.join("link");
3464 let linkdir = tmpdir.join("test3");
3466 File::create(&file).unwrap();
3467 fs::create_dir(&dir).unwrap();
3468 symlink_file(&file, &link).unwrap();
3469 symlink_dir(&dir, &linkdir).unwrap();
3471 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3473 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3474 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3475 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3476 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3477 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3481 fn realpath_works_tricky() {
3482 let tmpdir = tmpdir();
3483 if !got_symlink_permission(&tmpdir) {
3487 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3488 let a = tmpdir.join("a");
3489 let b = a.join("b");
3490 let c = b.join("c");
3491 let d = a.join("d");
3492 let e = d.join("e");
3493 let f = a.join("f");
3495 fs::create_dir_all(&b).unwrap();
3496 fs::create_dir_all(&d).unwrap();
3497 File::create(&f).unwrap();
3498 if cfg!(not(windows)) {
3499 symlink_file("../d/e", &c).unwrap();
3500 symlink_file("../f", &e).unwrap();
3503 symlink_file(r"..\d\e", &c).unwrap();
3504 symlink_file(r"..\f", &e).unwrap();
3507 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3508 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3512 fn dir_entry_methods() {
3513 let tmpdir = tmpdir();
3515 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3516 File::create(&tmpdir.join("b")).unwrap();
3518 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3519 let fname = file.file_name();
3520 match fname.to_str() {
3522 assert!(file.file_type().unwrap().is_dir());
3523 assert!(file.metadata().unwrap().is_dir());
3526 assert!(file.file_type().unwrap().is_file());
3527 assert!(file.metadata().unwrap().is_file());
3529 f => panic!("unknown file name: {:?}", f),
3535 fn dir_entry_debug() {
3536 let tmpdir = tmpdir();
3537 File::create(&tmpdir.join("b")).unwrap();
3538 let mut read_dir = tmpdir.path().read_dir().unwrap();
3539 let dir_entry = read_dir.next().unwrap().unwrap();
3540 let actual = format!("{:?}", dir_entry);
3541 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3542 assert_eq!(actual, expected);
3546 fn read_dir_not_found() {
3547 let res = fs::read_dir("/path/that/does/not/exist");
3548 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3552 fn create_dir_all_with_junctions() {
3553 let tmpdir = tmpdir();
3554 let target = tmpdir.join("target");
3556 let junction = tmpdir.join("junction");
3557 let b = junction.join("a/b");
3559 let link = tmpdir.join("link");
3560 let d = link.join("c/d");
3562 fs::create_dir(&target).unwrap();
3564 check!(symlink_junction(&target, &junction));
3565 check!(fs::create_dir_all(&b));
3566 // the junction itself is not a directory, but `is_dir()` on a Path
3568 assert!(junction.is_dir());
3569 assert!(b.exists());
3571 if !got_symlink_permission(&tmpdir) {
3574 check!(symlink_dir(&target, &link));
3575 check!(fs::create_dir_all(&d));
3576 assert!(link.is_dir());
3577 assert!(d.exists());
3581 fn metadata_access_times() {
3582 let tmpdir = tmpdir();
3584 let b = tmpdir.join("b");
3585 File::create(&b).unwrap();
3587 let a = check!(fs::metadata(&tmpdir.path()));
3588 let b = check!(fs::metadata(&b));
3590 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3591 assert_eq!(check!(a.modified()), check!(a.modified()));
3592 assert_eq!(check!(b.accessed()), check!(b.modified()));
3594 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3595 check!(a.created());
3596 check!(b.created());
3599 if cfg!(target_os = "linux") {
3600 // Not always available
3601 match (a.created(), b.created()) {
3602 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3604 if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3606 "creation time must be always supported or not supported: {:?} {:?}",