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")]
12 use crate::ffi::OsString;
14 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
15 use crate::path::{Path, PathBuf};
16 use crate::sys::fs as fs_imp;
17 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
18 use crate::time::SystemTime;
20 /// A reference to an open file on the filesystem.
22 /// An instance of a `File` can be read and/or written depending on what options
23 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
24 /// that the file contains internally.
26 /// Files are automatically closed when they go out of scope. Errors detected
27 /// on closing are ignored by the implementation of `Drop`. Use the method
28 /// [`sync_all`] if these errors must be manually handled.
32 /// Creates a new file and write bytes to it (you can also use [`write`]):
35 /// use std::fs::File;
36 /// use std::io::prelude::*;
38 /// fn main() -> std::io::Result<()> {
39 /// let mut file = File::create("foo.txt")?;
40 /// file.write_all(b"Hello, world!")?;
45 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
48 /// use std::fs::File;
49 /// use std::io::prelude::*;
51 /// fn main() -> std::io::Result<()> {
52 /// let mut file = File::open("foo.txt")?;
53 /// let mut contents = String::new();
54 /// file.read_to_string(&mut contents)?;
55 /// assert_eq!(contents, "Hello, world!");
60 /// It can be more efficient to read the contents of a file with a buffered
61 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
64 /// use std::fs::File;
65 /// use std::io::BufReader;
66 /// use std::io::prelude::*;
68 /// fn main() -> std::io::Result<()> {
69 /// let file = File::open("foo.txt")?;
70 /// let mut buf_reader = BufReader::new(file);
71 /// let mut contents = String::new();
72 /// buf_reader.read_to_string(&mut contents)?;
73 /// assert_eq!(contents, "Hello, world!");
78 /// Note that, although read and write methods require a `&mut File`, because
79 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
80 /// still modify the file, either through methods that take `&File` or by
81 /// retrieving the underlying OS object and modifying the file that way.
82 /// Additionally, many operating systems allow concurrent modification of files
83 /// by different processes. Avoid assuming that holding a `&File` means that the
84 /// file will not change.
86 /// [`Seek`]: ../io/trait.Seek.html
87 /// [`String`]: ../string/struct.String.html
88 /// [`Read`]: ../io/trait.Read.html
89 /// [`Write`]: ../io/trait.Write.html
90 /// [`BufReader<R>`]: ../io/struct.BufReader.html
91 /// [`sync_all`]: struct.File.html#method.sync_all
92 /// [`read`]: fn.read.html
93 /// [`write`]: fn.write.html
94 #[stable(feature = "rust1", since = "1.0.0")]
99 /// Metadata information about a file.
101 /// This structure is returned from the [`metadata`] or
102 /// [`symlink_metadata`] function or method and represents known
103 /// metadata about a file such as its permissions, size, modification
106 /// [`metadata`]: fn.metadata.html
107 /// [`symlink_metadata`]: fn.symlink_metadata.html
108 #[stable(feature = "rust1", since = "1.0.0")]
110 pub struct Metadata(fs_imp::FileAttr);
112 /// Iterator over the entries in a directory.
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
119 /// The order in which this iterator returns entries is platform and filesystem
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
127 /// [`read_dir`]: fn.read_dir.html
128 /// [`DirEntry`]: struct.DirEntry.html
129 /// [`io::Result`]: ../io/type.Result.html
130 /// [`Err`]: ../result/enum.Result.html#variant.Err
131 #[stable(feature = "rust1", since = "1.0.0")]
133 pub struct ReadDir(fs_imp::ReadDir);
135 /// Entries returned by the [`ReadDir`] iterator.
137 /// [`ReadDir`]: struct.ReadDir.html
139 /// An instance of `DirEntry` represents an entry inside of a directory on the
140 /// filesystem. Each entry can be inspected via methods to learn about the full
141 /// path or possibly other metadata through per-platform extension traits.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub struct DirEntry(fs_imp::DirEntry);
145 /// Options and flags which can be used to configure how a file is opened.
147 /// This builder exposes the ability to configure how a [`File`] is opened and
148 /// what operations are permitted on the open file. The [`File::open`] and
149 /// [`File::create`] methods are aliases for commonly used options using this
152 /// [`File`]: struct.File.html
153 /// [`File::open`]: struct.File.html#method.open
154 /// [`File::create`]: struct.File.html#method.create
156 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
157 /// then chain calls to methods to set each option, then call [`open`],
158 /// passing the path of the file you're trying to open. This will give you a
159 /// [`io::Result`][result] with a [`File`][file] inside that you can further
162 /// [`new`]: struct.OpenOptions.html#method.new
163 /// [`open`]: struct.OpenOptions.html#method.open
164 /// [result]: ../io/type.Result.html
165 /// [file]: struct.File.html
169 /// Opening a file to read:
172 /// use std::fs::OpenOptions;
174 /// let file = OpenOptions::new().read(true).open("foo.txt");
177 /// Opening a file for both reading and writing, as well as creating it if it
181 /// use std::fs::OpenOptions;
183 /// let file = OpenOptions::new()
187 /// .open("foo.txt");
189 #[derive(Clone, Debug)]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub struct OpenOptions(fs_imp::OpenOptions);
193 /// Representation of the various permissions on a file.
195 /// This module only currently provides one bit of information, [`readonly`],
196 /// which is exposed on all currently supported platforms. Unix-specific
197 /// functionality, such as mode bits, is available through the
198 /// [`PermissionsExt`] trait.
200 /// [`readonly`]: struct.Permissions.html#method.readonly
201 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
202 #[derive(Clone, PartialEq, Eq, Debug)]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub struct Permissions(fs_imp::FilePermissions);
206 /// A structure representing a type of file with accessors for each file type.
207 /// It is returned by [`Metadata::file_type`] method.
209 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
210 #[stable(feature = "file_type", since = "1.1.0")]
211 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
212 pub struct FileType(fs_imp::FileType);
214 /// A builder used to create directories in various manners.
216 /// This builder also supports platform-specific options.
217 #[stable(feature = "dir_builder", since = "1.6.0")]
219 pub struct DirBuilder {
220 inner: fs_imp::DirBuilder,
224 /// Indicates how large a buffer to pre-allocate before reading the entire file.
225 fn initial_buffer_size(file: &File) -> usize {
226 // Allocate one extra byte so the buffer doesn't need to grow before the
227 // final `read` call at the end of the file. Don't worry about `usize`
228 // overflow because reading will fail regardless in that case.
229 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
232 /// Read the entire contents of a file into a bytes vector.
234 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
235 /// with fewer imports and without an intermediate variable. It pre-allocates a
236 /// buffer based on the file size when available, so it is generally faster than
237 /// reading into a vector created with `Vec::new()`.
239 /// [`File::open`]: struct.File.html#method.open
240 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
244 /// This function will return an error if `path` does not already exist.
245 /// Other errors may also be returned according to [`OpenOptions::open`].
247 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
249 /// It will also return an error if it encounters while reading an error
250 /// of a kind other than [`ErrorKind::Interrupted`].
252 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
258 /// use std::net::SocketAddr;
260 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
261 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
265 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
266 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
267 fn inner(path: &Path) -> io::Result<Vec<u8>> {
268 let mut file = File::open(path)?;
269 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
270 file.read_to_end(&mut bytes)?;
276 /// Read the entire contents of a file into a string.
278 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
279 /// with fewer imports and without an intermediate variable. It pre-allocates a
280 /// buffer based on the file size when available, so it is generally faster than
281 /// reading into a string created with `String::new()`.
283 /// [`File::open`]: struct.File.html#method.open
284 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
288 /// This function will return an error if `path` does not already exist.
289 /// Other errors may also be returned according to [`OpenOptions::open`].
291 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
293 /// It will also return an error if it encounters while reading an error
294 /// of a kind other than [`ErrorKind::Interrupted`],
295 /// or if the contents of the file are not valid UTF-8.
297 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
303 /// use std::net::SocketAddr;
305 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
306 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
310 #[stable(feature = "fs_read_write", since = "1.26.0")]
311 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
312 fn inner(path: &Path) -> io::Result<String> {
313 let mut file = File::open(path)?;
314 let mut string = String::with_capacity(initial_buffer_size(&file));
315 file.read_to_string(&mut string)?;
321 /// Write a slice as the entire contents of a file.
323 /// This function will create a file if it does not exist,
324 /// and will entirely replace its contents if it does.
326 /// This is a convenience function for using [`File::create`] and [`write_all`]
327 /// with fewer imports.
329 /// [`File::create`]: struct.File.html#method.create
330 /// [`write_all`]: ../io/trait.Write.html#method.write_all
337 /// fn main() -> std::io::Result<()> {
338 /// fs::write("foo.txt", b"Lorem ipsum")?;
339 /// fs::write("bar.txt", "dolor sit")?;
343 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
344 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
345 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
346 File::create(path)?.write_all(contents)
348 inner(path.as_ref(), contents.as_ref())
352 /// Attempts to open a file in read-only mode.
354 /// See the [`OpenOptions::open`] method for more details.
358 /// This function will return an error if `path` does not already exist.
359 /// Other errors may also be returned according to [`OpenOptions::open`].
361 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
366 /// use std::fs::File;
368 /// fn main() -> std::io::Result<()> {
369 /// let mut f = File::open("foo.txt")?;
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
375 OpenOptions::new().read(true).open(path.as_ref())
378 /// Opens a file in write-only mode.
380 /// This function will create a file if it does not exist,
381 /// and will truncate it if it does.
383 /// See the [`OpenOptions::open`] function for more details.
385 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
390 /// use std::fs::File;
392 /// fn main() -> std::io::Result<()> {
393 /// let mut f = File::create("foo.txt")?;
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
399 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
402 /// Returns a new OpenOptions object.
404 /// This function returns a new OpenOptions object that you can use to
405 /// open or create a file with specific options if `open()` or `create()`
406 /// are not appropriate.
408 /// It is equivalent to `OpenOptions::new()` but allows you to write more
409 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
410 /// you can write `File::with_options().read(true).open("foo.txt"). This
411 /// also avoids the need to import `OpenOptions`.
413 /// See the [`OpenOptions::new`] function for more details.
415 /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
420 /// #![feature(with_options)]
421 /// use std::fs::File;
423 /// fn main() -> std::io::Result<()> {
424 /// let mut f = File::with_options().read(true).open("foo.txt")?;
428 #[unstable(feature = "with_options", issue = "65439")]
429 pub fn with_options() -> OpenOptions {
433 /// Attempts to sync all OS-internal metadata to disk.
435 /// This function will attempt to ensure that all in-memory data reaches the
436 /// filesystem before returning.
438 /// This can be used to handle errors that would otherwise only be caught
439 /// when the `File` is closed. Dropping a file will ignore errors in
440 /// synchronizing this in-memory data.
445 /// use std::fs::File;
446 /// use std::io::prelude::*;
448 /// fn main() -> std::io::Result<()> {
449 /// let mut f = File::create("foo.txt")?;
450 /// f.write_all(b"Hello, world!")?;
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn sync_all(&self) -> io::Result<()> {
461 /// This function is similar to [`sync_all`], except that it may not
462 /// synchronize file metadata to the filesystem.
464 /// This is intended for use cases that must synchronize content, but don't
465 /// need the metadata on disk. The goal of this method is to reduce disk
468 /// Note that some platforms may simply implement this in terms of
471 /// [`sync_all`]: struct.File.html#method.sync_all
476 /// use std::fs::File;
477 /// use std::io::prelude::*;
479 /// fn main() -> std::io::Result<()> {
480 /// let mut f = File::create("foo.txt")?;
481 /// f.write_all(b"Hello, world!")?;
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn sync_data(&self) -> io::Result<()> {
489 self.inner.datasync()
492 /// Truncates or extends the underlying file, updating the size of
493 /// this file to become `size`.
495 /// If the `size` is less than the current file's size, then the file will
496 /// be shrunk. If it is greater than the current file's size, then the file
497 /// will be extended to `size` and have all of the intermediate data filled
500 /// The file's cursor isn't changed. In particular, if the cursor was at the
501 /// end and the file is shrunk using this operation, the cursor will now be
506 /// This function will return an error if the file is not opened for writing.
507 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
508 /// length would cause an overflow due to the implementation specifics.
513 /// use std::fs::File;
515 /// fn main() -> std::io::Result<()> {
516 /// let mut f = File::create("foo.txt")?;
522 /// Note that this method alters the content of the underlying file, even
523 /// though it takes `&self` rather than `&mut self`.
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn set_len(&self, size: u64) -> io::Result<()> {
526 self.inner.truncate(size)
529 /// Queries metadata about the underlying file.
534 /// use std::fs::File;
536 /// fn main() -> std::io::Result<()> {
537 /// let mut f = File::open("foo.txt")?;
538 /// let metadata = f.metadata()?;
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn metadata(&self) -> io::Result<Metadata> {
544 self.inner.file_attr().map(Metadata)
547 /// Creates a new `File` instance that shares the same underlying file handle
548 /// as the existing `File` instance. Reads, writes, and seeks will affect
549 /// both `File` instances simultaneously.
553 /// Creates two handles for a file named `foo.txt`:
556 /// use std::fs::File;
558 /// fn main() -> std::io::Result<()> {
559 /// let mut file = File::open("foo.txt")?;
560 /// let file_copy = file.try_clone()?;
565 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
566 /// two handles, seek one of them, and read the remaining bytes from the
570 /// use std::fs::File;
571 /// use std::io::SeekFrom;
572 /// use std::io::prelude::*;
574 /// fn main() -> std::io::Result<()> {
575 /// let mut file = File::open("foo.txt")?;
576 /// let mut file_copy = file.try_clone()?;
578 /// file.seek(SeekFrom::Start(3))?;
580 /// let mut contents = vec![];
581 /// file_copy.read_to_end(&mut contents)?;
582 /// assert_eq!(contents, b"def\n");
586 #[stable(feature = "file_try_clone", since = "1.9.0")]
587 pub fn try_clone(&self) -> io::Result<File> {
588 Ok(File { inner: self.inner.duplicate()? })
591 /// Changes the permissions on the underlying file.
593 /// # Platform-specific behavior
595 /// This function currently corresponds to the `fchmod` function on Unix and
596 /// the `SetFileInformationByHandle` function on Windows. Note that, this
597 /// [may change in the future][changes].
599 /// [changes]: ../io/index.html#platform-specific-behavior
603 /// This function will return an error if the user lacks permission change
604 /// attributes on the underlying file. It may also return an error in other
605 /// os-specific unspecified cases.
610 /// fn main() -> std::io::Result<()> {
611 /// use std::fs::File;
613 /// let file = File::open("foo.txt")?;
614 /// let mut perms = file.metadata()?.permissions();
615 /// perms.set_readonly(true);
616 /// file.set_permissions(perms)?;
621 /// Note that this method alters the permissions of the underlying file,
622 /// even though it takes `&self` rather than `&mut self`.
623 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
624 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
625 self.inner.set_permissions(perm.0)
629 impl AsInner<fs_imp::File> for File {
630 fn as_inner(&self) -> &fs_imp::File {
634 impl FromInner<fs_imp::File> for File {
635 fn from_inner(f: fs_imp::File) -> File {
639 impl IntoInner<fs_imp::File> for File {
640 fn into_inner(self) -> fs_imp::File {
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl fmt::Debug for File {
647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 #[stable(feature = "rust1", since = "1.0.0")]
654 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
658 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
659 self.inner.read_vectored(bufs)
663 unsafe fn initializer(&self) -> Initializer {
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl Write for File {
669 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
670 self.inner.write(buf)
673 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
674 self.inner.write_vectored(bufs)
677 fn flush(&mut self) -> io::Result<()> {
681 #[stable(feature = "rust1", since = "1.0.0")]
683 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl Read for &File {
689 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
693 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
694 self.inner.read_vectored(bufs)
698 unsafe fn initializer(&self) -> Initializer {
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl Write for &File {
704 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
705 self.inner.write(buf)
708 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
709 self.inner.write_vectored(bufs)
712 fn flush(&mut self) -> io::Result<()> {
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl Seek for &File {
718 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
724 /// Creates a blank new set of options ready for configuration.
726 /// All options are initially set to `false`.
731 /// use std::fs::OpenOptions;
733 /// let mut options = OpenOptions::new();
734 /// let file = options.read(true).open("foo.txt");
736 #[stable(feature = "rust1", since = "1.0.0")]
737 pub fn new() -> OpenOptions {
738 OpenOptions(fs_imp::OpenOptions::new())
741 /// Sets the option for read access.
743 /// This option, when true, will indicate that the file should be
744 /// `read`-able if opened.
749 /// use std::fs::OpenOptions;
751 /// let file = OpenOptions::new().read(true).open("foo.txt");
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
759 /// Sets the option for write access.
761 /// This option, when true, will indicate that the file should be
762 /// `write`-able if opened.
764 /// If the file already exists, any write calls on it will overwrite its
765 /// contents, without truncating it.
770 /// use std::fs::OpenOptions;
772 /// let file = OpenOptions::new().write(true).open("foo.txt");
774 #[stable(feature = "rust1", since = "1.0.0")]
775 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
780 /// Sets the option for the append mode.
782 /// This option, when true, means that writes will append to a file instead
783 /// of overwriting previous contents.
784 /// Note that setting `.write(true).append(true)` has the same effect as
785 /// setting only `.append(true)`.
787 /// For most filesystems, the operating system guarantees that all writes are
788 /// atomic: no writes get mangled because another process writes at the same
791 /// One maybe obvious note when using append-mode: make sure that all data
792 /// that belongs together is written to the file in one operation. This
793 /// can be done by concatenating strings before passing them to [`write()`],
794 /// or using a buffered writer (with a buffer of adequate size),
795 /// and calling [`flush()`] when the message is complete.
797 /// If a file is opened with both read and append access, beware that after
798 /// opening, and after every write, the position for reading may be set at the
799 /// end of the file. So, before writing, save the current position (using
800 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
804 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
807 /// [`write()`]: ../../std/fs/struct.File.html#method.write
808 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
809 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
810 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
811 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
812 /// [`create`]: #method.create
817 /// use std::fs::OpenOptions;
819 /// let file = OpenOptions::new().append(true).open("foo.txt");
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
823 self.0.append(append);
827 /// Sets the option for truncating a previous file.
829 /// If a file is successfully opened with this option set it will truncate
830 /// the file to 0 length if it already exists.
832 /// The file must be opened with write access for truncate to work.
837 /// use std::fs::OpenOptions;
839 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
841 #[stable(feature = "rust1", since = "1.0.0")]
842 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
843 self.0.truncate(truncate);
847 /// Sets the option to create a new file, or open it if it already exists.
849 /// In order for the file to be created, [`write`] or [`append`] access must
852 /// [`write`]: #method.write
853 /// [`append`]: #method.append
858 /// use std::fs::OpenOptions;
860 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
864 self.0.create(create);
868 /// Sets the option to create a new file, failing if it already exists.
870 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
871 /// way, if the call succeeds, the file returned is guaranteed to be new.
873 /// This option is useful because it is atomic. Otherwise between checking
874 /// whether a file exists and creating a new one, the file may have been
875 /// created by another process (a TOCTOU race condition / attack).
877 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
880 /// The file must be opened with write or append access in order to create
883 /// [`.create()`]: #method.create
884 /// [`.truncate()`]: #method.truncate
889 /// use std::fs::OpenOptions;
891 /// let file = OpenOptions::new().write(true)
892 /// .create_new(true)
893 /// .open("foo.txt");
895 #[stable(feature = "expand_open_options2", since = "1.9.0")]
896 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
897 self.0.create_new(create_new);
901 /// Opens a file at `path` with the options specified by `self`.
905 /// This function will return an error under a number of different
906 /// circumstances. Some of these error conditions are listed here, together
907 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
908 /// the compatibility contract of the function, especially the `Other` kind
909 /// might change to more specific kinds in the future.
911 /// * [`NotFound`]: The specified file does not exist and neither `create`
912 /// or `create_new` is set.
913 /// * [`NotFound`]: One of the directory components of the file path does
915 /// * [`PermissionDenied`]: The user lacks permission to get the specified
916 /// access rights for the file.
917 /// * [`PermissionDenied`]: The user lacks permission to open one of the
918 /// directory components of the specified path.
919 /// * [`AlreadyExists`]: `create_new` was specified and the file already
921 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
922 /// without write access, no access mode set, etc.).
923 /// * [`Other`]: One of the directory components of the specified file path
924 /// was not, in fact, a directory.
925 /// * [`Other`]: Filesystem-level errors: full disk, write permission
926 /// requested on a read-only file system, exceeded disk quota, too many
927 /// open files, too long filename, too many symbolic links in the
928 /// specified path (Unix-like systems only), etc.
933 /// use std::fs::OpenOptions;
935 /// let file = OpenOptions::new().read(true).open("foo.txt");
938 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
939 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
940 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
941 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
942 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
943 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
946 self._open(path.as_ref())
949 fn _open(&self, path: &Path) -> io::Result<File> {
950 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
954 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
955 fn as_inner(&self) -> &fs_imp::OpenOptions {
960 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
961 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
967 /// Returns the file type for this metadata.
972 /// fn main() -> std::io::Result<()> {
975 /// let metadata = fs::metadata("foo.txt")?;
977 /// println!("{:?}", metadata.file_type());
981 #[stable(feature = "file_type", since = "1.1.0")]
982 pub fn file_type(&self) -> FileType {
983 FileType(self.0.file_type())
986 /// Returns `true` if this metadata is for a directory. The
987 /// result is mutually exclusive to the result of
988 /// [`is_file`], and will be false for symlink metadata
989 /// obtained from [`symlink_metadata`].
991 /// [`is_file`]: struct.Metadata.html#method.is_file
992 /// [`symlink_metadata`]: fn.symlink_metadata.html
997 /// fn main() -> std::io::Result<()> {
1000 /// let metadata = fs::metadata("foo.txt")?;
1002 /// assert!(!metadata.is_dir());
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn is_dir(&self) -> bool {
1008 self.file_type().is_dir()
1011 /// Returns `true` if this metadata is for a regular file. The
1012 /// result is mutually exclusive to the result of
1013 /// [`is_dir`], and will be false for symlink metadata
1014 /// obtained from [`symlink_metadata`].
1016 /// [`is_dir`]: struct.Metadata.html#method.is_dir
1017 /// [`symlink_metadata`]: fn.symlink_metadata.html
1024 /// fn main() -> std::io::Result<()> {
1025 /// let metadata = fs::metadata("foo.txt")?;
1027 /// assert!(metadata.is_file());
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn is_file(&self) -> bool {
1033 self.file_type().is_file()
1036 /// Returns the size of the file, in bytes, this metadata is for.
1043 /// fn main() -> std::io::Result<()> {
1044 /// let metadata = fs::metadata("foo.txt")?;
1046 /// assert_eq!(0, metadata.len());
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 pub fn len(&self) -> u64 {
1055 /// Returns the permissions of the file this metadata is for.
1062 /// fn main() -> std::io::Result<()> {
1063 /// let metadata = fs::metadata("foo.txt")?;
1065 /// assert!(!metadata.permissions().readonly());
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 pub fn permissions(&self) -> Permissions {
1071 Permissions(self.0.perm())
1074 /// Returns the last modification time listed in this metadata.
1076 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1077 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1081 /// This field may not be available on all platforms, and will return an
1082 /// `Err` on platforms where it is not available.
1089 /// fn main() -> std::io::Result<()> {
1090 /// let metadata = fs::metadata("foo.txt")?;
1092 /// if let Ok(time) = metadata.modified() {
1093 /// println!("{:?}", time);
1095 /// println!("Not supported on this platform");
1100 #[stable(feature = "fs_time", since = "1.10.0")]
1101 pub fn modified(&self) -> io::Result<SystemTime> {
1102 self.0.modified().map(FromInner::from_inner)
1105 /// Returns the last access time of this metadata.
1107 /// The returned value corresponds to the `atime` field of `stat` on Unix
1108 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1110 /// Note that not all platforms will keep this field update in a file's
1111 /// metadata, for example Windows has an option to disable updating this
1112 /// time when files are accessed and Linux similarly has `noatime`.
1116 /// This field may not be available on all platforms, and will return an
1117 /// `Err` on platforms where it is not available.
1124 /// fn main() -> std::io::Result<()> {
1125 /// let metadata = fs::metadata("foo.txt")?;
1127 /// if let Ok(time) = metadata.accessed() {
1128 /// println!("{:?}", time);
1130 /// println!("Not supported on this platform");
1135 #[stable(feature = "fs_time", since = "1.10.0")]
1136 pub fn accessed(&self) -> io::Result<SystemTime> {
1137 self.0.accessed().map(FromInner::from_inner)
1140 /// Returns the creation time listed in this metadata.
1142 /// The returned value corresponds to the `btime` field of `statx` on
1143 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1144 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1148 /// This field may not be available on all platforms, and will return an
1149 /// `Err` on platforms or filesystems where it is not available.
1156 /// fn main() -> std::io::Result<()> {
1157 /// let metadata = fs::metadata("foo.txt")?;
1159 /// if let Ok(time) = metadata.created() {
1160 /// println!("{:?}", time);
1162 /// println!("Not supported on this platform or filesystem");
1167 #[stable(feature = "fs_time", since = "1.10.0")]
1168 pub fn created(&self) -> io::Result<SystemTime> {
1169 self.0.created().map(FromInner::from_inner)
1173 #[stable(feature = "std_debug", since = "1.16.0")]
1174 impl fmt::Debug for Metadata {
1175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176 f.debug_struct("Metadata")
1177 .field("file_type", &self.file_type())
1178 .field("is_dir", &self.is_dir())
1179 .field("is_file", &self.is_file())
1180 .field("permissions", &self.permissions())
1181 .field("modified", &self.modified())
1182 .field("accessed", &self.accessed())
1183 .field("created", &self.created())
1188 impl AsInner<fs_imp::FileAttr> for Metadata {
1189 fn as_inner(&self) -> &fs_imp::FileAttr {
1194 impl FromInner<fs_imp::FileAttr> for Metadata {
1195 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1201 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1206 /// use std::fs::File;
1208 /// fn main() -> std::io::Result<()> {
1209 /// let mut f = File::create("foo.txt")?;
1210 /// let metadata = f.metadata()?;
1212 /// assert_eq!(false, metadata.permissions().readonly());
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 pub fn readonly(&self) -> bool {
1221 /// Modifies the readonly flag for this set of permissions. If the
1222 /// `readonly` argument is `true`, using the resulting `Permission` will
1223 /// update file permissions to forbid writing. Conversely, if it's `false`,
1224 /// using the resulting `Permission` will update file permissions to allow
1227 /// This operation does **not** modify the filesystem. To modify the
1228 /// filesystem use the [`fs::set_permissions`] function.
1230 /// [`fs::set_permissions`]: fn.set_permissions.html
1235 /// use std::fs::File;
1237 /// fn main() -> std::io::Result<()> {
1238 /// let f = File::create("foo.txt")?;
1239 /// let metadata = f.metadata()?;
1240 /// let mut permissions = metadata.permissions();
1242 /// permissions.set_readonly(true);
1244 /// // filesystem doesn't change
1245 /// assert_eq!(false, metadata.permissions().readonly());
1247 /// // just this particular `permissions`.
1248 /// assert_eq!(true, permissions.readonly());
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 pub fn set_readonly(&mut self, readonly: bool) {
1254 self.0.set_readonly(readonly)
1259 /// Tests whether this file type represents a directory. The
1260 /// result is mutually exclusive to the results of
1261 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1264 /// [`is_file`]: struct.FileType.html#method.is_file
1265 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1270 /// fn main() -> std::io::Result<()> {
1273 /// let metadata = fs::metadata("foo.txt")?;
1274 /// let file_type = metadata.file_type();
1276 /// assert_eq!(file_type.is_dir(), false);
1280 #[stable(feature = "file_type", since = "1.1.0")]
1281 pub fn is_dir(&self) -> bool {
1285 /// Tests whether this file type represents a regular file.
1286 /// The result is mutually exclusive to the results of
1287 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1290 /// [`is_dir`]: struct.FileType.html#method.is_dir
1291 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1296 /// fn main() -> std::io::Result<()> {
1299 /// let metadata = fs::metadata("foo.txt")?;
1300 /// let file_type = metadata.file_type();
1302 /// assert_eq!(file_type.is_file(), true);
1306 #[stable(feature = "file_type", since = "1.1.0")]
1307 pub fn is_file(&self) -> bool {
1311 /// Tests whether this file type represents a symbolic link.
1312 /// The result is mutually exclusive to the results of
1313 /// [`is_dir`] and [`is_file`]; only zero or one of these
1316 /// The underlying [`Metadata`] struct needs to be retrieved
1317 /// with the [`fs::symlink_metadata`] function and not the
1318 /// [`fs::metadata`] function. The [`fs::metadata`] function
1319 /// follows symbolic links, so [`is_symlink`] would always
1320 /// return `false` for the target file.
1322 /// [`Metadata`]: struct.Metadata.html
1323 /// [`fs::metadata`]: fn.metadata.html
1324 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1325 /// [`is_dir`]: struct.FileType.html#method.is_dir
1326 /// [`is_file`]: struct.FileType.html#method.is_file
1327 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1334 /// fn main() -> std::io::Result<()> {
1335 /// let metadata = fs::symlink_metadata("foo.txt")?;
1336 /// let file_type = metadata.file_type();
1338 /// assert_eq!(file_type.is_symlink(), false);
1342 #[stable(feature = "file_type", since = "1.1.0")]
1343 pub fn is_symlink(&self) -> bool {
1348 impl AsInner<fs_imp::FileType> for FileType {
1349 fn as_inner(&self) -> &fs_imp::FileType {
1354 impl FromInner<fs_imp::FilePermissions> for Permissions {
1355 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1360 impl AsInner<fs_imp::FilePermissions> for Permissions {
1361 fn as_inner(&self) -> &fs_imp::FilePermissions {
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl Iterator for ReadDir {
1368 type Item = io::Result<DirEntry>;
1370 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1371 self.0.next().map(|entry| entry.map(DirEntry))
1376 /// Returns the full path to the file that this entry represents.
1378 /// The full path is created by joining the original path to `read_dir`
1379 /// with the filename of this entry.
1386 /// fn main() -> std::io::Result<()> {
1387 /// for entry in fs::read_dir(".")? {
1388 /// let dir = entry?;
1389 /// println!("{:?}", dir.path());
1395 /// This prints output like:
1398 /// "./whatever.txt"
1400 /// "./hello_world.rs"
1403 /// The exact text, of course, depends on what files you have in `.`.
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn path(&self) -> PathBuf {
1409 /// Returns the metadata for the file that this entry points at.
1411 /// This function will not traverse symlinks if this entry points at a
1414 /// # Platform-specific behavior
1416 /// On Windows this function is cheap to call (no extra system calls
1417 /// needed), but on Unix platforms this function is the equivalent of
1418 /// calling `symlink_metadata` on the path.
1425 /// if let Ok(entries) = fs::read_dir(".") {
1426 /// for entry in entries {
1427 /// if let Ok(entry) = entry {
1428 /// // Here, `entry` is a `DirEntry`.
1429 /// if let Ok(metadata) = entry.metadata() {
1430 /// // Now let's show our entry's permissions!
1431 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1433 /// println!("Couldn't get metadata for {:?}", entry.path());
1439 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1440 pub fn metadata(&self) -> io::Result<Metadata> {
1441 self.0.metadata().map(Metadata)
1444 /// Returns the file type for the file that this entry points at.
1446 /// This function will not traverse symlinks if this entry points at a
1449 /// # Platform-specific behavior
1451 /// On Windows and most Unix platforms this function is free (no extra
1452 /// system calls needed), but some Unix platforms may require the equivalent
1453 /// call to `symlink_metadata` to learn about the target file type.
1460 /// if let Ok(entries) = fs::read_dir(".") {
1461 /// for entry in entries {
1462 /// if let Ok(entry) = entry {
1463 /// // Here, `entry` is a `DirEntry`.
1464 /// if let Ok(file_type) = entry.file_type() {
1465 /// // Now let's show our entry's file type!
1466 /// println!("{:?}: {:?}", entry.path(), file_type);
1468 /// println!("Couldn't get file type for {:?}", entry.path());
1474 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1475 pub fn file_type(&self) -> io::Result<FileType> {
1476 self.0.file_type().map(FileType)
1479 /// Returns the bare file name of this directory entry without any other
1480 /// leading path component.
1487 /// if let Ok(entries) = fs::read_dir(".") {
1488 /// for entry in entries {
1489 /// if let Ok(entry) = entry {
1490 /// // Here, `entry` is a `DirEntry`.
1491 /// println!("{:?}", entry.file_name());
1496 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1497 pub fn file_name(&self) -> OsString {
1502 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1503 impl fmt::Debug for DirEntry {
1504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1505 f.debug_tuple("DirEntry").field(&self.path()).finish()
1509 impl AsInner<fs_imp::DirEntry> for DirEntry {
1510 fn as_inner(&self) -> &fs_imp::DirEntry {
1515 /// Removes a file from the filesystem.
1517 /// Note that there is no
1518 /// guarantee that the file is immediately deleted (e.g., depending on
1519 /// platform, other open file descriptors may prevent immediate removal).
1521 /// # Platform-specific behavior
1523 /// This function currently corresponds to the `unlink` function on Unix
1524 /// and the `DeleteFile` function on Windows.
1525 /// Note that, this [may change in the future][changes].
1527 /// [changes]: ../io/index.html#platform-specific-behavior
1531 /// This function will return an error in the following situations, but is not
1532 /// limited to just these cases:
1534 /// * `path` points to a directory.
1535 /// * The user lacks permissions to remove the file.
1542 /// fn main() -> std::io::Result<()> {
1543 /// fs::remove_file("a.txt")?;
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1549 fs_imp::unlink(path.as_ref())
1552 /// Given a path, query the file system to get information about a file,
1555 /// This function will traverse symbolic links to query information about the
1556 /// destination file.
1558 /// # Platform-specific behavior
1560 /// This function currently corresponds to the `stat` function on Unix
1561 /// and the `GetFileAttributesEx` function on Windows.
1562 /// Note that, this [may change in the future][changes].
1564 /// [changes]: ../io/index.html#platform-specific-behavior
1568 /// This function will return an error in the following situations, but is not
1569 /// limited to just these cases:
1571 /// * The user lacks permissions to perform `metadata` call on `path`.
1572 /// * `path` does not exist.
1579 /// fn main() -> std::io::Result<()> {
1580 /// let attr = fs::metadata("/some/file/path.txt")?;
1581 /// // inspect attr ...
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1587 fs_imp::stat(path.as_ref()).map(Metadata)
1590 /// Query the metadata about a file without following symlinks.
1592 /// # Platform-specific behavior
1594 /// This function currently corresponds to the `lstat` function on Unix
1595 /// and the `GetFileAttributesEx` function on Windows.
1596 /// Note that, this [may change in the future][changes].
1598 /// [changes]: ../io/index.html#platform-specific-behavior
1602 /// This function will return an error in the following situations, but is not
1603 /// limited to just these cases:
1605 /// * The user lacks permissions to perform `metadata` call on `path`.
1606 /// * `path` does not exist.
1613 /// fn main() -> std::io::Result<()> {
1614 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1615 /// // inspect attr ...
1619 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1620 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1621 fs_imp::lstat(path.as_ref()).map(Metadata)
1624 /// Rename a file or directory to a new name, replacing the original file if
1625 /// `to` already exists.
1627 /// This will not work if the new name is on a different mount point.
1629 /// # Platform-specific behavior
1631 /// This function currently corresponds to the `rename` function on Unix
1632 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1634 /// Because of this, the behavior when both `from` and `to` exist differs. On
1635 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1636 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1637 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1639 /// Note that, this [may change in the future][changes].
1641 /// [changes]: ../io/index.html#platform-specific-behavior
1645 /// This function will return an error in the following situations, but is not
1646 /// limited to just these cases:
1648 /// * `from` does not exist.
1649 /// * The user lacks permissions to view contents.
1650 /// * `from` and `to` are on separate filesystems.
1657 /// fn main() -> std::io::Result<()> {
1658 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1664 fs_imp::rename(from.as_ref(), to.as_ref())
1667 /// Copies the contents of one file to another. This function will also
1668 /// copy the permission bits of the original file to the destination file.
1670 /// This function will **overwrite** the contents of `to`.
1672 /// Note that if `from` and `to` both point to the same file, then the file
1673 /// will likely get truncated by this operation.
1675 /// On success, the total number of bytes copied is returned and it is equal to
1676 /// the length of the `to` file as reported by `metadata`.
1678 /// If you’re wanting to copy the contents of one file to another and you’re
1679 /// working with [`File`]s, see the [`io::copy`] function.
1681 /// [`io::copy`]: ../io/fn.copy.html
1682 /// [`File`]: ./struct.File.html
1684 /// # Platform-specific behavior
1686 /// This function currently corresponds to the `open` function in Unix
1687 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1688 /// `O_CLOEXEC` is set for returned file descriptors.
1689 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1690 /// NTFS streams are copied but only the size of the main stream is returned by
1691 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1693 /// Note that, this [may change in the future][changes].
1695 /// [changes]: ../io/index.html#platform-specific-behavior
1699 /// This function will return an error in the following situations, but is not
1700 /// limited to just these cases:
1702 /// * The `from` path is not a file.
1703 /// * The `from` file does not exist.
1704 /// * The current process does not have the permission rights to access
1705 /// `from` or write `to`.
1712 /// fn main() -> std::io::Result<()> {
1713 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1719 fs_imp::copy(from.as_ref(), to.as_ref())
1722 /// Creates a new hard link on the filesystem.
1724 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1725 /// often require these two paths to both be located on the same filesystem.
1727 /// # Platform-specific behavior
1729 /// This function currently corresponds to the `link` function on Unix
1730 /// and the `CreateHardLink` function on Windows.
1731 /// Note that, this [may change in the future][changes].
1733 /// [changes]: ../io/index.html#platform-specific-behavior
1737 /// This function will return an error in the following situations, but is not
1738 /// limited to just these cases:
1740 /// * The `src` path is not a file or doesn't exist.
1747 /// fn main() -> std::io::Result<()> {
1748 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1754 fs_imp::link(src.as_ref(), dst.as_ref())
1757 /// Creates a new symbolic link on the filesystem.
1759 /// The `dst` path will be a symbolic link pointing to the `src` path.
1760 /// On Windows, this will be a file symlink, not a directory symlink;
1761 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1762 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1763 /// used instead to make the intent explicit.
1765 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1766 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1767 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1775 /// fn main() -> std::io::Result<()> {
1776 /// fs::soft_link("a.txt", "b.txt")?;
1780 #[stable(feature = "rust1", since = "1.0.0")]
1783 reason = "replaced with std::os::unix::fs::symlink and \
1784 std::os::windows::fs::{symlink_file, symlink_dir}"
1786 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1787 fs_imp::symlink(src.as_ref(), dst.as_ref())
1790 /// Reads a symbolic link, returning the file that the link points to.
1792 /// # Platform-specific behavior
1794 /// This function currently corresponds to the `readlink` function on Unix
1795 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1796 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1797 /// Note that, this [may change in the future][changes].
1799 /// [changes]: ../io/index.html#platform-specific-behavior
1803 /// This function will return an error in the following situations, but is not
1804 /// limited to just these cases:
1806 /// * `path` is not a symbolic link.
1807 /// * `path` does not exist.
1814 /// fn main() -> std::io::Result<()> {
1815 /// let path = fs::read_link("a.txt")?;
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1821 fs_imp::readlink(path.as_ref())
1824 /// Returns the canonical, absolute form of a path with all intermediate
1825 /// components normalized and symbolic links resolved.
1827 /// # Platform-specific behavior
1829 /// This function currently corresponds to the `realpath` function on Unix
1830 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1831 /// Note that, this [may change in the future][changes].
1833 /// On Windows, this converts the path to use [extended length path][path]
1834 /// syntax, which allows your program to use longer path names, but means you
1835 /// can only join backslash-delimited paths to it, and it may be incompatible
1836 /// with other applications (if passed to the application on the command-line,
1837 /// or written to a file another application may read).
1839 /// [changes]: ../io/index.html#platform-specific-behavior
1840 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1844 /// This function will return an error in the following situations, but is not
1845 /// limited to just these cases:
1847 /// * `path` does not exist.
1848 /// * A non-final component in path is not a directory.
1855 /// fn main() -> std::io::Result<()> {
1856 /// let path = fs::canonicalize("../a/../foo.txt")?;
1860 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1861 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1862 fs_imp::canonicalize(path.as_ref())
1865 /// Creates a new, empty directory at the provided path
1867 /// # Platform-specific behavior
1869 /// This function currently corresponds to the `mkdir` function on Unix
1870 /// and the `CreateDirectory` function on Windows.
1871 /// Note that, this [may change in the future][changes].
1873 /// [changes]: ../io/index.html#platform-specific-behavior
1875 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1876 /// return an error. To create a directory and all its missing parents at the
1877 /// same time, use the [`create_dir_all`] function.
1881 /// This function will return an error in the following situations, but is not
1882 /// limited to just these cases:
1884 /// * User lacks permissions to create directory at `path`.
1885 /// * A parent of the given path doesn't exist. (To create a directory and all
1886 /// its missing parents at the same time, use the [`create_dir_all`]
1888 /// * `path` already exists.
1890 /// [`create_dir_all`]: fn.create_dir_all.html
1897 /// fn main() -> std::io::Result<()> {
1898 /// fs::create_dir("/some/dir")?;
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1904 DirBuilder::new().create(path.as_ref())
1907 /// Recursively create a directory and all of its parent components if they
1910 /// # Platform-specific behavior
1912 /// This function currently corresponds to the `mkdir` function on Unix
1913 /// and the `CreateDirectory` function on Windows.
1914 /// Note that, this [may change in the future][changes].
1916 /// [changes]: ../io/index.html#platform-specific-behavior
1920 /// This function will return an error in the following situations, but is not
1921 /// limited to just these cases:
1923 /// * If any directory in the path specified by `path`
1924 /// does not already exist and it could not be created otherwise. The specific
1925 /// error conditions for when a directory is being created (after it is
1926 /// determined to not exist) are outlined by [`fs::create_dir`].
1928 /// Notable exception is made for situations where any of the directories
1929 /// specified in the `path` could not be created as it was being created concurrently.
1930 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1931 /// concurrently from multiple threads or processes is guaranteed not to fail
1932 /// due to a race condition with itself.
1934 /// [`fs::create_dir`]: fn.create_dir.html
1941 /// fn main() -> std::io::Result<()> {
1942 /// fs::create_dir_all("/some/dir")?;
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1948 DirBuilder::new().recursive(true).create(path.as_ref())
1951 /// Removes an existing, empty directory.
1953 /// # Platform-specific behavior
1955 /// This function currently corresponds to the `rmdir` function on Unix
1956 /// and the `RemoveDirectory` function on Windows.
1957 /// Note that, this [may change in the future][changes].
1959 /// [changes]: ../io/index.html#platform-specific-behavior
1963 /// This function will return an error in the following situations, but is not
1964 /// limited to just these cases:
1966 /// * The user lacks permissions to remove the directory at the provided `path`.
1967 /// * The directory isn't empty.
1974 /// fn main() -> std::io::Result<()> {
1975 /// fs::remove_dir("/some/dir")?;
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1981 fs_imp::rmdir(path.as_ref())
1984 /// Removes a directory at this path, after removing all its contents. Use
1987 /// This function does **not** follow symbolic links and it will simply remove the
1988 /// symbolic link itself.
1990 /// # Platform-specific behavior
1992 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1993 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1995 /// Note that, this [may change in the future][changes].
1997 /// [changes]: ../io/index.html#platform-specific-behavior
2001 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2003 /// [`fs::remove_file`]: fn.remove_file.html
2004 /// [`fs::remove_dir`]: fn.remove_dir.html
2011 /// fn main() -> std::io::Result<()> {
2012 /// fs::remove_dir_all("/some/dir")?;
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2018 fs_imp::remove_dir_all(path.as_ref())
2021 /// Returns an iterator over the entries within a directory.
2023 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2024 /// New errors may be encountered after an iterator is initially constructed.
2026 /// [`io::Result`]: ../io/type.Result.html
2027 /// [`DirEntry`]: struct.DirEntry.html
2029 /// # Platform-specific behavior
2031 /// This function currently corresponds to the `opendir` function on Unix
2032 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2033 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2034 /// Note that, this [may change in the future][changes].
2036 /// [changes]: ../io/index.html#platform-specific-behavior
2038 /// The order in which this iterator returns entries is platform and filesystem
2043 /// This function will return an error in the following situations, but is not
2044 /// limited to just these cases:
2046 /// * The provided `path` doesn't exist.
2047 /// * The process lacks permissions to view the contents.
2048 /// * The `path` points at a non-directory file.
2054 /// use std::fs::{self, DirEntry};
2055 /// use std::path::Path;
2057 /// // one possible implementation of walking a directory only visiting files
2058 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2059 /// if dir.is_dir() {
2060 /// for entry in fs::read_dir(dir)? {
2061 /// let entry = entry?;
2062 /// let path = entry.path();
2063 /// if path.is_dir() {
2064 /// visit_dirs(&path, cb)?;
2075 /// use std::{fs, io};
2077 /// fn main() -> io::Result<()> {
2078 /// let mut entries = fs::read_dir(".")?
2079 /// .map(|res| res.map(|e| e.path()))
2080 /// .collect::<Result<Vec<_>, io::Error>>()?;
2082 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2083 /// // ordering is required the entries should be explicitly sorted.
2087 /// // The entries have now been sorted by their path.
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2094 fs_imp::readdir(path.as_ref()).map(ReadDir)
2097 /// Changes the permissions found on a file or a directory.
2099 /// # Platform-specific behavior
2101 /// This function currently corresponds to the `chmod` function on Unix
2102 /// and the `SetFileAttributes` function on Windows.
2103 /// Note that, this [may change in the future][changes].
2105 /// [changes]: ../io/index.html#platform-specific-behavior
2109 /// This function will return an error in the following situations, but is not
2110 /// limited to just these cases:
2112 /// * `path` does not exist.
2113 /// * The user lacks the permission to change attributes of the file.
2120 /// fn main() -> std::io::Result<()> {
2121 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2122 /// perms.set_readonly(true);
2123 /// fs::set_permissions("foo.txt", perms)?;
2127 #[stable(feature = "set_permissions", since = "1.1.0")]
2128 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2129 fs_imp::set_perm(path.as_ref(), perm.0)
2133 /// Creates a new set of options with default mode/security settings for all
2134 /// platforms and also non-recursive.
2139 /// use std::fs::DirBuilder;
2141 /// let builder = DirBuilder::new();
2143 #[stable(feature = "dir_builder", since = "1.6.0")]
2144 pub fn new() -> DirBuilder {
2145 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2148 /// Indicates that directories should be created recursively, creating all
2149 /// parent directories. Parents that do not exist are created with the same
2150 /// security and permissions settings.
2152 /// This option defaults to `false`.
2157 /// use std::fs::DirBuilder;
2159 /// let mut builder = DirBuilder::new();
2160 /// builder.recursive(true);
2162 #[stable(feature = "dir_builder", since = "1.6.0")]
2163 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2164 self.recursive = recursive;
2168 /// Creates the specified directory with the options configured in this
2171 /// It is considered an error if the directory already exists unless
2172 /// recursive mode is enabled.
2177 /// use std::fs::{self, DirBuilder};
2179 /// let path = "/tmp/foo/bar/baz";
2180 /// DirBuilder::new()
2181 /// .recursive(true)
2182 /// .create(path).unwrap();
2184 /// assert!(fs::metadata(path).unwrap().is_dir());
2186 #[stable(feature = "dir_builder", since = "1.6.0")]
2187 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2188 self._create(path.as_ref())
2191 fn _create(&self, path: &Path) -> io::Result<()> {
2192 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2195 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2196 if path == Path::new("") {
2200 match self.inner.mkdir(path) {
2201 Ok(()) => return Ok(()),
2202 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2203 Err(_) if path.is_dir() => return Ok(()),
2204 Err(e) => return Err(e),
2206 match path.parent() {
2207 Some(p) => self.create_dir_all(p)?,
2209 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2212 match self.inner.mkdir(path) {
2214 Err(_) if path.is_dir() => Ok(()),
2220 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2221 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2226 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2228 use crate::io::prelude::*;
2230 use crate::fs::{self, File, OpenOptions};
2231 use crate::io::{ErrorKind, SeekFrom};
2232 use crate::path::Path;
2234 use crate::sys_common::io::test::{tmpdir, TempDir};
2237 use rand::{rngs::StdRng, RngCore, SeedableRng};
2240 use crate::os::unix::fs::symlink as symlink_dir;
2242 use crate::os::unix::fs::symlink as symlink_file;
2244 use crate::os::unix::fs::symlink as symlink_junction;
2246 use crate::os::windows::fs::{symlink_dir, symlink_file};
2248 use crate::sys::fs::symlink_junction;
2250 macro_rules! check {
2254 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2260 macro_rules! error {
2261 ($e:expr, $s:expr) => {
2263 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2264 Err(ref err) => assert!(
2265 err.raw_os_error() == Some($s),
2266 format!("`{}` did not have a code of `{}`", err, $s)
2273 macro_rules! error {
2274 ($e:expr, $s:expr) => {
2275 error_contains!($e, $s)
2279 macro_rules! error_contains {
2280 ($e:expr, $s:expr) => {
2282 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2283 Err(ref err) => assert!(
2284 err.to_string().contains($s),
2285 format!("`{}` did not contain `{}`", err, $s)
2291 // Several test fail on windows if the user does not have permission to
2292 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2293 // disabling these test on Windows, use this function to test whether we
2294 // have permission, and return otherwise. This way, we still don't run these
2295 // tests most of the time, but at least we do if the user has the right
2297 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2301 let link = tmpdir.join("some_hopefully_unique_link_name");
2303 match symlink_file(r"nonexisting_target", link) {
2305 // ERROR_PRIVILEGE_NOT_HELD = 1314
2306 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2312 fn file_test_io_smoke_test() {
2313 let message = "it's alright. have a good time";
2314 let tmpdir = tmpdir();
2315 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2317 let mut write_stream = check!(File::create(filename));
2318 check!(write_stream.write(message.as_bytes()));
2321 let mut read_stream = check!(File::open(filename));
2322 let mut read_buf = [0; 1028];
2323 let read_str = match check!(read_stream.read(&mut read_buf)) {
2324 0 => panic!("shouldn't happen"),
2325 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2327 assert_eq!(read_str, message);
2329 check!(fs::remove_file(filename));
2333 fn invalid_path_raises() {
2334 let tmpdir = tmpdir();
2335 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2336 let result = File::open(filename);
2338 #[cfg(all(unix, not(target_os = "vxworks")))]
2339 error!(result, "No such file or directory");
2340 #[cfg(target_os = "vxworks")]
2341 error!(result, "no such file or directory");
2343 error!(result, 2); // ERROR_FILE_NOT_FOUND
2347 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2348 let tmpdir = tmpdir();
2349 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2351 let result = fs::remove_file(filename);
2353 #[cfg(all(unix, not(target_os = "vxworks")))]
2354 error!(result, "No such file or directory");
2355 #[cfg(target_os = "vxworks")]
2356 error!(result, "no such file or directory");
2358 error!(result, 2); // ERROR_FILE_NOT_FOUND
2362 fn file_test_io_non_positional_read() {
2363 let message: &str = "ten-four";
2364 let mut read_mem = [0; 8];
2365 let tmpdir = tmpdir();
2366 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2368 let mut rw_stream = check!(File::create(filename));
2369 check!(rw_stream.write(message.as_bytes()));
2372 let mut read_stream = check!(File::open(filename));
2374 let read_buf = &mut read_mem[0..4];
2375 check!(read_stream.read(read_buf));
2378 let read_buf = &mut read_mem[4..8];
2379 check!(read_stream.read(read_buf));
2382 check!(fs::remove_file(filename));
2383 let read_str = str::from_utf8(&read_mem).unwrap();
2384 assert_eq!(read_str, message);
2388 fn file_test_io_seek_and_tell_smoke_test() {
2389 let message = "ten-four";
2390 let mut read_mem = [0; 4];
2391 let set_cursor = 4 as u64;
2392 let tell_pos_pre_read;
2393 let tell_pos_post_read;
2394 let tmpdir = tmpdir();
2395 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2397 let mut rw_stream = check!(File::create(filename));
2398 check!(rw_stream.write(message.as_bytes()));
2401 let mut read_stream = check!(File::open(filename));
2402 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2403 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2404 check!(read_stream.read(&mut read_mem));
2405 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2407 check!(fs::remove_file(filename));
2408 let read_str = str::from_utf8(&read_mem).unwrap();
2409 assert_eq!(read_str, &message[4..8]);
2410 assert_eq!(tell_pos_pre_read, set_cursor);
2411 assert_eq!(tell_pos_post_read, message.len() as u64);
2415 fn file_test_io_seek_and_write() {
2416 let initial_msg = "food-is-yummy";
2417 let overwrite_msg = "-the-bar!!";
2418 let final_msg = "foo-the-bar!!";
2420 let mut read_mem = [0; 13];
2421 let tmpdir = tmpdir();
2422 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2424 let mut rw_stream = check!(File::create(filename));
2425 check!(rw_stream.write(initial_msg.as_bytes()));
2426 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2427 check!(rw_stream.write(overwrite_msg.as_bytes()));
2430 let mut read_stream = check!(File::open(filename));
2431 check!(read_stream.read(&mut read_mem));
2433 check!(fs::remove_file(filename));
2434 let read_str = str::from_utf8(&read_mem).unwrap();
2435 assert!(read_str == final_msg);
2439 fn file_test_io_seek_shakedown() {
2441 let initial_msg = "qwer-asdf-zxcv";
2442 let chunk_one: &str = "qwer";
2443 let chunk_two: &str = "asdf";
2444 let chunk_three: &str = "zxcv";
2445 let mut read_mem = [0; 4];
2446 let tmpdir = tmpdir();
2447 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2449 let mut rw_stream = check!(File::create(filename));
2450 check!(rw_stream.write(initial_msg.as_bytes()));
2453 let mut read_stream = check!(File::open(filename));
2455 check!(read_stream.seek(SeekFrom::End(-4)));
2456 check!(read_stream.read(&mut read_mem));
2457 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2459 check!(read_stream.seek(SeekFrom::Current(-9)));
2460 check!(read_stream.read(&mut read_mem));
2461 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2463 check!(read_stream.seek(SeekFrom::Start(0)));
2464 check!(read_stream.read(&mut read_mem));
2465 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2467 check!(fs::remove_file(filename));
2471 fn file_test_io_eof() {
2472 let tmpdir = tmpdir();
2473 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2474 let mut buf = [0; 256];
2476 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2477 let mut rw = check!(oo.open(&filename));
2478 assert_eq!(check!(rw.read(&mut buf)), 0);
2479 assert_eq!(check!(rw.read(&mut buf)), 0);
2481 check!(fs::remove_file(&filename));
2486 fn file_test_io_read_write_at() {
2487 use crate::os::unix::fs::FileExt;
2489 let tmpdir = tmpdir();
2490 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2491 let mut buf = [0; 256];
2492 let write1 = "asdf";
2493 let write2 = "qwer-";
2494 let write3 = "-zxcv";
2495 let content = "qwer-asdf-zxcv";
2497 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2498 let mut rw = check!(oo.open(&filename));
2499 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2500 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2501 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2502 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2503 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2504 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2505 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2506 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2507 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2508 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2509 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2510 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2511 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2512 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2513 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2514 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2515 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2516 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2519 let mut read = check!(File::open(&filename));
2520 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2521 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2522 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2523 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2524 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2525 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2526 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2527 assert_eq!(check!(read.read(&mut buf)), write3.len());
2528 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2529 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2530 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2531 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2532 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2533 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2534 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2535 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2537 check!(fs::remove_file(&filename));
2542 fn set_get_unix_permissions() {
2543 use crate::os::unix::fs::PermissionsExt;
2545 let tmpdir = tmpdir();
2546 let filename = &tmpdir.join("set_get_unix_permissions");
2547 check!(fs::create_dir(filename));
2550 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2551 let metadata0 = check!(fs::metadata(filename));
2552 assert_eq!(mask & metadata0.permissions().mode(), 0);
2554 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2555 let metadata1 = check!(fs::metadata(filename));
2556 #[cfg(all(unix, not(target_os = "vxworks")))]
2557 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2558 #[cfg(target_os = "vxworks")]
2559 assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2564 fn file_test_io_seek_read_write() {
2565 use crate::os::windows::fs::FileExt;
2567 let tmpdir = tmpdir();
2568 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2569 let mut buf = [0; 256];
2570 let write1 = "asdf";
2571 let write2 = "qwer-";
2572 let write3 = "-zxcv";
2573 let content = "qwer-asdf-zxcv";
2575 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2576 let mut rw = check!(oo.open(&filename));
2577 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2578 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2579 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2580 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2581 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2582 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2583 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2584 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2585 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2586 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2587 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2588 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2589 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2590 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2591 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2592 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2595 let mut read = check!(File::open(&filename));
2596 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2597 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2598 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2599 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2600 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2601 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2602 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2603 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2604 assert_eq!(check!(read.read(&mut buf)), write3.len());
2605 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2606 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2607 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2608 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2609 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2610 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2611 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2613 check!(fs::remove_file(&filename));
2617 fn file_test_stat_is_correct_on_is_file() {
2618 let tmpdir = tmpdir();
2619 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2621 let mut opts = OpenOptions::new();
2622 let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2624 fs.write(msg.as_bytes()).unwrap();
2626 let fstat_res = check!(fs.metadata());
2627 assert!(fstat_res.is_file());
2629 let stat_res_fn = check!(fs::metadata(filename));
2630 assert!(stat_res_fn.is_file());
2631 let stat_res_meth = check!(filename.metadata());
2632 assert!(stat_res_meth.is_file());
2633 check!(fs::remove_file(filename));
2637 fn file_test_stat_is_correct_on_is_dir() {
2638 let tmpdir = tmpdir();
2639 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2640 check!(fs::create_dir(filename));
2641 let stat_res_fn = check!(fs::metadata(filename));
2642 assert!(stat_res_fn.is_dir());
2643 let stat_res_meth = check!(filename.metadata());
2644 assert!(stat_res_meth.is_dir());
2645 check!(fs::remove_dir(filename));
2649 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2650 let tmpdir = tmpdir();
2651 let dir = &tmpdir.join("fileinfo_false_on_dir");
2652 check!(fs::create_dir(dir));
2653 assert!(!dir.is_file());
2654 check!(fs::remove_dir(dir));
2658 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2659 let tmpdir = tmpdir();
2660 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2661 check!(check!(File::create(file)).write(b"foo"));
2662 assert!(file.exists());
2663 check!(fs::remove_file(file));
2664 assert!(!file.exists());
2668 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2669 let tmpdir = tmpdir();
2670 let dir = &tmpdir.join("before_and_after_dir");
2671 assert!(!dir.exists());
2672 check!(fs::create_dir(dir));
2673 assert!(dir.exists());
2674 assert!(dir.is_dir());
2675 check!(fs::remove_dir(dir));
2676 assert!(!dir.exists());
2680 fn file_test_directoryinfo_readdir() {
2681 let tmpdir = tmpdir();
2682 let dir = &tmpdir.join("di_readdir");
2683 check!(fs::create_dir(dir));
2686 let f = dir.join(&format!("{}.txt", n));
2687 let mut w = check!(File::create(&f));
2688 let msg_str = format!("{}{}", prefix, n.to_string());
2689 let msg = msg_str.as_bytes();
2690 check!(w.write(msg));
2692 let files = check!(fs::read_dir(dir));
2693 let mut mem = [0; 4];
2695 let f = f.unwrap().path();
2697 let n = f.file_stem().unwrap();
2698 check!(check!(File::open(&f)).read(&mut mem));
2699 let read_str = str::from_utf8(&mem).unwrap();
2700 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2701 assert_eq!(expected, read_str);
2703 check!(fs::remove_file(&f));
2705 check!(fs::remove_dir(dir));
2709 fn file_create_new_already_exists_error() {
2710 let tmpdir = tmpdir();
2711 let file = &tmpdir.join("file_create_new_error_exists");
2712 check!(fs::File::create(file));
2713 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2714 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2718 fn mkdir_path_already_exists_error() {
2719 let tmpdir = tmpdir();
2720 let dir = &tmpdir.join("mkdir_error_twice");
2721 check!(fs::create_dir(dir));
2722 let e = fs::create_dir(dir).unwrap_err();
2723 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2727 fn recursive_mkdir() {
2728 let tmpdir = tmpdir();
2729 let dir = tmpdir.join("d1/d2");
2730 check!(fs::create_dir_all(&dir));
2731 assert!(dir.is_dir())
2735 fn recursive_mkdir_failure() {
2736 let tmpdir = tmpdir();
2737 let dir = tmpdir.join("d1");
2738 let file = dir.join("f1");
2740 check!(fs::create_dir_all(&dir));
2741 check!(File::create(&file));
2743 let result = fs::create_dir_all(&file);
2745 assert!(result.is_err());
2749 fn concurrent_recursive_mkdir() {
2752 let mut dir = dir.join("a");
2754 dir = dir.join("a");
2756 let mut join = vec![];
2758 let dir = dir.clone();
2759 join.push(thread::spawn(move || {
2760 check!(fs::create_dir_all(&dir));
2764 // No `Display` on result of `join()`
2765 join.drain(..).map(|join| join.join().unwrap()).count();
2770 fn recursive_mkdir_slash() {
2771 check!(fs::create_dir_all(Path::new("/")));
2775 fn recursive_mkdir_dot() {
2776 check!(fs::create_dir_all(Path::new(".")));
2780 fn recursive_mkdir_empty() {
2781 check!(fs::create_dir_all(Path::new("")));
2785 fn recursive_rmdir() {
2786 let tmpdir = tmpdir();
2787 let d1 = tmpdir.join("d1");
2788 let dt = d1.join("t");
2789 let dtt = dt.join("t");
2790 let d2 = tmpdir.join("d2");
2791 let canary = d2.join("do_not_delete");
2792 check!(fs::create_dir_all(&dtt));
2793 check!(fs::create_dir_all(&d2));
2794 check!(check!(File::create(&canary)).write(b"foo"));
2795 check!(symlink_junction(&d2, &dt.join("d2")));
2796 let _ = symlink_file(&canary, &d1.join("canary"));
2797 check!(fs::remove_dir_all(&d1));
2799 assert!(!d1.is_dir());
2800 assert!(canary.exists());
2804 fn recursive_rmdir_of_symlink() {
2805 // test we do not recursively delete a symlink but only dirs.
2806 let tmpdir = tmpdir();
2807 let link = tmpdir.join("d1");
2808 let dir = tmpdir.join("d2");
2809 let canary = dir.join("do_not_delete");
2810 check!(fs::create_dir_all(&dir));
2811 check!(check!(File::create(&canary)).write(b"foo"));
2812 check!(symlink_junction(&dir, &link));
2813 check!(fs::remove_dir_all(&link));
2815 assert!(!link.is_dir());
2816 assert!(canary.exists());
2820 // only Windows makes a distinction between file and directory symlinks.
2822 fn recursive_rmdir_of_file_symlink() {
2823 let tmpdir = tmpdir();
2824 if !got_symlink_permission(&tmpdir) {
2828 let f1 = tmpdir.join("f1");
2829 let f2 = tmpdir.join("f2");
2830 check!(check!(File::create(&f1)).write(b"foo"));
2831 check!(symlink_file(&f1, &f2));
2832 match fs::remove_dir_all(&f2) {
2833 Ok(..) => panic!("wanted a failure"),
2839 fn unicode_path_is_dir() {
2840 assert!(Path::new(".").is_dir());
2841 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2843 let tmpdir = tmpdir();
2845 let mut dirpath = tmpdir.path().to_path_buf();
2846 dirpath.push("test-가一ー你好");
2847 check!(fs::create_dir(&dirpath));
2848 assert!(dirpath.is_dir());
2850 let mut filepath = dirpath;
2851 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2852 check!(File::create(&filepath)); // ignore return; touch only
2853 assert!(!filepath.is_dir());
2854 assert!(filepath.exists());
2858 fn unicode_path_exists() {
2859 assert!(Path::new(".").exists());
2860 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2862 let tmpdir = tmpdir();
2863 let unicode = tmpdir.path();
2864 let unicode = unicode.join("test-각丁ー再见");
2865 check!(fs::create_dir(&unicode));
2866 assert!(unicode.exists());
2867 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2871 fn copy_file_does_not_exist() {
2872 let from = Path::new("test/nonexistent-bogus-path");
2873 let to = Path::new("test/other-bogus-path");
2875 match fs::copy(&from, &to) {
2878 assert!(!from.exists());
2879 assert!(!to.exists());
2885 fn copy_src_does_not_exist() {
2886 let tmpdir = tmpdir();
2887 let from = Path::new("test/nonexistent-bogus-path");
2888 let to = tmpdir.join("out.txt");
2889 check!(check!(File::create(&to)).write(b"hello"));
2890 assert!(fs::copy(&from, &to).is_err());
2891 assert!(!from.exists());
2892 let mut v = Vec::new();
2893 check!(check!(File::open(&to)).read_to_end(&mut v));
2894 assert_eq!(v, b"hello");
2899 let tmpdir = tmpdir();
2900 let input = tmpdir.join("in.txt");
2901 let out = tmpdir.join("out.txt");
2903 check!(check!(File::create(&input)).write(b"hello"));
2904 check!(fs::copy(&input, &out));
2905 let mut v = Vec::new();
2906 check!(check!(File::open(&out)).read_to_end(&mut v));
2907 assert_eq!(v, b"hello");
2909 assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2913 fn copy_file_dst_dir() {
2914 let tmpdir = tmpdir();
2915 let out = tmpdir.join("out");
2917 check!(File::create(&out));
2918 match fs::copy(&*out, tmpdir.path()) {
2925 fn copy_file_dst_exists() {
2926 let tmpdir = tmpdir();
2927 let input = tmpdir.join("in");
2928 let output = tmpdir.join("out");
2930 check!(check!(File::create(&input)).write("foo".as_bytes()));
2931 check!(check!(File::create(&output)).write("bar".as_bytes()));
2932 check!(fs::copy(&input, &output));
2934 let mut v = Vec::new();
2935 check!(check!(File::open(&output)).read_to_end(&mut v));
2936 assert_eq!(v, b"foo".to_vec());
2940 fn copy_file_src_dir() {
2941 let tmpdir = tmpdir();
2942 let out = tmpdir.join("out");
2944 match fs::copy(tmpdir.path(), &out) {
2948 assert!(!out.exists());
2952 fn copy_file_preserves_perm_bits() {
2953 let tmpdir = tmpdir();
2954 let input = tmpdir.join("in.txt");
2955 let out = tmpdir.join("out.txt");
2957 let attr = check!(check!(File::create(&input)).metadata());
2958 let mut p = attr.permissions();
2959 p.set_readonly(true);
2960 check!(fs::set_permissions(&input, p));
2961 check!(fs::copy(&input, &out));
2962 assert!(check!(out.metadata()).permissions().readonly());
2963 check!(fs::set_permissions(&input, attr.permissions()));
2964 check!(fs::set_permissions(&out, attr.permissions()));
2969 fn copy_file_preserves_streams() {
2971 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2972 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2973 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2974 let mut v = Vec::new();
2975 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2976 assert_eq!(v, b"carrot".to_vec());
2980 fn copy_file_returns_metadata_len() {
2982 let in_path = tmp.join("in.txt");
2983 let out_path = tmp.join("out.txt");
2984 check!(check!(File::create(&in_path)).write(b"lettuce"));
2986 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2987 let copied_len = check!(fs::copy(&in_path, &out_path));
2988 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2992 fn copy_file_follows_dst_symlink() {
2994 if !got_symlink_permission(&tmp) {
2998 let in_path = tmp.join("in.txt");
2999 let out_path = tmp.join("out.txt");
3000 let out_path_symlink = tmp.join("out_symlink.txt");
3002 check!(fs::write(&in_path, "foo"));
3003 check!(fs::write(&out_path, "bar"));
3004 check!(symlink_file(&out_path, &out_path_symlink));
3006 check!(fs::copy(&in_path, &out_path_symlink));
3008 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
3009 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
3010 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
3014 fn symlinks_work() {
3015 let tmpdir = tmpdir();
3016 if !got_symlink_permission(&tmpdir) {
3020 let input = tmpdir.join("in.txt");
3021 let out = tmpdir.join("out.txt");
3023 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3024 check!(symlink_file(&input, &out));
3025 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
3026 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3027 let mut v = Vec::new();
3028 check!(check!(File::open(&out)).read_to_end(&mut v));
3029 assert_eq!(v, b"foobar".to_vec());
3033 fn symlink_noexist() {
3034 // Symlinks can point to things that don't exist
3035 let tmpdir = tmpdir();
3036 if !got_symlink_permission(&tmpdir) {
3040 // Use a relative path for testing. Symlinks get normalized by Windows,
3041 // so we may not get the same path back for absolute paths
3042 check!(symlink_file(&"foo", &tmpdir.join("bar")));
3043 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3049 // directory symlink
3051 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3056 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3059 // junction with special permissions
3061 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3065 let tmpdir = tmpdir();
3066 let link = tmpdir.join("link");
3067 if !got_symlink_permission(&tmpdir) {
3070 check!(symlink_file(&"foo", &link));
3071 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3075 fn readlink_not_symlink() {
3076 let tmpdir = tmpdir();
3077 match fs::read_link(tmpdir.path()) {
3078 Ok(..) => panic!("wanted a failure"),
3085 let tmpdir = tmpdir();
3086 let input = tmpdir.join("in.txt");
3087 let out = tmpdir.join("out.txt");
3089 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3090 check!(fs::hard_link(&input, &out));
3091 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3092 assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3093 let mut v = Vec::new();
3094 check!(check!(File::open(&out)).read_to_end(&mut v));
3095 assert_eq!(v, b"foobar".to_vec());
3097 // can't link to yourself
3098 match fs::hard_link(&input, &input) {
3099 Ok(..) => panic!("wanted a failure"),
3102 // can't link to something that doesn't exist
3103 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3104 Ok(..) => panic!("wanted a failure"),
3111 let tmpdir = tmpdir();
3112 let file = tmpdir.join("in.txt");
3114 check!(File::create(&file));
3115 let attr = check!(fs::metadata(&file));
3116 assert!(!attr.permissions().readonly());
3117 let mut p = attr.permissions();
3118 p.set_readonly(true);
3119 check!(fs::set_permissions(&file, p.clone()));
3120 let attr = check!(fs::metadata(&file));
3121 assert!(attr.permissions().readonly());
3123 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3124 Ok(..) => panic!("wanted an error"),
3128 p.set_readonly(false);
3129 check!(fs::set_permissions(&file, p));
3134 let tmpdir = tmpdir();
3135 let path = tmpdir.join("in.txt");
3137 let file = check!(File::create(&path));
3138 let attr = check!(fs::metadata(&path));
3139 assert!(!attr.permissions().readonly());
3140 let mut p = attr.permissions();
3141 p.set_readonly(true);
3142 check!(file.set_permissions(p.clone()));
3143 let attr = check!(fs::metadata(&path));
3144 assert!(attr.permissions().readonly());
3146 p.set_readonly(false);
3147 check!(file.set_permissions(p));
3151 fn sync_doesnt_kill_anything() {
3152 let tmpdir = tmpdir();
3153 let path = tmpdir.join("in.txt");
3155 let mut file = check!(File::create(&path));
3156 check!(file.sync_all());
3157 check!(file.sync_data());
3158 check!(file.write(b"foo"));
3159 check!(file.sync_all());
3160 check!(file.sync_data());
3164 fn truncate_works() {
3165 let tmpdir = tmpdir();
3166 let path = tmpdir.join("in.txt");
3168 let mut file = check!(File::create(&path));
3169 check!(file.write(b"foo"));
3170 check!(file.sync_all());
3172 // Do some simple things with truncation
3173 assert_eq!(check!(file.metadata()).len(), 3);
3174 check!(file.set_len(10));
3175 assert_eq!(check!(file.metadata()).len(), 10);
3176 check!(file.write(b"bar"));
3177 check!(file.sync_all());
3178 assert_eq!(check!(file.metadata()).len(), 10);
3180 let mut v = Vec::new();
3181 check!(check!(File::open(&path)).read_to_end(&mut v));
3182 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3184 // Truncate to a smaller length, don't seek, and then write something.
3185 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3186 // past the end of the file).
3187 check!(file.set_len(2));
3188 assert_eq!(check!(file.metadata()).len(), 2);
3189 check!(file.write(b"wut"));
3190 check!(file.sync_all());
3191 assert_eq!(check!(file.metadata()).len(), 9);
3192 let mut v = Vec::new();
3193 check!(check!(File::open(&path)).read_to_end(&mut v));
3194 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3199 use crate::fs::OpenOptions as OO;
3200 fn c<T: Clone>(t: &T) -> T {
3204 let tmpdir = tmpdir();
3206 let mut r = OO::new();
3208 let mut w = OO::new();
3210 let mut rw = OO::new();
3211 rw.read(true).write(true);
3212 let mut a = OO::new();
3214 let mut ra = OO::new();
3215 ra.read(true).append(true);
3218 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3219 #[cfg(all(unix, not(target_os = "vxworks")))]
3220 let invalid_options = "Invalid argument";
3221 #[cfg(target_os = "vxworks")]
3222 let invalid_options = "invalid argument";
3224 // Test various combinations of creation modes and access modes.
3227 // creation mode | read | write | read-write | append | read-append |
3228 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3229 // not set (open existing) | X | X | X | X | X |
3230 // create | | X | X | X | X |
3231 // truncate | | X | X | | |
3232 // create and truncate | | X | X | | |
3233 // create_new | | X | X | X | X |
3235 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3238 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3239 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3240 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3241 check!(c(&w).create(true).open(&tmpdir.join("a")));
3242 check!(c(&w).open(&tmpdir.join("a")));
3245 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3246 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3247 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3248 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3249 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3252 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3253 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3254 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3255 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3256 check!(c(&rw).open(&tmpdir.join("c")));
3259 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3260 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3261 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3262 check!(c(&a).create(true).open(&tmpdir.join("d")));
3263 check!(c(&a).open(&tmpdir.join("d")));
3266 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3267 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3268 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3269 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3270 check!(c(&ra).open(&tmpdir.join("e")));
3272 // Test opening a file without setting an access mode
3273 let mut blank = OO::new();
3274 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3277 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3279 // Test write fails for read-only
3280 check!(r.open(&tmpdir.join("h")));
3282 let mut f = check!(r.open(&tmpdir.join("h")));
3283 assert!(f.write("wut".as_bytes()).is_err());
3286 // Test write overwrites
3288 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3289 check!(f.write("baz".as_bytes()));
3292 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3293 let mut b = vec![0; 6];
3294 check!(f.read(&mut b));
3295 assert_eq!(b, "bazbar".as_bytes());
3298 // Test truncate works
3300 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3301 check!(f.write("foo".as_bytes()));
3303 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3305 // Test append works
3306 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3308 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3309 check!(f.write("bar".as_bytes()));
3311 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3313 // Test .append(true) equals .write(true).append(true)
3315 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3316 check!(f.write("baz".as_bytes()));
3318 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3322 fn _assert_send_sync() {
3323 fn _assert_send_sync<T: Send + Sync>() {}
3324 _assert_send_sync::<OpenOptions>();
3329 let mut bytes = [0; 1024];
3330 StdRng::from_entropy().fill_bytes(&mut bytes);
3332 let tmpdir = tmpdir();
3334 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3335 let mut v = Vec::new();
3336 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3337 assert!(v == &bytes[..]);
3341 fn write_then_read() {
3342 let mut bytes = [0; 1024];
3343 StdRng::from_entropy().fill_bytes(&mut bytes);
3345 let tmpdir = tmpdir();
3347 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3348 let v = check!(fs::read(&tmpdir.join("test")));
3349 assert!(v == &bytes[..]);
3351 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3353 fs::read_to_string(&tmpdir.join("not-utf8")),
3354 "stream did not contain valid UTF-8"
3358 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3359 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3360 assert_eq!(string, s);
3364 fn file_try_clone() {
3365 let tmpdir = tmpdir();
3367 let mut f1 = check!(
3368 OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3370 let mut f2 = check!(f1.try_clone());
3372 check!(f1.write_all(b"hello world"));
3373 check!(f1.seek(SeekFrom::Start(2)));
3375 let mut buf = vec![];
3376 check!(f2.read_to_end(&mut buf));
3377 assert_eq!(buf, b"llo world");
3380 check!(f1.write_all(b"!"));
3384 #[cfg(not(windows))]
3385 fn unlink_readonly() {
3386 let tmpdir = tmpdir();
3387 let path = tmpdir.join("file");
3388 check!(File::create(&path));
3389 let mut perm = check!(fs::metadata(&path)).permissions();
3390 perm.set_readonly(true);
3391 check!(fs::set_permissions(&path, perm));
3392 check!(fs::remove_file(&path));
3396 fn mkdir_trailing_slash() {
3397 let tmpdir = tmpdir();
3398 let path = tmpdir.join("file");
3399 check!(fs::create_dir_all(&path.join("a/")));
3403 fn canonicalize_works_simple() {
3404 let tmpdir = tmpdir();
3405 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3406 let file = tmpdir.join("test");
3407 File::create(&file).unwrap();
3408 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3412 fn realpath_works() {
3413 let tmpdir = tmpdir();
3414 if !got_symlink_permission(&tmpdir) {
3418 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3419 let file = tmpdir.join("test");
3420 let dir = tmpdir.join("test2");
3421 let link = dir.join("link");
3422 let linkdir = tmpdir.join("test3");
3424 File::create(&file).unwrap();
3425 fs::create_dir(&dir).unwrap();
3426 symlink_file(&file, &link).unwrap();
3427 symlink_dir(&dir, &linkdir).unwrap();
3429 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3431 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3432 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3433 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3434 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3435 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3439 fn realpath_works_tricky() {
3440 let tmpdir = tmpdir();
3441 if !got_symlink_permission(&tmpdir) {
3445 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3446 let a = tmpdir.join("a");
3447 let b = a.join("b");
3448 let c = b.join("c");
3449 let d = a.join("d");
3450 let e = d.join("e");
3451 let f = a.join("f");
3453 fs::create_dir_all(&b).unwrap();
3454 fs::create_dir_all(&d).unwrap();
3455 File::create(&f).unwrap();
3456 if cfg!(not(windows)) {
3457 symlink_file("../d/e", &c).unwrap();
3458 symlink_file("../f", &e).unwrap();
3461 symlink_file(r"..\d\e", &c).unwrap();
3462 symlink_file(r"..\f", &e).unwrap();
3465 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3466 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3470 fn dir_entry_methods() {
3471 let tmpdir = tmpdir();
3473 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3474 File::create(&tmpdir.join("b")).unwrap();
3476 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3477 let fname = file.file_name();
3478 match fname.to_str() {
3480 assert!(file.file_type().unwrap().is_dir());
3481 assert!(file.metadata().unwrap().is_dir());
3484 assert!(file.file_type().unwrap().is_file());
3485 assert!(file.metadata().unwrap().is_file());
3487 f => panic!("unknown file name: {:?}", f),
3493 fn dir_entry_debug() {
3494 let tmpdir = tmpdir();
3495 File::create(&tmpdir.join("b")).unwrap();
3496 let mut read_dir = tmpdir.path().read_dir().unwrap();
3497 let dir_entry = read_dir.next().unwrap().unwrap();
3498 let actual = format!("{:?}", dir_entry);
3499 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3500 assert_eq!(actual, expected);
3504 fn read_dir_not_found() {
3505 let res = fs::read_dir("/path/that/does/not/exist");
3506 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3510 fn create_dir_all_with_junctions() {
3511 let tmpdir = tmpdir();
3512 let target = tmpdir.join("target");
3514 let junction = tmpdir.join("junction");
3515 let b = junction.join("a/b");
3517 let link = tmpdir.join("link");
3518 let d = link.join("c/d");
3520 fs::create_dir(&target).unwrap();
3522 check!(symlink_junction(&target, &junction));
3523 check!(fs::create_dir_all(&b));
3524 // the junction itself is not a directory, but `is_dir()` on a Path
3526 assert!(junction.is_dir());
3527 assert!(b.exists());
3529 if !got_symlink_permission(&tmpdir) {
3532 check!(symlink_dir(&target, &link));
3533 check!(fs::create_dir_all(&d));
3534 assert!(link.is_dir());
3535 assert!(d.exists());
3539 fn metadata_access_times() {
3540 let tmpdir = tmpdir();
3542 let b = tmpdir.join("b");
3543 File::create(&b).unwrap();
3545 let a = check!(fs::metadata(&tmpdir.path()));
3546 let b = check!(fs::metadata(&b));
3548 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3549 assert_eq!(check!(a.modified()), check!(a.modified()));
3550 assert_eq!(check!(b.accessed()), check!(b.modified()));
3552 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3553 check!(a.created());
3554 check!(b.created());
3557 if cfg!(target_os = "linux") {
3558 // Not always available
3559 match (a.created(), b.created()) {
3560 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3562 if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3564 "creation time must be always supported or not supported: {:?} {:?}",