]> git.proxmox.com Git - rustc.git/blob - library/std/src/fs.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / library / std / src / fs.rs
1 //! Filesystem manipulation operations.
2 //!
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
7
8 #![stable(feature = "rust1", since = "1.0.0")]
9 #![deny(unsafe_op_in_unsafe_fn)]
10
11 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
12 mod tests;
13
14 use crate::ffi::OsString;
15 use crate::fmt;
16 use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
17 use crate::path::{Path, PathBuf};
18 use crate::sys::fs as fs_imp;
19 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
20 use crate::time::SystemTime;
21
22 /// An object providing access to an open file on the filesystem.
23 ///
24 /// An instance of a `File` can be read and/or written depending on what options
25 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
26 /// that the file contains internally.
27 ///
28 /// Files are automatically closed when they go out of scope. Errors detected
29 /// on closing are ignored by the implementation of `Drop`. Use the method
30 /// [`sync_all`] if these errors must be manually handled.
31 ///
32 /// # Examples
33 ///
34 /// Creates a new file and write bytes to it (you can also use [`write()`]):
35 ///
36 /// ```no_run
37 /// use std::fs::File;
38 /// use std::io::prelude::*;
39 ///
40 /// fn main() -> std::io::Result<()> {
41 /// let mut file = File::create("foo.txt")?;
42 /// file.write_all(b"Hello, world!")?;
43 /// Ok(())
44 /// }
45 /// ```
46 ///
47 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
48 ///
49 /// ```no_run
50 /// use std::fs::File;
51 /// use std::io::prelude::*;
52 ///
53 /// fn main() -> std::io::Result<()> {
54 /// let mut file = File::open("foo.txt")?;
55 /// let mut contents = String::new();
56 /// file.read_to_string(&mut contents)?;
57 /// assert_eq!(contents, "Hello, world!");
58 /// Ok(())
59 /// }
60 /// ```
61 ///
62 /// It can be more efficient to read the contents of a file with a buffered
63 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
64 ///
65 /// ```no_run
66 /// use std::fs::File;
67 /// use std::io::BufReader;
68 /// use std::io::prelude::*;
69 ///
70 /// fn main() -> std::io::Result<()> {
71 /// let file = File::open("foo.txt")?;
72 /// let mut buf_reader = BufReader::new(file);
73 /// let mut contents = String::new();
74 /// buf_reader.read_to_string(&mut contents)?;
75 /// assert_eq!(contents, "Hello, world!");
76 /// Ok(())
77 /// }
78 /// ```
79 ///
80 /// Note that, although read and write methods require a `&mut File`, because
81 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
82 /// still modify the file, either through methods that take `&File` or by
83 /// retrieving the underlying OS object and modifying the file that way.
84 /// Additionally, many operating systems allow concurrent modification of files
85 /// by different processes. Avoid assuming that holding a `&File` means that the
86 /// file will not change.
87 ///
88 /// # Platform-specific behavior
89 ///
90 /// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
91 /// perform synchronous I/O operations. Therefore the underlying file must not
92 /// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
93 ///
94 /// [`BufReader<R>`]: io::BufReader
95 /// [`sync_all`]: File::sync_all
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
98 pub struct File {
99 inner: fs_imp::File,
100 }
101
102 /// Metadata information about a file.
103 ///
104 /// This structure is returned from the [`metadata`] or
105 /// [`symlink_metadata`] function or method and represents known
106 /// metadata about a file such as its permissions, size, modification
107 /// times, etc.
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[derive(Clone)]
110 pub struct Metadata(fs_imp::FileAttr);
111
112 /// Iterator over the entries in a directory.
113 ///
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
117 /// learned.
118 ///
119 /// The order in which this iterator returns entries is platform and filesystem
120 /// dependent.
121 ///
122 /// # Errors
123 ///
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
126 #[stable(feature = "rust1", since = "1.0.0")]
127 #[derive(Debug)]
128 pub struct ReadDir(fs_imp::ReadDir);
129
130 /// Entries returned by the [`ReadDir`] iterator.
131 ///
132 /// An instance of `DirEntry` represents an entry inside of a directory on the
133 /// filesystem. Each entry can be inspected via methods to learn about the full
134 /// path or possibly other metadata through per-platform extension traits.
135 ///
136 /// # Platform-specific behavior
137 ///
138 /// On Unix, the `DirEntry` struct contains an internal reference to the open
139 /// directory. Holding `DirEntry` objects will consume a file handle even
140 /// after the `ReadDir` iterator is dropped.
141 ///
142 /// Note that this [may change in the future][changes].
143 ///
144 /// [changes]: io#platform-specific-behavior
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub struct DirEntry(fs_imp::DirEntry);
147
148 /// Options and flags which can be used to configure how a file is opened.
149 ///
150 /// This builder exposes the ability to configure how a [`File`] is opened and
151 /// what operations are permitted on the open file. The [`File::open`] and
152 /// [`File::create`] methods are aliases for commonly used options using this
153 /// builder.
154 ///
155 /// Generally speaking, when using `OpenOptions`, you'll first call
156 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
157 /// call [`OpenOptions::open`], passing the path of the file you're trying to
158 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
159 /// can further operate on.
160 ///
161 /// # Examples
162 ///
163 /// Opening a file to read:
164 ///
165 /// ```no_run
166 /// use std::fs::OpenOptions;
167 ///
168 /// let file = OpenOptions::new().read(true).open("foo.txt");
169 /// ```
170 ///
171 /// Opening a file for both reading and writing, as well as creating it if it
172 /// doesn't exist:
173 ///
174 /// ```no_run
175 /// use std::fs::OpenOptions;
176 ///
177 /// let file = OpenOptions::new()
178 /// .read(true)
179 /// .write(true)
180 /// .create(true)
181 /// .open("foo.txt");
182 /// ```
183 #[derive(Clone, Debug)]
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub struct OpenOptions(fs_imp::OpenOptions);
186
187 /// Representation of the various timestamps on a file.
188 #[derive(Copy, Clone, Debug, Default)]
189 #[unstable(feature = "file_set_times", issue = "98245")]
190 pub struct FileTimes(fs_imp::FileTimes);
191
192 /// Representation of the various permissions on a file.
193 ///
194 /// This module only currently provides one bit of information,
195 /// [`Permissions::readonly`], which is exposed on all currently supported
196 /// platforms. Unix-specific functionality, such as mode bits, is available
197 /// through the [`PermissionsExt`] trait.
198 ///
199 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
200 #[derive(Clone, PartialEq, Eq, Debug)]
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub struct Permissions(fs_imp::FilePermissions);
203
204 /// A structure representing a type of file with accessors for each file type.
205 /// It is returned by [`Metadata::file_type`] method.
206 #[stable(feature = "file_type", since = "1.1.0")]
207 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
208 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
209 pub struct FileType(fs_imp::FileType);
210
211 /// A builder used to create directories in various manners.
212 ///
213 /// This builder also supports platform-specific options.
214 #[stable(feature = "dir_builder", since = "1.6.0")]
215 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
216 #[derive(Debug)]
217 pub struct DirBuilder {
218 inner: fs_imp::DirBuilder,
219 recursive: bool,
220 }
221
222 /// Read the entire contents of a file into a bytes vector.
223 ///
224 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
225 /// with fewer imports and without an intermediate variable.
226 ///
227 /// [`read_to_end`]: Read::read_to_end
228 ///
229 /// # Errors
230 ///
231 /// This function will return an error if `path` does not already exist.
232 /// Other errors may also be returned according to [`OpenOptions::open`].
233 ///
234 /// It will also return an error if it encounters while reading an error
235 /// of a kind other than [`io::ErrorKind::Interrupted`].
236 ///
237 /// # Examples
238 ///
239 /// ```no_run
240 /// use std::fs;
241 /// use std::net::SocketAddr;
242 ///
243 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
244 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
245 /// Ok(())
246 /// }
247 /// ```
248 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
249 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
250 fn inner(path: &Path) -> io::Result<Vec<u8>> {
251 let mut file = File::open(path)?;
252 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
253 let mut bytes = Vec::with_capacity(size as usize);
254 io::default_read_to_end(&mut file, &mut bytes)?;
255 Ok(bytes)
256 }
257 inner(path.as_ref())
258 }
259
260 /// Read the entire contents of a file into a string.
261 ///
262 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
263 /// with fewer imports and without an intermediate variable.
264 ///
265 /// [`read_to_string`]: Read::read_to_string
266 ///
267 /// # Errors
268 ///
269 /// This function will return an error if `path` does not already exist.
270 /// Other errors may also be returned according to [`OpenOptions::open`].
271 ///
272 /// It will also return an error if it encounters while reading an error
273 /// of a kind other than [`io::ErrorKind::Interrupted`],
274 /// or if the contents of the file are not valid UTF-8.
275 ///
276 /// # Examples
277 ///
278 /// ```no_run
279 /// use std::fs;
280 /// use std::net::SocketAddr;
281 /// use std::error::Error;
282 ///
283 /// fn main() -> Result<(), Box<dyn Error>> {
284 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
285 /// Ok(())
286 /// }
287 /// ```
288 #[stable(feature = "fs_read_write", since = "1.26.0")]
289 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
290 fn inner(path: &Path) -> io::Result<String> {
291 let mut file = File::open(path)?;
292 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
293 let mut string = String::with_capacity(size as usize);
294 io::default_read_to_string(&mut file, &mut string)?;
295 Ok(string)
296 }
297 inner(path.as_ref())
298 }
299
300 /// Write a slice as the entire contents of a file.
301 ///
302 /// This function will create a file if it does not exist,
303 /// and will entirely replace its contents if it does.
304 ///
305 /// Depending on the platform, this function may fail if the
306 /// full directory path does not exist.
307 ///
308 /// This is a convenience function for using [`File::create`] and [`write_all`]
309 /// with fewer imports.
310 ///
311 /// [`write_all`]: Write::write_all
312 ///
313 /// # Examples
314 ///
315 /// ```no_run
316 /// use std::fs;
317 ///
318 /// fn main() -> std::io::Result<()> {
319 /// fs::write("foo.txt", b"Lorem ipsum")?;
320 /// fs::write("bar.txt", "dolor sit")?;
321 /// Ok(())
322 /// }
323 /// ```
324 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
325 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
326 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
327 File::create(path)?.write_all(contents)
328 }
329 inner(path.as_ref(), contents.as_ref())
330 }
331
332 impl File {
333 /// Attempts to open a file in read-only mode.
334 ///
335 /// See the [`OpenOptions::open`] method for more details.
336 ///
337 /// If you only need to read the entire file contents,
338 /// consider [`std::fs::read()`][self::read] or
339 /// [`std::fs::read_to_string()`][self::read_to_string] instead.
340 ///
341 /// # Errors
342 ///
343 /// This function will return an error if `path` does not already exist.
344 /// Other errors may also be returned according to [`OpenOptions::open`].
345 ///
346 /// # Examples
347 ///
348 /// ```no_run
349 /// use std::fs::File;
350 /// use std::io::Read;
351 ///
352 /// fn main() -> std::io::Result<()> {
353 /// let mut f = File::open("foo.txt")?;
354 /// let mut data = vec![];
355 /// f.read_to_end(&mut data)?;
356 /// Ok(())
357 /// }
358 /// ```
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
361 OpenOptions::new().read(true).open(path.as_ref())
362 }
363
364 /// Opens a file in write-only mode.
365 ///
366 /// This function will create a file if it does not exist,
367 /// and will truncate it if it does.
368 ///
369 /// Depending on the platform, this function may fail if the
370 /// full directory path does not exist.
371 /// See the [`OpenOptions::open`] function for more details.
372 ///
373 /// See also [`std::fs::write()`][self::write] for a simple function to
374 /// create a file with a given data.
375 ///
376 /// # Examples
377 ///
378 /// ```no_run
379 /// use std::fs::File;
380 /// use std::io::Write;
381 ///
382 /// fn main() -> std::io::Result<()> {
383 /// let mut f = File::create("foo.txt")?;
384 /// f.write_all(&1234_u32.to_be_bytes())?;
385 /// Ok(())
386 /// }
387 /// ```
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
390 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
391 }
392
393 /// Creates a new file in read-write mode; error if the file exists.
394 ///
395 /// This function will create a file if it does not exist, or return an error if it does. This
396 /// way, if the call succeeds, the file returned is guaranteed to be new.
397 ///
398 /// This option is useful because it is atomic. Otherwise between checking whether a file
399 /// exists and creating a new one, the file may have been created by another process (a TOCTOU
400 /// race condition / attack).
401 ///
402 /// This can also be written using
403 /// `File::options().read(true).write(true).create_new(true).open(...)`.
404 ///
405 /// # Examples
406 ///
407 /// ```no_run
408 /// #![feature(file_create_new)]
409 ///
410 /// use std::fs::File;
411 /// use std::io::Write;
412 ///
413 /// fn main() -> std::io::Result<()> {
414 /// let mut f = File::create_new("foo.txt")?;
415 /// f.write_all("Hello, world!".as_bytes())?;
416 /// Ok(())
417 /// }
418 /// ```
419 #[unstable(feature = "file_create_new", issue = "105135")]
420 pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
421 OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
422 }
423
424 /// Returns a new OpenOptions object.
425 ///
426 /// This function returns a new OpenOptions object that you can use to
427 /// open or create a file with specific options if `open()` or `create()`
428 /// are not appropriate.
429 ///
430 /// It is equivalent to `OpenOptions::new()`, but allows you to write more
431 /// readable code. Instead of
432 /// `OpenOptions::new().append(true).open("example.log")`,
433 /// you can write `File::options().append(true).open("example.log")`. This
434 /// also avoids the need to import `OpenOptions`.
435 ///
436 /// See the [`OpenOptions::new`] function for more details.
437 ///
438 /// # Examples
439 ///
440 /// ```no_run
441 /// use std::fs::File;
442 /// use std::io::Write;
443 ///
444 /// fn main() -> std::io::Result<()> {
445 /// let mut f = File::options().append(true).open("example.log")?;
446 /// writeln!(&mut f, "new line")?;
447 /// Ok(())
448 /// }
449 /// ```
450 #[must_use]
451 #[stable(feature = "with_options", since = "1.58.0")]
452 pub fn options() -> OpenOptions {
453 OpenOptions::new()
454 }
455
456 /// Attempts to sync all OS-internal metadata to disk.
457 ///
458 /// This function will attempt to ensure that all in-memory data reaches the
459 /// filesystem before returning.
460 ///
461 /// This can be used to handle errors that would otherwise only be caught
462 /// when the `File` is closed. Dropping a file will ignore errors in
463 /// synchronizing this in-memory data.
464 ///
465 /// # Examples
466 ///
467 /// ```no_run
468 /// use std::fs::File;
469 /// use std::io::prelude::*;
470 ///
471 /// fn main() -> std::io::Result<()> {
472 /// let mut f = File::create("foo.txt")?;
473 /// f.write_all(b"Hello, world!")?;
474 ///
475 /// f.sync_all()?;
476 /// Ok(())
477 /// }
478 /// ```
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn sync_all(&self) -> io::Result<()> {
481 self.inner.fsync()
482 }
483
484 /// This function is similar to [`sync_all`], except that it might not
485 /// synchronize file metadata to the filesystem.
486 ///
487 /// This is intended for use cases that must synchronize content, but don't
488 /// need the metadata on disk. The goal of this method is to reduce disk
489 /// operations.
490 ///
491 /// Note that some platforms may simply implement this in terms of
492 /// [`sync_all`].
493 ///
494 /// [`sync_all`]: File::sync_all
495 ///
496 /// # Examples
497 ///
498 /// ```no_run
499 /// use std::fs::File;
500 /// use std::io::prelude::*;
501 ///
502 /// fn main() -> std::io::Result<()> {
503 /// let mut f = File::create("foo.txt")?;
504 /// f.write_all(b"Hello, world!")?;
505 ///
506 /// f.sync_data()?;
507 /// Ok(())
508 /// }
509 /// ```
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn sync_data(&self) -> io::Result<()> {
512 self.inner.datasync()
513 }
514
515 /// Truncates or extends the underlying file, updating the size of
516 /// this file to become `size`.
517 ///
518 /// If the `size` is less than the current file's size, then the file will
519 /// be shrunk. If it is greater than the current file's size, then the file
520 /// will be extended to `size` and have all of the intermediate data filled
521 /// in with 0s.
522 ///
523 /// The file's cursor isn't changed. In particular, if the cursor was at the
524 /// end and the file is shrunk using this operation, the cursor will now be
525 /// past the end.
526 ///
527 /// # Errors
528 ///
529 /// This function will return an error if the file is not opened for writing.
530 /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
531 /// will be returned if the desired length would cause an overflow due to
532 /// the implementation specifics.
533 ///
534 /// # Examples
535 ///
536 /// ```no_run
537 /// use std::fs::File;
538 ///
539 /// fn main() -> std::io::Result<()> {
540 /// let mut f = File::create("foo.txt")?;
541 /// f.set_len(10)?;
542 /// Ok(())
543 /// }
544 /// ```
545 ///
546 /// Note that this method alters the content of the underlying file, even
547 /// though it takes `&self` rather than `&mut self`.
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn set_len(&self, size: u64) -> io::Result<()> {
550 self.inner.truncate(size)
551 }
552
553 /// Queries metadata about the underlying file.
554 ///
555 /// # Examples
556 ///
557 /// ```no_run
558 /// use std::fs::File;
559 ///
560 /// fn main() -> std::io::Result<()> {
561 /// let mut f = File::open("foo.txt")?;
562 /// let metadata = f.metadata()?;
563 /// Ok(())
564 /// }
565 /// ```
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn metadata(&self) -> io::Result<Metadata> {
568 self.inner.file_attr().map(Metadata)
569 }
570
571 /// Creates a new `File` instance that shares the same underlying file handle
572 /// as the existing `File` instance. Reads, writes, and seeks will affect
573 /// both `File` instances simultaneously.
574 ///
575 /// # Examples
576 ///
577 /// Creates two handles for a file named `foo.txt`:
578 ///
579 /// ```no_run
580 /// use std::fs::File;
581 ///
582 /// fn main() -> std::io::Result<()> {
583 /// let mut file = File::open("foo.txt")?;
584 /// let file_copy = file.try_clone()?;
585 /// Ok(())
586 /// }
587 /// ```
588 ///
589 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
590 /// two handles, seek one of them, and read the remaining bytes from the
591 /// other handle:
592 ///
593 /// ```no_run
594 /// use std::fs::File;
595 /// use std::io::SeekFrom;
596 /// use std::io::prelude::*;
597 ///
598 /// fn main() -> std::io::Result<()> {
599 /// let mut file = File::open("foo.txt")?;
600 /// let mut file_copy = file.try_clone()?;
601 ///
602 /// file.seek(SeekFrom::Start(3))?;
603 ///
604 /// let mut contents = vec![];
605 /// file_copy.read_to_end(&mut contents)?;
606 /// assert_eq!(contents, b"def\n");
607 /// Ok(())
608 /// }
609 /// ```
610 #[stable(feature = "file_try_clone", since = "1.9.0")]
611 pub fn try_clone(&self) -> io::Result<File> {
612 Ok(File { inner: self.inner.duplicate()? })
613 }
614
615 /// Changes the permissions on the underlying file.
616 ///
617 /// # Platform-specific behavior
618 ///
619 /// This function currently corresponds to the `fchmod` function on Unix and
620 /// the `SetFileInformationByHandle` function on Windows. Note that, this
621 /// [may change in the future][changes].
622 ///
623 /// [changes]: io#platform-specific-behavior
624 ///
625 /// # Errors
626 ///
627 /// This function will return an error if the user lacks permission change
628 /// attributes on the underlying file. It may also return an error in other
629 /// os-specific unspecified cases.
630 ///
631 /// # Examples
632 ///
633 /// ```no_run
634 /// fn main() -> std::io::Result<()> {
635 /// use std::fs::File;
636 ///
637 /// let file = File::open("foo.txt")?;
638 /// let mut perms = file.metadata()?.permissions();
639 /// perms.set_readonly(true);
640 /// file.set_permissions(perms)?;
641 /// Ok(())
642 /// }
643 /// ```
644 ///
645 /// Note that this method alters the permissions of the underlying file,
646 /// even though it takes `&self` rather than `&mut self`.
647 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
648 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
649 self.inner.set_permissions(perm.0)
650 }
651
652 /// Changes the timestamps of the underlying file.
653 ///
654 /// # Platform-specific behavior
655 ///
656 /// This function currently corresponds to the `futimens` function on Unix (falling back to
657 /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
658 /// [may change in the future][changes].
659 ///
660 /// [changes]: io#platform-specific-behavior
661 ///
662 /// # Errors
663 ///
664 /// This function will return an error if the user lacks permission to change timestamps on the
665 /// underlying file. It may also return an error in other os-specific unspecified cases.
666 ///
667 /// This function may return an error if the operating system lacks support to change one or
668 /// more of the timestamps set in the `FileTimes` structure.
669 ///
670 /// # Examples
671 ///
672 /// ```no_run
673 /// #![feature(file_set_times)]
674 ///
675 /// fn main() -> std::io::Result<()> {
676 /// use std::fs::{self, File, FileTimes};
677 ///
678 /// let src = fs::metadata("src")?;
679 /// let dest = File::options().write(true).open("dest")?;
680 /// let times = FileTimes::new()
681 /// .set_accessed(src.accessed()?)
682 /// .set_modified(src.modified()?);
683 /// dest.set_times(times)?;
684 /// Ok(())
685 /// }
686 /// ```
687 #[unstable(feature = "file_set_times", issue = "98245")]
688 #[doc(alias = "futimens")]
689 #[doc(alias = "futimes")]
690 #[doc(alias = "SetFileTime")]
691 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
692 self.inner.set_times(times.0)
693 }
694
695 /// Changes the modification time of the underlying file.
696 ///
697 /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
698 #[unstable(feature = "file_set_times", issue = "98245")]
699 #[inline]
700 pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
701 self.set_times(FileTimes::new().set_modified(time))
702 }
703 }
704
705 // In addition to the `impl`s here, `File` also has `impl`s for
706 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
707 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
708 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
709 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
710
711 impl AsInner<fs_imp::File> for File {
712 fn as_inner(&self) -> &fs_imp::File {
713 &self.inner
714 }
715 }
716 impl FromInner<fs_imp::File> for File {
717 fn from_inner(f: fs_imp::File) -> File {
718 File { inner: f }
719 }
720 }
721 impl IntoInner<fs_imp::File> for File {
722 fn into_inner(self) -> fs_imp::File {
723 self.inner
724 }
725 }
726
727 #[stable(feature = "rust1", since = "1.0.0")]
728 impl fmt::Debug for File {
729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 self.inner.fmt(f)
731 }
732 }
733
734 /// Indicates how much extra capacity is needed to read the rest of the file.
735 fn buffer_capacity_required(mut file: &File) -> usize {
736 let size = file.metadata().map(|m| m.len()).unwrap_or(0);
737 let pos = file.stream_position().unwrap_or(0);
738 // Don't worry about `usize` overflow because reading will fail regardless
739 // in that case.
740 size.saturating_sub(pos) as usize
741 }
742
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl Read for File {
745 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
746 self.inner.read(buf)
747 }
748
749 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
750 self.inner.read_vectored(bufs)
751 }
752
753 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
754 self.inner.read_buf(cursor)
755 }
756
757 #[inline]
758 fn is_read_vectored(&self) -> bool {
759 self.inner.is_read_vectored()
760 }
761
762 // Reserves space in the buffer based on the file size when available.
763 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
764 buf.reserve(buffer_capacity_required(self));
765 io::default_read_to_end(self, buf)
766 }
767
768 // Reserves space in the buffer based on the file size when available.
769 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
770 buf.reserve(buffer_capacity_required(self));
771 io::default_read_to_string(self, buf)
772 }
773 }
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl Write for File {
776 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
777 self.inner.write(buf)
778 }
779
780 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
781 self.inner.write_vectored(bufs)
782 }
783
784 #[inline]
785 fn is_write_vectored(&self) -> bool {
786 self.inner.is_write_vectored()
787 }
788
789 fn flush(&mut self) -> io::Result<()> {
790 self.inner.flush()
791 }
792 }
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl Seek for File {
795 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
796 self.inner.seek(pos)
797 }
798 }
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl Read for &File {
801 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
802 self.inner.read(buf)
803 }
804
805 fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
806 self.inner.read_buf(cursor)
807 }
808
809 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
810 self.inner.read_vectored(bufs)
811 }
812
813 #[inline]
814 fn is_read_vectored(&self) -> bool {
815 self.inner.is_read_vectored()
816 }
817
818 // Reserves space in the buffer based on the file size when available.
819 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
820 buf.reserve(buffer_capacity_required(self));
821 io::default_read_to_end(self, buf)
822 }
823
824 // Reserves space in the buffer based on the file size when available.
825 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
826 buf.reserve(buffer_capacity_required(self));
827 io::default_read_to_string(self, buf)
828 }
829 }
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl Write for &File {
832 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
833 self.inner.write(buf)
834 }
835
836 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
837 self.inner.write_vectored(bufs)
838 }
839
840 #[inline]
841 fn is_write_vectored(&self) -> bool {
842 self.inner.is_write_vectored()
843 }
844
845 fn flush(&mut self) -> io::Result<()> {
846 self.inner.flush()
847 }
848 }
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl Seek for &File {
851 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
852 self.inner.seek(pos)
853 }
854 }
855
856 impl OpenOptions {
857 /// Creates a blank new set of options ready for configuration.
858 ///
859 /// All options are initially set to `false`.
860 ///
861 /// # Examples
862 ///
863 /// ```no_run
864 /// use std::fs::OpenOptions;
865 ///
866 /// let mut options = OpenOptions::new();
867 /// let file = options.read(true).open("foo.txt");
868 /// ```
869 #[stable(feature = "rust1", since = "1.0.0")]
870 #[must_use]
871 pub fn new() -> Self {
872 OpenOptions(fs_imp::OpenOptions::new())
873 }
874
875 /// Sets the option for read access.
876 ///
877 /// This option, when true, will indicate that the file should be
878 /// `read`-able if opened.
879 ///
880 /// # Examples
881 ///
882 /// ```no_run
883 /// use std::fs::OpenOptions;
884 ///
885 /// let file = OpenOptions::new().read(true).open("foo.txt");
886 /// ```
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn read(&mut self, read: bool) -> &mut Self {
889 self.0.read(read);
890 self
891 }
892
893 /// Sets the option for write access.
894 ///
895 /// This option, when true, will indicate that the file should be
896 /// `write`-able if opened.
897 ///
898 /// If the file already exists, any write calls on it will overwrite its
899 /// contents, without truncating it.
900 ///
901 /// # Examples
902 ///
903 /// ```no_run
904 /// use std::fs::OpenOptions;
905 ///
906 /// let file = OpenOptions::new().write(true).open("foo.txt");
907 /// ```
908 #[stable(feature = "rust1", since = "1.0.0")]
909 pub fn write(&mut self, write: bool) -> &mut Self {
910 self.0.write(write);
911 self
912 }
913
914 /// Sets the option for the append mode.
915 ///
916 /// This option, when true, means that writes will append to a file instead
917 /// of overwriting previous contents.
918 /// Note that setting `.write(true).append(true)` has the same effect as
919 /// setting only `.append(true)`.
920 ///
921 /// For most filesystems, the operating system guarantees that all writes are
922 /// atomic: no writes get mangled because another process writes at the same
923 /// time.
924 ///
925 /// One maybe obvious note when using append-mode: make sure that all data
926 /// that belongs together is written to the file in one operation. This
927 /// can be done by concatenating strings before passing them to [`write()`],
928 /// or using a buffered writer (with a buffer of adequate size),
929 /// and calling [`flush()`] when the message is complete.
930 ///
931 /// If a file is opened with both read and append access, beware that after
932 /// opening, and after every write, the position for reading may be set at the
933 /// end of the file. So, before writing, save the current position (using
934 /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
935 ///
936 /// ## Note
937 ///
938 /// This function doesn't create the file if it doesn't exist. Use the
939 /// [`OpenOptions::create`] method to do so.
940 ///
941 /// [`write()`]: Write::write "io::Write::write"
942 /// [`flush()`]: Write::flush "io::Write::flush"
943 /// [seek]: Seek::seek "io::Seek::seek"
944 /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
945 ///
946 /// # Examples
947 ///
948 /// ```no_run
949 /// use std::fs::OpenOptions;
950 ///
951 /// let file = OpenOptions::new().append(true).open("foo.txt");
952 /// ```
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn append(&mut self, append: bool) -> &mut Self {
955 self.0.append(append);
956 self
957 }
958
959 /// Sets the option for truncating a previous file.
960 ///
961 /// If a file is successfully opened with this option set it will truncate
962 /// the file to 0 length if it already exists.
963 ///
964 /// The file must be opened with write access for truncate to work.
965 ///
966 /// # Examples
967 ///
968 /// ```no_run
969 /// use std::fs::OpenOptions;
970 ///
971 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
972 /// ```
973 #[stable(feature = "rust1", since = "1.0.0")]
974 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
975 self.0.truncate(truncate);
976 self
977 }
978
979 /// Sets the option to create a new file, or open it if it already exists.
980 ///
981 /// In order for the file to be created, [`OpenOptions::write`] or
982 /// [`OpenOptions::append`] access must be used.
983 ///
984 /// See also [`std::fs::write()`][self::write] for a simple function to
985 /// create a file with a given data.
986 ///
987 /// # Examples
988 ///
989 /// ```no_run
990 /// use std::fs::OpenOptions;
991 ///
992 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
993 /// ```
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn create(&mut self, create: bool) -> &mut Self {
996 self.0.create(create);
997 self
998 }
999
1000 /// Sets the option to create a new file, failing if it already exists.
1001 ///
1002 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
1003 /// way, if the call succeeds, the file returned is guaranteed to be new.
1004 ///
1005 /// This option is useful because it is atomic. Otherwise between checking
1006 /// whether a file exists and creating a new one, the file may have been
1007 /// created by another process (a TOCTOU race condition / attack).
1008 ///
1009 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
1010 /// ignored.
1011 ///
1012 /// The file must be opened with write or append access in order to create
1013 /// a new file.
1014 ///
1015 /// [`.create()`]: OpenOptions::create
1016 /// [`.truncate()`]: OpenOptions::truncate
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```no_run
1021 /// use std::fs::OpenOptions;
1022 ///
1023 /// let file = OpenOptions::new().write(true)
1024 /// .create_new(true)
1025 /// .open("foo.txt");
1026 /// ```
1027 #[stable(feature = "expand_open_options2", since = "1.9.0")]
1028 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
1029 self.0.create_new(create_new);
1030 self
1031 }
1032
1033 /// Opens a file at `path` with the options specified by `self`.
1034 ///
1035 /// # Errors
1036 ///
1037 /// This function will return an error under a number of different
1038 /// circumstances. Some of these error conditions are listed here, together
1039 /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
1040 /// part of the compatibility contract of the function.
1041 ///
1042 /// * [`NotFound`]: The specified file does not exist and neither `create`
1043 /// or `create_new` is set.
1044 /// * [`NotFound`]: One of the directory components of the file path does
1045 /// not exist.
1046 /// * [`PermissionDenied`]: The user lacks permission to get the specified
1047 /// access rights for the file.
1048 /// * [`PermissionDenied`]: The user lacks permission to open one of the
1049 /// directory components of the specified path.
1050 /// * [`AlreadyExists`]: `create_new` was specified and the file already
1051 /// exists.
1052 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
1053 /// without write access, no access mode set, etc.).
1054 ///
1055 /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
1056 /// * One of the directory components of the specified file path
1057 /// was not, in fact, a directory.
1058 /// * Filesystem-level errors: full disk, write permission
1059 /// requested on a read-only file system, exceeded disk quota, too many
1060 /// open files, too long filename, too many symbolic links in the
1061 /// specified path (Unix-like systems only), etc.
1062 ///
1063 /// # Examples
1064 ///
1065 /// ```no_run
1066 /// use std::fs::OpenOptions;
1067 ///
1068 /// let file = OpenOptions::new().read(true).open("foo.txt");
1069 /// ```
1070 ///
1071 /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
1072 /// [`InvalidInput`]: io::ErrorKind::InvalidInput
1073 /// [`NotFound`]: io::ErrorKind::NotFound
1074 /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
1077 self._open(path.as_ref())
1078 }
1079
1080 fn _open(&self, path: &Path) -> io::Result<File> {
1081 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
1082 }
1083 }
1084
1085 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
1086 fn as_inner(&self) -> &fs_imp::OpenOptions {
1087 &self.0
1088 }
1089 }
1090
1091 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
1092 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
1093 &mut self.0
1094 }
1095 }
1096
1097 impl Metadata {
1098 /// Returns the file type for this metadata.
1099 ///
1100 /// # Examples
1101 ///
1102 /// ```no_run
1103 /// fn main() -> std::io::Result<()> {
1104 /// use std::fs;
1105 ///
1106 /// let metadata = fs::metadata("foo.txt")?;
1107 ///
1108 /// println!("{:?}", metadata.file_type());
1109 /// Ok(())
1110 /// }
1111 /// ```
1112 #[must_use]
1113 #[stable(feature = "file_type", since = "1.1.0")]
1114 pub fn file_type(&self) -> FileType {
1115 FileType(self.0.file_type())
1116 }
1117
1118 /// Returns `true` if this metadata is for a directory. The
1119 /// result is mutually exclusive to the result of
1120 /// [`Metadata::is_file`], and will be false for symlink metadata
1121 /// obtained from [`symlink_metadata`].
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```no_run
1126 /// fn main() -> std::io::Result<()> {
1127 /// use std::fs;
1128 ///
1129 /// let metadata = fs::metadata("foo.txt")?;
1130 ///
1131 /// assert!(!metadata.is_dir());
1132 /// Ok(())
1133 /// }
1134 /// ```
1135 #[must_use]
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn is_dir(&self) -> bool {
1138 self.file_type().is_dir()
1139 }
1140
1141 /// Returns `true` if this metadata is for a regular file. The
1142 /// result is mutually exclusive to the result of
1143 /// [`Metadata::is_dir`], and will be false for symlink metadata
1144 /// obtained from [`symlink_metadata`].
1145 ///
1146 /// When the goal is simply to read from (or write to) the source, the most
1147 /// reliable way to test the source can be read (or written to) is to open
1148 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1149 /// a Unix-like system for example. See [`File::open`] or
1150 /// [`OpenOptions::open`] for more information.
1151 ///
1152 /// # Examples
1153 ///
1154 /// ```no_run
1155 /// use std::fs;
1156 ///
1157 /// fn main() -> std::io::Result<()> {
1158 /// let metadata = fs::metadata("foo.txt")?;
1159 ///
1160 /// assert!(metadata.is_file());
1161 /// Ok(())
1162 /// }
1163 /// ```
1164 #[must_use]
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub fn is_file(&self) -> bool {
1167 self.file_type().is_file()
1168 }
1169
1170 /// Returns `true` if this metadata is for a symbolic link.
1171 ///
1172 /// # Examples
1173 ///
1174 #[cfg_attr(unix, doc = "```no_run")]
1175 #[cfg_attr(not(unix), doc = "```ignore")]
1176 /// use std::fs;
1177 /// use std::path::Path;
1178 /// use std::os::unix::fs::symlink;
1179 ///
1180 /// fn main() -> std::io::Result<()> {
1181 /// let link_path = Path::new("link");
1182 /// symlink("/origin_does_not_exist/", link_path)?;
1183 ///
1184 /// let metadata = fs::symlink_metadata(link_path)?;
1185 ///
1186 /// assert!(metadata.is_symlink());
1187 /// Ok(())
1188 /// }
1189 /// ```
1190 #[must_use]
1191 #[stable(feature = "is_symlink", since = "1.58.0")]
1192 pub fn is_symlink(&self) -> bool {
1193 self.file_type().is_symlink()
1194 }
1195
1196 /// Returns the size of the file, in bytes, this metadata is for.
1197 ///
1198 /// # Examples
1199 ///
1200 /// ```no_run
1201 /// use std::fs;
1202 ///
1203 /// fn main() -> std::io::Result<()> {
1204 /// let metadata = fs::metadata("foo.txt")?;
1205 ///
1206 /// assert_eq!(0, metadata.len());
1207 /// Ok(())
1208 /// }
1209 /// ```
1210 #[must_use]
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub fn len(&self) -> u64 {
1213 self.0.size()
1214 }
1215
1216 /// Returns the permissions of the file this metadata is for.
1217 ///
1218 /// # Examples
1219 ///
1220 /// ```no_run
1221 /// use std::fs;
1222 ///
1223 /// fn main() -> std::io::Result<()> {
1224 /// let metadata = fs::metadata("foo.txt")?;
1225 ///
1226 /// assert!(!metadata.permissions().readonly());
1227 /// Ok(())
1228 /// }
1229 /// ```
1230 #[must_use]
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn permissions(&self) -> Permissions {
1233 Permissions(self.0.perm())
1234 }
1235
1236 /// Returns the last modification time listed in this metadata.
1237 ///
1238 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1239 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1240 ///
1241 /// # Errors
1242 ///
1243 /// This field might not be available on all platforms, and will return an
1244 /// `Err` on platforms where it is not available.
1245 ///
1246 /// # Examples
1247 ///
1248 /// ```no_run
1249 /// use std::fs;
1250 ///
1251 /// fn main() -> std::io::Result<()> {
1252 /// let metadata = fs::metadata("foo.txt")?;
1253 ///
1254 /// if let Ok(time) = metadata.modified() {
1255 /// println!("{time:?}");
1256 /// } else {
1257 /// println!("Not supported on this platform");
1258 /// }
1259 /// Ok(())
1260 /// }
1261 /// ```
1262 #[stable(feature = "fs_time", since = "1.10.0")]
1263 pub fn modified(&self) -> io::Result<SystemTime> {
1264 self.0.modified().map(FromInner::from_inner)
1265 }
1266
1267 /// Returns the last access time of this metadata.
1268 ///
1269 /// The returned value corresponds to the `atime` field of `stat` on Unix
1270 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1271 ///
1272 /// Note that not all platforms will keep this field update in a file's
1273 /// metadata, for example Windows has an option to disable updating this
1274 /// time when files are accessed and Linux similarly has `noatime`.
1275 ///
1276 /// # Errors
1277 ///
1278 /// This field might not be available on all platforms, and will return an
1279 /// `Err` on platforms where it is not available.
1280 ///
1281 /// # Examples
1282 ///
1283 /// ```no_run
1284 /// use std::fs;
1285 ///
1286 /// fn main() -> std::io::Result<()> {
1287 /// let metadata = fs::metadata("foo.txt")?;
1288 ///
1289 /// if let Ok(time) = metadata.accessed() {
1290 /// println!("{time:?}");
1291 /// } else {
1292 /// println!("Not supported on this platform");
1293 /// }
1294 /// Ok(())
1295 /// }
1296 /// ```
1297 #[stable(feature = "fs_time", since = "1.10.0")]
1298 pub fn accessed(&self) -> io::Result<SystemTime> {
1299 self.0.accessed().map(FromInner::from_inner)
1300 }
1301
1302 /// Returns the creation time listed in this metadata.
1303 ///
1304 /// The returned value corresponds to the `btime` field of `statx` on
1305 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1306 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1307 ///
1308 /// # Errors
1309 ///
1310 /// This field might not be available on all platforms, and will return an
1311 /// `Err` on platforms or filesystems where it is not available.
1312 ///
1313 /// # Examples
1314 ///
1315 /// ```no_run
1316 /// use std::fs;
1317 ///
1318 /// fn main() -> std::io::Result<()> {
1319 /// let metadata = fs::metadata("foo.txt")?;
1320 ///
1321 /// if let Ok(time) = metadata.created() {
1322 /// println!("{time:?}");
1323 /// } else {
1324 /// println!("Not supported on this platform or filesystem");
1325 /// }
1326 /// Ok(())
1327 /// }
1328 /// ```
1329 #[stable(feature = "fs_time", since = "1.10.0")]
1330 pub fn created(&self) -> io::Result<SystemTime> {
1331 self.0.created().map(FromInner::from_inner)
1332 }
1333 }
1334
1335 #[stable(feature = "std_debug", since = "1.16.0")]
1336 impl fmt::Debug for Metadata {
1337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1338 f.debug_struct("Metadata")
1339 .field("file_type", &self.file_type())
1340 .field("is_dir", &self.is_dir())
1341 .field("is_file", &self.is_file())
1342 .field("permissions", &self.permissions())
1343 .field("modified", &self.modified())
1344 .field("accessed", &self.accessed())
1345 .field("created", &self.created())
1346 .finish_non_exhaustive()
1347 }
1348 }
1349
1350 impl AsInner<fs_imp::FileAttr> for Metadata {
1351 fn as_inner(&self) -> &fs_imp::FileAttr {
1352 &self.0
1353 }
1354 }
1355
1356 impl FromInner<fs_imp::FileAttr> for Metadata {
1357 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1358 Metadata(attr)
1359 }
1360 }
1361
1362 impl FileTimes {
1363 /// Create a new `FileTimes` with no times set.
1364 ///
1365 /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
1366 #[unstable(feature = "file_set_times", issue = "98245")]
1367 pub fn new() -> Self {
1368 Self::default()
1369 }
1370
1371 /// Set the last access time of a file.
1372 #[unstable(feature = "file_set_times", issue = "98245")]
1373 pub fn set_accessed(mut self, t: SystemTime) -> Self {
1374 self.0.set_accessed(t.into_inner());
1375 self
1376 }
1377
1378 /// Set the last modified time of a file.
1379 #[unstable(feature = "file_set_times", issue = "98245")]
1380 pub fn set_modified(mut self, t: SystemTime) -> Self {
1381 self.0.set_modified(t.into_inner());
1382 self
1383 }
1384 }
1385
1386 impl Permissions {
1387 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1388 ///
1389 /// # Note
1390 ///
1391 /// This function does not take Access Control Lists (ACLs) or Unix group
1392 /// membership into account.
1393 ///
1394 /// # Windows
1395 ///
1396 /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1397 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1398 /// but the user may still have permission to change this flag. If
1399 /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
1400 /// to lack of write permission.
1401 /// The behavior of this attribute for directories depends on the Windows
1402 /// version.
1403 ///
1404 /// # Unix (including macOS)
1405 ///
1406 /// On Unix-based platforms this checks if *any* of the owner, group or others
1407 /// write permission bits are set. It does not check if the current
1408 /// user is in the file's assigned group. It also does not check ACLs.
1409 /// Therefore even if this returns true you may not be able to write to the
1410 /// file, and vice versa. The [`PermissionsExt`] trait gives direct access
1411 /// to the permission bits but also does not read ACLs. If you need to
1412 /// accurately know whether or not a file is writable use the `access()`
1413 /// function from libc.
1414 ///
1415 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1416 ///
1417 /// # Examples
1418 ///
1419 /// ```no_run
1420 /// use std::fs::File;
1421 ///
1422 /// fn main() -> std::io::Result<()> {
1423 /// let mut f = File::create("foo.txt")?;
1424 /// let metadata = f.metadata()?;
1425 ///
1426 /// assert_eq!(false, metadata.permissions().readonly());
1427 /// Ok(())
1428 /// }
1429 /// ```
1430 #[must_use = "call `set_readonly` to modify the readonly flag"]
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn readonly(&self) -> bool {
1433 self.0.readonly()
1434 }
1435
1436 /// Modifies the readonly flag for this set of permissions. If the
1437 /// `readonly` argument is `true`, using the resulting `Permission` will
1438 /// update file permissions to forbid writing. Conversely, if it's `false`,
1439 /// using the resulting `Permission` will update file permissions to allow
1440 /// writing.
1441 ///
1442 /// This operation does **not** modify the files attributes. This only
1443 /// changes the in-memory value of these attributes for this `Permissions`
1444 /// instance. To modify the files attributes use the [`set_permissions`]
1445 /// function which commits these attribute changes to the file.
1446 ///
1447 /// # Note
1448 ///
1449 /// `set_readonly(false)` makes the file *world-writable* on Unix.
1450 /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
1451 ///
1452 /// It also does not take Access Control Lists (ACLs) or Unix group
1453 /// membership into account.
1454 ///
1455 /// # Windows
1456 ///
1457 /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
1458 /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
1459 /// but the user may still have permission to change this flag. If
1460 /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
1461 /// the user does not have permission to write to the file.
1462 ///
1463 /// In Windows 7 and earlier this attribute prevents deleting empty
1464 /// directories. It does not prevent modifying the directory contents.
1465 /// On later versions of Windows this attribute is ignored for directories.
1466 ///
1467 /// # Unix (including macOS)
1468 ///
1469 /// On Unix-based platforms this sets or clears the write access bit for
1470 /// the owner, group *and* others, equivalent to `chmod a+w <file>`
1471 /// or `chmod a-w <file>` respectively. The latter will grant write access
1472 /// to all users! You can use the [`PermissionsExt`] trait on Unix
1473 /// to avoid this issue.
1474 ///
1475 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
1476 ///
1477 /// # Examples
1478 ///
1479 /// ```no_run
1480 /// use std::fs::File;
1481 ///
1482 /// fn main() -> std::io::Result<()> {
1483 /// let f = File::create("foo.txt")?;
1484 /// let metadata = f.metadata()?;
1485 /// let mut permissions = metadata.permissions();
1486 ///
1487 /// permissions.set_readonly(true);
1488 ///
1489 /// // filesystem doesn't change, only the in memory state of the
1490 /// // readonly permission
1491 /// assert_eq!(false, metadata.permissions().readonly());
1492 ///
1493 /// // just this particular `permissions`.
1494 /// assert_eq!(true, permissions.readonly());
1495 /// Ok(())
1496 /// }
1497 /// ```
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn set_readonly(&mut self, readonly: bool) {
1500 self.0.set_readonly(readonly)
1501 }
1502 }
1503
1504 impl FileType {
1505 /// Tests whether this file type represents a directory. The
1506 /// result is mutually exclusive to the results of
1507 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1508 /// tests may pass.
1509 ///
1510 /// [`is_file`]: FileType::is_file
1511 /// [`is_symlink`]: FileType::is_symlink
1512 ///
1513 /// # Examples
1514 ///
1515 /// ```no_run
1516 /// fn main() -> std::io::Result<()> {
1517 /// use std::fs;
1518 ///
1519 /// let metadata = fs::metadata("foo.txt")?;
1520 /// let file_type = metadata.file_type();
1521 ///
1522 /// assert_eq!(file_type.is_dir(), false);
1523 /// Ok(())
1524 /// }
1525 /// ```
1526 #[must_use]
1527 #[stable(feature = "file_type", since = "1.1.0")]
1528 pub fn is_dir(&self) -> bool {
1529 self.0.is_dir()
1530 }
1531
1532 /// Tests whether this file type represents a regular file.
1533 /// The result is mutually exclusive to the results of
1534 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1535 /// tests may pass.
1536 ///
1537 /// When the goal is simply to read from (or write to) the source, the most
1538 /// reliable way to test the source can be read (or written to) is to open
1539 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1540 /// a Unix-like system for example. See [`File::open`] or
1541 /// [`OpenOptions::open`] for more information.
1542 ///
1543 /// [`is_dir`]: FileType::is_dir
1544 /// [`is_symlink`]: FileType::is_symlink
1545 ///
1546 /// # Examples
1547 ///
1548 /// ```no_run
1549 /// fn main() -> std::io::Result<()> {
1550 /// use std::fs;
1551 ///
1552 /// let metadata = fs::metadata("foo.txt")?;
1553 /// let file_type = metadata.file_type();
1554 ///
1555 /// assert_eq!(file_type.is_file(), true);
1556 /// Ok(())
1557 /// }
1558 /// ```
1559 #[must_use]
1560 #[stable(feature = "file_type", since = "1.1.0")]
1561 pub fn is_file(&self) -> bool {
1562 self.0.is_file()
1563 }
1564
1565 /// Tests whether this file type represents a symbolic link.
1566 /// The result is mutually exclusive to the results of
1567 /// [`is_dir`] and [`is_file`]; only zero or one of these
1568 /// tests may pass.
1569 ///
1570 /// The underlying [`Metadata`] struct needs to be retrieved
1571 /// with the [`fs::symlink_metadata`] function and not the
1572 /// [`fs::metadata`] function. The [`fs::metadata`] function
1573 /// follows symbolic links, so [`is_symlink`] would always
1574 /// return `false` for the target file.
1575 ///
1576 /// [`fs::metadata`]: metadata
1577 /// [`fs::symlink_metadata`]: symlink_metadata
1578 /// [`is_dir`]: FileType::is_dir
1579 /// [`is_file`]: FileType::is_file
1580 /// [`is_symlink`]: FileType::is_symlink
1581 ///
1582 /// # Examples
1583 ///
1584 /// ```no_run
1585 /// use std::fs;
1586 ///
1587 /// fn main() -> std::io::Result<()> {
1588 /// let metadata = fs::symlink_metadata("foo.txt")?;
1589 /// let file_type = metadata.file_type();
1590 ///
1591 /// assert_eq!(file_type.is_symlink(), false);
1592 /// Ok(())
1593 /// }
1594 /// ```
1595 #[must_use]
1596 #[stable(feature = "file_type", since = "1.1.0")]
1597 pub fn is_symlink(&self) -> bool {
1598 self.0.is_symlink()
1599 }
1600 }
1601
1602 impl AsInner<fs_imp::FileType> for FileType {
1603 fn as_inner(&self) -> &fs_imp::FileType {
1604 &self.0
1605 }
1606 }
1607
1608 impl FromInner<fs_imp::FilePermissions> for Permissions {
1609 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1610 Permissions(f)
1611 }
1612 }
1613
1614 impl AsInner<fs_imp::FilePermissions> for Permissions {
1615 fn as_inner(&self) -> &fs_imp::FilePermissions {
1616 &self.0
1617 }
1618 }
1619
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl Iterator for ReadDir {
1622 type Item = io::Result<DirEntry>;
1623
1624 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1625 self.0.next().map(|entry| entry.map(DirEntry))
1626 }
1627 }
1628
1629 impl DirEntry {
1630 /// Returns the full path to the file that this entry represents.
1631 ///
1632 /// The full path is created by joining the original path to `read_dir`
1633 /// with the filename of this entry.
1634 ///
1635 /// # Examples
1636 ///
1637 /// ```no_run
1638 /// use std::fs;
1639 ///
1640 /// fn main() -> std::io::Result<()> {
1641 /// for entry in fs::read_dir(".")? {
1642 /// let dir = entry?;
1643 /// println!("{:?}", dir.path());
1644 /// }
1645 /// Ok(())
1646 /// }
1647 /// ```
1648 ///
1649 /// This prints output like:
1650 ///
1651 /// ```text
1652 /// "./whatever.txt"
1653 /// "./foo.html"
1654 /// "./hello_world.rs"
1655 /// ```
1656 ///
1657 /// The exact text, of course, depends on what files you have in `.`.
1658 #[must_use]
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 pub fn path(&self) -> PathBuf {
1661 self.0.path()
1662 }
1663
1664 /// Returns the metadata for the file that this entry points at.
1665 ///
1666 /// This function will not traverse symlinks if this entry points at a
1667 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1668 ///
1669 /// [`fs::metadata`]: metadata
1670 /// [`fs::File::metadata`]: File::metadata
1671 ///
1672 /// # Platform-specific behavior
1673 ///
1674 /// On Windows this function is cheap to call (no extra system calls
1675 /// needed), but on Unix platforms this function is the equivalent of
1676 /// calling `symlink_metadata` on the path.
1677 ///
1678 /// # Examples
1679 ///
1680 /// ```
1681 /// use std::fs;
1682 ///
1683 /// if let Ok(entries) = fs::read_dir(".") {
1684 /// for entry in entries {
1685 /// if let Ok(entry) = entry {
1686 /// // Here, `entry` is a `DirEntry`.
1687 /// if let Ok(metadata) = entry.metadata() {
1688 /// // Now let's show our entry's permissions!
1689 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1690 /// } else {
1691 /// println!("Couldn't get metadata for {:?}", entry.path());
1692 /// }
1693 /// }
1694 /// }
1695 /// }
1696 /// ```
1697 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1698 pub fn metadata(&self) -> io::Result<Metadata> {
1699 self.0.metadata().map(Metadata)
1700 }
1701
1702 /// Returns the file type for the file that this entry points at.
1703 ///
1704 /// This function will not traverse symlinks if this entry points at a
1705 /// symlink.
1706 ///
1707 /// # Platform-specific behavior
1708 ///
1709 /// On Windows and most Unix platforms this function is free (no extra
1710 /// system calls needed), but some Unix platforms may require the equivalent
1711 /// call to `symlink_metadata` to learn about the target file type.
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// use std::fs;
1717 ///
1718 /// if let Ok(entries) = fs::read_dir(".") {
1719 /// for entry in entries {
1720 /// if let Ok(entry) = entry {
1721 /// // Here, `entry` is a `DirEntry`.
1722 /// if let Ok(file_type) = entry.file_type() {
1723 /// // Now let's show our entry's file type!
1724 /// println!("{:?}: {:?}", entry.path(), file_type);
1725 /// } else {
1726 /// println!("Couldn't get file type for {:?}", entry.path());
1727 /// }
1728 /// }
1729 /// }
1730 /// }
1731 /// ```
1732 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1733 pub fn file_type(&self) -> io::Result<FileType> {
1734 self.0.file_type().map(FileType)
1735 }
1736
1737 /// Returns the bare file name of this directory entry without any other
1738 /// leading path component.
1739 ///
1740 /// # Examples
1741 ///
1742 /// ```
1743 /// use std::fs;
1744 ///
1745 /// if let Ok(entries) = fs::read_dir(".") {
1746 /// for entry in entries {
1747 /// if let Ok(entry) = entry {
1748 /// // Here, `entry` is a `DirEntry`.
1749 /// println!("{:?}", entry.file_name());
1750 /// }
1751 /// }
1752 /// }
1753 /// ```
1754 #[must_use]
1755 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1756 pub fn file_name(&self) -> OsString {
1757 self.0.file_name()
1758 }
1759 }
1760
1761 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1762 impl fmt::Debug for DirEntry {
1763 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1764 f.debug_tuple("DirEntry").field(&self.path()).finish()
1765 }
1766 }
1767
1768 impl AsInner<fs_imp::DirEntry> for DirEntry {
1769 fn as_inner(&self) -> &fs_imp::DirEntry {
1770 &self.0
1771 }
1772 }
1773
1774 /// Removes a file from the filesystem.
1775 ///
1776 /// Note that there is no
1777 /// guarantee that the file is immediately deleted (e.g., depending on
1778 /// platform, other open file descriptors may prevent immediate removal).
1779 ///
1780 /// # Platform-specific behavior
1781 ///
1782 /// This function currently corresponds to the `unlink` function on Unix
1783 /// and the `DeleteFile` function on Windows.
1784 /// Note that, this [may change in the future][changes].
1785 ///
1786 /// [changes]: io#platform-specific-behavior
1787 ///
1788 /// # Errors
1789 ///
1790 /// This function will return an error in the following situations, but is not
1791 /// limited to just these cases:
1792 ///
1793 /// * `path` points to a directory.
1794 /// * The file doesn't exist.
1795 /// * The user lacks permissions to remove the file.
1796 ///
1797 /// # Examples
1798 ///
1799 /// ```no_run
1800 /// use std::fs;
1801 ///
1802 /// fn main() -> std::io::Result<()> {
1803 /// fs::remove_file("a.txt")?;
1804 /// Ok(())
1805 /// }
1806 /// ```
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1809 fs_imp::unlink(path.as_ref())
1810 }
1811
1812 /// Given a path, query the file system to get information about a file,
1813 /// directory, etc.
1814 ///
1815 /// This function will traverse symbolic links to query information about the
1816 /// destination file.
1817 ///
1818 /// # Platform-specific behavior
1819 ///
1820 /// This function currently corresponds to the `stat` function on Unix
1821 /// and the `GetFileInformationByHandle` function on Windows.
1822 /// Note that, this [may change in the future][changes].
1823 ///
1824 /// [changes]: io#platform-specific-behavior
1825 ///
1826 /// # Errors
1827 ///
1828 /// This function will return an error in the following situations, but is not
1829 /// limited to just these cases:
1830 ///
1831 /// * The user lacks permissions to perform `metadata` call on `path`.
1832 /// * `path` does not exist.
1833 ///
1834 /// # Examples
1835 ///
1836 /// ```rust,no_run
1837 /// use std::fs;
1838 ///
1839 /// fn main() -> std::io::Result<()> {
1840 /// let attr = fs::metadata("/some/file/path.txt")?;
1841 /// // inspect attr ...
1842 /// Ok(())
1843 /// }
1844 /// ```
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1847 fs_imp::stat(path.as_ref()).map(Metadata)
1848 }
1849
1850 /// Query the metadata about a file without following symlinks.
1851 ///
1852 /// # Platform-specific behavior
1853 ///
1854 /// This function currently corresponds to the `lstat` function on Unix
1855 /// and the `GetFileInformationByHandle` function on Windows.
1856 /// Note that, this [may change in the future][changes].
1857 ///
1858 /// [changes]: io#platform-specific-behavior
1859 ///
1860 /// # Errors
1861 ///
1862 /// This function will return an error in the following situations, but is not
1863 /// limited to just these cases:
1864 ///
1865 /// * The user lacks permissions to perform `metadata` call on `path`.
1866 /// * `path` does not exist.
1867 ///
1868 /// # Examples
1869 ///
1870 /// ```rust,no_run
1871 /// use std::fs;
1872 ///
1873 /// fn main() -> std::io::Result<()> {
1874 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1875 /// // inspect attr ...
1876 /// Ok(())
1877 /// }
1878 /// ```
1879 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1880 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1881 fs_imp::lstat(path.as_ref()).map(Metadata)
1882 }
1883
1884 /// Rename a file or directory to a new name, replacing the original file if
1885 /// `to` already exists.
1886 ///
1887 /// This will not work if the new name is on a different mount point.
1888 ///
1889 /// # Platform-specific behavior
1890 ///
1891 /// This function currently corresponds to the `rename` function on Unix
1892 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1893 ///
1894 /// Because of this, the behavior when both `from` and `to` exist differs. On
1895 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1896 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1897 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1898 ///
1899 /// Note that, this [may change in the future][changes].
1900 ///
1901 /// [changes]: io#platform-specific-behavior
1902 ///
1903 /// # Errors
1904 ///
1905 /// This function will return an error in the following situations, but is not
1906 /// limited to just these cases:
1907 ///
1908 /// * `from` does not exist.
1909 /// * The user lacks permissions to view contents.
1910 /// * `from` and `to` are on separate filesystems.
1911 ///
1912 /// # Examples
1913 ///
1914 /// ```no_run
1915 /// use std::fs;
1916 ///
1917 /// fn main() -> std::io::Result<()> {
1918 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1919 /// Ok(())
1920 /// }
1921 /// ```
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1924 fs_imp::rename(from.as_ref(), to.as_ref())
1925 }
1926
1927 /// Copies the contents of one file to another. This function will also
1928 /// copy the permission bits of the original file to the destination file.
1929 ///
1930 /// This function will **overwrite** the contents of `to`.
1931 ///
1932 /// Note that if `from` and `to` both point to the same file, then the file
1933 /// will likely get truncated by this operation.
1934 ///
1935 /// On success, the total number of bytes copied is returned and it is equal to
1936 /// the length of the `to` file as reported by `metadata`.
1937 ///
1938 /// If you’re wanting to copy the contents of one file to another and you’re
1939 /// working with [`File`]s, see the [`io::copy()`] function.
1940 ///
1941 /// # Platform-specific behavior
1942 ///
1943 /// This function currently corresponds to the `open` function in Unix
1944 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1945 /// `O_CLOEXEC` is set for returned file descriptors.
1946 ///
1947 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1948 /// and falls back to reading and writing if that is not possible.
1949 ///
1950 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1951 /// NTFS streams are copied but only the size of the main stream is returned by
1952 /// this function.
1953 ///
1954 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1955 ///
1956 /// Note that platform-specific behavior [may change in the future][changes].
1957 ///
1958 /// [changes]: io#platform-specific-behavior
1959 ///
1960 /// # Errors
1961 ///
1962 /// This function will return an error in the following situations, but is not
1963 /// limited to just these cases:
1964 ///
1965 /// * `from` is neither a regular file nor a symlink to a regular file.
1966 /// * `from` does not exist.
1967 /// * The current process does not have the permission rights to read
1968 /// `from` or write `to`.
1969 ///
1970 /// # Examples
1971 ///
1972 /// ```no_run
1973 /// use std::fs;
1974 ///
1975 /// fn main() -> std::io::Result<()> {
1976 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1977 /// Ok(())
1978 /// }
1979 /// ```
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1982 fs_imp::copy(from.as_ref(), to.as_ref())
1983 }
1984
1985 /// Creates a new hard link on the filesystem.
1986 ///
1987 /// The `link` path will be a link pointing to the `original` path. Note that
1988 /// systems often require these two paths to both be located on the same
1989 /// filesystem.
1990 ///
1991 /// If `original` names a symbolic link, it is platform-specific whether the
1992 /// symbolic link is followed. On platforms where it's possible to not follow
1993 /// it, it is not followed, and the created hard link points to the symbolic
1994 /// link itself.
1995 ///
1996 /// # Platform-specific behavior
1997 ///
1998 /// This function currently corresponds the `CreateHardLink` function on Windows.
1999 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
2000 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
2001 /// On MacOS, it uses the `linkat` function if it is available, but on very old
2002 /// systems where `linkat` is not available, `link` is selected at runtime instead.
2003 /// Note that, this [may change in the future][changes].
2004 ///
2005 /// [changes]: io#platform-specific-behavior
2006 ///
2007 /// # Errors
2008 ///
2009 /// This function will return an error in the following situations, but is not
2010 /// limited to just these cases:
2011 ///
2012 /// * The `original` path is not a file or doesn't exist.
2013 ///
2014 /// # Examples
2015 ///
2016 /// ```no_run
2017 /// use std::fs;
2018 ///
2019 /// fn main() -> std::io::Result<()> {
2020 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
2021 /// Ok(())
2022 /// }
2023 /// ```
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2026 fs_imp::link(original.as_ref(), link.as_ref())
2027 }
2028
2029 /// Creates a new symbolic link on the filesystem.
2030 ///
2031 /// The `link` path will be a symbolic link pointing to the `original` path.
2032 /// On Windows, this will be a file symlink, not a directory symlink;
2033 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
2034 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
2035 /// used instead to make the intent explicit.
2036 ///
2037 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
2038 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
2039 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
2040 ///
2041 /// # Examples
2042 ///
2043 /// ```no_run
2044 /// use std::fs;
2045 ///
2046 /// fn main() -> std::io::Result<()> {
2047 /// fs::soft_link("a.txt", "b.txt")?;
2048 /// Ok(())
2049 /// }
2050 /// ```
2051 #[stable(feature = "rust1", since = "1.0.0")]
2052 #[deprecated(
2053 since = "1.1.0",
2054 note = "replaced with std::os::unix::fs::symlink and \
2055 std::os::windows::fs::{symlink_file, symlink_dir}"
2056 )]
2057 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
2058 fs_imp::symlink(original.as_ref(), link.as_ref())
2059 }
2060
2061 /// Reads a symbolic link, returning the file that the link points to.
2062 ///
2063 /// # Platform-specific behavior
2064 ///
2065 /// This function currently corresponds to the `readlink` function on Unix
2066 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
2067 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
2068 /// Note that, this [may change in the future][changes].
2069 ///
2070 /// [changes]: io#platform-specific-behavior
2071 ///
2072 /// # Errors
2073 ///
2074 /// This function will return an error in the following situations, but is not
2075 /// limited to just these cases:
2076 ///
2077 /// * `path` is not a symbolic link.
2078 /// * `path` does not exist.
2079 ///
2080 /// # Examples
2081 ///
2082 /// ```no_run
2083 /// use std::fs;
2084 ///
2085 /// fn main() -> std::io::Result<()> {
2086 /// let path = fs::read_link("a.txt")?;
2087 /// Ok(())
2088 /// }
2089 /// ```
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2092 fs_imp::readlink(path.as_ref())
2093 }
2094
2095 /// Returns the canonical, absolute form of a path with all intermediate
2096 /// components normalized and symbolic links resolved.
2097 ///
2098 /// # Platform-specific behavior
2099 ///
2100 /// This function currently corresponds to the `realpath` function on Unix
2101 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
2102 /// Note that, this [may change in the future][changes].
2103 ///
2104 /// On Windows, this converts the path to use [extended length path][path]
2105 /// syntax, which allows your program to use longer path names, but means you
2106 /// can only join backslash-delimited paths to it, and it may be incompatible
2107 /// with other applications (if passed to the application on the command-line,
2108 /// or written to a file another application may read).
2109 ///
2110 /// [changes]: io#platform-specific-behavior
2111 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
2112 ///
2113 /// # Errors
2114 ///
2115 /// This function will return an error in the following situations, but is not
2116 /// limited to just these cases:
2117 ///
2118 /// * `path` does not exist.
2119 /// * A non-final component in path is not a directory.
2120 ///
2121 /// # Examples
2122 ///
2123 /// ```no_run
2124 /// use std::fs;
2125 ///
2126 /// fn main() -> std::io::Result<()> {
2127 /// let path = fs::canonicalize("../a/../foo.txt")?;
2128 /// Ok(())
2129 /// }
2130 /// ```
2131 #[doc(alias = "realpath")]
2132 #[doc(alias = "GetFinalPathNameByHandle")]
2133 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
2134 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
2135 fs_imp::canonicalize(path.as_ref())
2136 }
2137
2138 /// Creates a new, empty directory at the provided path
2139 ///
2140 /// # Platform-specific behavior
2141 ///
2142 /// This function currently corresponds to the `mkdir` function on Unix
2143 /// and the `CreateDirectory` function on Windows.
2144 /// Note that, this [may change in the future][changes].
2145 ///
2146 /// [changes]: io#platform-specific-behavior
2147 ///
2148 /// **NOTE**: If a parent of the given path doesn't exist, this function will
2149 /// return an error. To create a directory and all its missing parents at the
2150 /// same time, use the [`create_dir_all`] function.
2151 ///
2152 /// # Errors
2153 ///
2154 /// This function will return an error in the following situations, but is not
2155 /// limited to just these cases:
2156 ///
2157 /// * User lacks permissions to create directory at `path`.
2158 /// * A parent of the given path doesn't exist. (To create a directory and all
2159 /// its missing parents at the same time, use the [`create_dir_all`]
2160 /// function.)
2161 /// * `path` already exists.
2162 ///
2163 /// # Examples
2164 ///
2165 /// ```no_run
2166 /// use std::fs;
2167 ///
2168 /// fn main() -> std::io::Result<()> {
2169 /// fs::create_dir("/some/dir")?;
2170 /// Ok(())
2171 /// }
2172 /// ```
2173 #[doc(alias = "mkdir")]
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2176 DirBuilder::new().create(path.as_ref())
2177 }
2178
2179 /// Recursively create a directory and all of its parent components if they
2180 /// are missing.
2181 ///
2182 /// # Platform-specific behavior
2183 ///
2184 /// This function currently corresponds to the `mkdir` function on Unix
2185 /// and the `CreateDirectory` function on Windows.
2186 /// Note that, this [may change in the future][changes].
2187 ///
2188 /// [changes]: io#platform-specific-behavior
2189 ///
2190 /// # Errors
2191 ///
2192 /// This function will return an error in the following situations, but is not
2193 /// limited to just these cases:
2194 ///
2195 /// * If any directory in the path specified by `path`
2196 /// does not already exist and it could not be created otherwise. The specific
2197 /// error conditions for when a directory is being created (after it is
2198 /// determined to not exist) are outlined by [`fs::create_dir`].
2199 ///
2200 /// Notable exception is made for situations where any of the directories
2201 /// specified in the `path` could not be created as it was being created concurrently.
2202 /// Such cases are considered to be successful. That is, calling `create_dir_all`
2203 /// concurrently from multiple threads or processes is guaranteed not to fail
2204 /// due to a race condition with itself.
2205 ///
2206 /// [`fs::create_dir`]: create_dir
2207 ///
2208 /// # Examples
2209 ///
2210 /// ```no_run
2211 /// use std::fs;
2212 ///
2213 /// fn main() -> std::io::Result<()> {
2214 /// fs::create_dir_all("/some/dir")?;
2215 /// Ok(())
2216 /// }
2217 /// ```
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2220 DirBuilder::new().recursive(true).create(path.as_ref())
2221 }
2222
2223 /// Removes an empty directory.
2224 ///
2225 /// # Platform-specific behavior
2226 ///
2227 /// This function currently corresponds to the `rmdir` function on Unix
2228 /// and the `RemoveDirectory` function on Windows.
2229 /// Note that, this [may change in the future][changes].
2230 ///
2231 /// [changes]: io#platform-specific-behavior
2232 ///
2233 /// # Errors
2234 ///
2235 /// This function will return an error in the following situations, but is not
2236 /// limited to just these cases:
2237 ///
2238 /// * `path` doesn't exist.
2239 /// * `path` isn't a directory.
2240 /// * The user lacks permissions to remove the directory at the provided `path`.
2241 /// * The directory isn't empty.
2242 ///
2243 /// # Examples
2244 ///
2245 /// ```no_run
2246 /// use std::fs;
2247 ///
2248 /// fn main() -> std::io::Result<()> {
2249 /// fs::remove_dir("/some/dir")?;
2250 /// Ok(())
2251 /// }
2252 /// ```
2253 #[doc(alias = "rmdir")]
2254 #[stable(feature = "rust1", since = "1.0.0")]
2255 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2256 fs_imp::rmdir(path.as_ref())
2257 }
2258
2259 /// Removes a directory at this path, after removing all its contents. Use
2260 /// carefully!
2261 ///
2262 /// This function does **not** follow symbolic links and it will simply remove the
2263 /// symbolic link itself.
2264 ///
2265 /// # Platform-specific behavior
2266 ///
2267 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2268 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2269 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2270 /// Windows. Note that, this [may change in the future][changes].
2271 ///
2272 /// [changes]: io#platform-specific-behavior
2273 ///
2274 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2275 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2276 /// should not be used in security-sensitive code on those platforms. All other platforms are
2277 /// protected.
2278 ///
2279 /// # Errors
2280 ///
2281 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2282 ///
2283 /// [`fs::remove_file`]: remove_file
2284 /// [`fs::remove_dir`]: remove_dir
2285 ///
2286 /// # Examples
2287 ///
2288 /// ```no_run
2289 /// use std::fs;
2290 ///
2291 /// fn main() -> std::io::Result<()> {
2292 /// fs::remove_dir_all("/some/dir")?;
2293 /// Ok(())
2294 /// }
2295 /// ```
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2298 fs_imp::remove_dir_all(path.as_ref())
2299 }
2300
2301 /// Returns an iterator over the entries within a directory.
2302 ///
2303 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2304 /// New errors may be encountered after an iterator is initially constructed.
2305 /// Entries for the current and parent directories (typically `.` and `..`) are
2306 /// skipped.
2307 ///
2308 /// # Platform-specific behavior
2309 ///
2310 /// This function currently corresponds to the `opendir` function on Unix
2311 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2312 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2313 /// Note that, this [may change in the future][changes].
2314 ///
2315 /// [changes]: io#platform-specific-behavior
2316 ///
2317 /// The order in which this iterator returns entries is platform and filesystem
2318 /// dependent.
2319 ///
2320 /// # Errors
2321 ///
2322 /// This function will return an error in the following situations, but is not
2323 /// limited to just these cases:
2324 ///
2325 /// * The provided `path` doesn't exist.
2326 /// * The process lacks permissions to view the contents.
2327 /// * The `path` points at a non-directory file.
2328 ///
2329 /// # Examples
2330 ///
2331 /// ```
2332 /// use std::io;
2333 /// use std::fs::{self, DirEntry};
2334 /// use std::path::Path;
2335 ///
2336 /// // one possible implementation of walking a directory only visiting files
2337 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2338 /// if dir.is_dir() {
2339 /// for entry in fs::read_dir(dir)? {
2340 /// let entry = entry?;
2341 /// let path = entry.path();
2342 /// if path.is_dir() {
2343 /// visit_dirs(&path, cb)?;
2344 /// } else {
2345 /// cb(&entry);
2346 /// }
2347 /// }
2348 /// }
2349 /// Ok(())
2350 /// }
2351 /// ```
2352 ///
2353 /// ```rust,no_run
2354 /// use std::{fs, io};
2355 ///
2356 /// fn main() -> io::Result<()> {
2357 /// let mut entries = fs::read_dir(".")?
2358 /// .map(|res| res.map(|e| e.path()))
2359 /// .collect::<Result<Vec<_>, io::Error>>()?;
2360 ///
2361 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2362 /// // ordering is required the entries should be explicitly sorted.
2363 ///
2364 /// entries.sort();
2365 ///
2366 /// // The entries have now been sorted by their path.
2367 ///
2368 /// Ok(())
2369 /// }
2370 /// ```
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2373 fs_imp::readdir(path.as_ref()).map(ReadDir)
2374 }
2375
2376 /// Changes the permissions found on a file or a directory.
2377 ///
2378 /// # Platform-specific behavior
2379 ///
2380 /// This function currently corresponds to the `chmod` function on Unix
2381 /// and the `SetFileAttributes` function on Windows.
2382 /// Note that, this [may change in the future][changes].
2383 ///
2384 /// [changes]: io#platform-specific-behavior
2385 ///
2386 /// # Errors
2387 ///
2388 /// This function will return an error in the following situations, but is not
2389 /// limited to just these cases:
2390 ///
2391 /// * `path` does not exist.
2392 /// * The user lacks the permission to change attributes of the file.
2393 ///
2394 /// # Examples
2395 ///
2396 /// ```no_run
2397 /// use std::fs;
2398 ///
2399 /// fn main() -> std::io::Result<()> {
2400 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2401 /// perms.set_readonly(true);
2402 /// fs::set_permissions("foo.txt", perms)?;
2403 /// Ok(())
2404 /// }
2405 /// ```
2406 #[stable(feature = "set_permissions", since = "1.1.0")]
2407 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2408 fs_imp::set_perm(path.as_ref(), perm.0)
2409 }
2410
2411 impl DirBuilder {
2412 /// Creates a new set of options with default mode/security settings for all
2413 /// platforms and also non-recursive.
2414 ///
2415 /// # Examples
2416 ///
2417 /// ```
2418 /// use std::fs::DirBuilder;
2419 ///
2420 /// let builder = DirBuilder::new();
2421 /// ```
2422 #[stable(feature = "dir_builder", since = "1.6.0")]
2423 #[must_use]
2424 pub fn new() -> DirBuilder {
2425 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2426 }
2427
2428 /// Indicates that directories should be created recursively, creating all
2429 /// parent directories. Parents that do not exist are created with the same
2430 /// security and permissions settings.
2431 ///
2432 /// This option defaults to `false`.
2433 ///
2434 /// # Examples
2435 ///
2436 /// ```
2437 /// use std::fs::DirBuilder;
2438 ///
2439 /// let mut builder = DirBuilder::new();
2440 /// builder.recursive(true);
2441 /// ```
2442 #[stable(feature = "dir_builder", since = "1.6.0")]
2443 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2444 self.recursive = recursive;
2445 self
2446 }
2447
2448 /// Creates the specified directory with the options configured in this
2449 /// builder.
2450 ///
2451 /// It is considered an error if the directory already exists unless
2452 /// recursive mode is enabled.
2453 ///
2454 /// # Examples
2455 ///
2456 /// ```no_run
2457 /// use std::fs::{self, DirBuilder};
2458 ///
2459 /// let path = "/tmp/foo/bar/baz";
2460 /// DirBuilder::new()
2461 /// .recursive(true)
2462 /// .create(path).unwrap();
2463 ///
2464 /// assert!(fs::metadata(path).unwrap().is_dir());
2465 /// ```
2466 #[stable(feature = "dir_builder", since = "1.6.0")]
2467 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2468 self._create(path.as_ref())
2469 }
2470
2471 fn _create(&self, path: &Path) -> io::Result<()> {
2472 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2473 }
2474
2475 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2476 if path == Path::new("") {
2477 return Ok(());
2478 }
2479
2480 match self.inner.mkdir(path) {
2481 Ok(()) => return Ok(()),
2482 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2483 Err(_) if path.is_dir() => return Ok(()),
2484 Err(e) => return Err(e),
2485 }
2486 match path.parent() {
2487 Some(p) => self.create_dir_all(p)?,
2488 None => {
2489 return Err(io::const_io_error!(
2490 io::ErrorKind::Uncategorized,
2491 "failed to create whole tree",
2492 ));
2493 }
2494 }
2495 match self.inner.mkdir(path) {
2496 Ok(()) => Ok(()),
2497 Err(_) if path.is_dir() => Ok(()),
2498 Err(e) => Err(e),
2499 }
2500 }
2501 }
2502
2503 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2504 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2505 &mut self.inner
2506 }
2507 }
2508
2509 /// Returns `Ok(true)` if the path points at an existing entity.
2510 ///
2511 /// This function will traverse symbolic links to query information about the
2512 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2513 ///
2514 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2515 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2516 /// denied on some of the parent directories.)
2517 ///
2518 /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
2519 /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
2520 /// where those bugs are not an issue.
2521 ///
2522 /// # Examples
2523 ///
2524 /// ```no_run
2525 /// #![feature(fs_try_exists)]
2526 /// use std::fs;
2527 ///
2528 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2529 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2530 /// ```
2531 ///
2532 /// [`Path::exists`]: crate::path::Path::exists
2533 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2534 // instead.
2535 #[unstable(feature = "fs_try_exists", issue = "83186")]
2536 #[inline]
2537 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2538 fs_imp::try_exists(path.as_ref())
2539 }