std/os/windows/fs.rs
1//! Windows-specific extensions to primitives in the [`std::fs`] module.
2//!
3//! [`std::fs`]: crate::fs
4
5#![stable(feature = "rust1", since = "1.0.0")]
6
7use crate::fs::{self, Metadata, OpenOptions, Permissions};
8use crate::io::BorrowedCursor;
9use crate::macros::rustdoc_skip_body;
10use crate::path::Path;
11use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner};
12use crate::time::SystemTime;
13use crate::{io, sys};
14
15mod dirs;
16
17#[unstable(feature = "fs_home_dirs", issue = "162082")]
18pub use dirs::HomeDirsExt;
19#[unstable(feature = "fs_media_dirs", issue = "162083")]
20pub use dirs::MediaDirsExt;
21
22/// Windows-specific extensions to [`fs::File`].
23#[stable(feature = "file_offset", since = "1.15.0")]
24pub trait FileExt {
25 /// Seeks to a given position and reads a number of bytes.
26 ///
27 /// Returns the number of bytes read.
28 ///
29 /// The offset is relative to the start of the file and thus independent
30 /// from the current cursor. The current cursor **is** affected by this
31 /// function, it is set to the end of the read.
32 ///
33 /// Reading beyond the end of the file will always return with a length of
34 /// 0\.
35 ///
36 /// Note that similar to `File::read`, it is not an error to return with a
37 /// short read. When returning from such a short read, the file pointer is
38 /// still updated.
39 ///
40 /// # Examples
41 ///
42 #[cfg_attr(windows, doc = "```no_run")]
43 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
44 /// use std::io;
45 /// use std::fs::File;
46 /// use std::os::windows::prelude::*;
47 ///
48 /// fn main() -> io::Result<()> {
49 /// let mut file = File::open("foo.txt")?;
50 /// let mut buffer = [0; 10];
51 ///
52 /// // Read 10 bytes, starting 72 bytes from the
53 /// // start of the file.
54 /// file.seek_read(&mut buffer[..], 72)?;
55 /// Ok(())
56 /// }
57 /// ```
58 #[stable(feature = "file_offset", since = "1.15.0")]
59 fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
60
61 /// Seeks to a given position and reads the exact number of bytes required to fill `buf`.
62 ///
63 /// The offset is relative to the start of the file and thus independent
64 /// from the current cursor. The current cursor **is** affected by this
65 /// function, it is set to the end of the read.
66 ///
67 /// Similar to [`io::Read::read_exact`] but uses [`seek_read`] instead of `read`.
68 ///
69 /// [`seek_read`]: FileExt::seek_read
70 ///
71 /// # Errors
72 ///
73 ///
74 /// If this function encounters an "end of file" before completely filling
75 /// the buffer, it returns an error of the kind [`io::ErrorKind::UnexpectedEof`].
76 /// The contents of `buf` are unspecified in this case.
77 ///
78 /// If any other read error is encountered then this function immediately
79 /// returns. The contents of `buf` are unspecified in this case.
80 ///
81 /// If this function returns an error, it is unspecified how many bytes it
82 /// has read, but it will never read more than would be necessary to
83 /// completely fill the buffer.
84 ///
85 /// # Examples
86 ///
87 #[cfg_attr(windows, doc = "```no_run")]
88 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
89 /// #![feature(seek_read_exact_seek_write_all)]
90 ///
91 /// use std::io;
92 /// use std::fs::File;
93 /// use std::os::windows::prelude::*;
94 ///
95 /// fn main() -> io::Result<()> {
96 /// let mut file = File::open("foo.txt")?;
97 /// let mut buffer = [0; 10];
98 ///
99 /// // Read 10 bytes, starting 72 bytes from the
100 /// // start of the file.
101 /// file.seek_read_exact(&mut buffer[..], 72)?;
102 /// Ok(())
103 /// }
104 /// ```
105 #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
106 fn seek_read_exact(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
107 while !buf.is_empty() {
108 match self.seek_read(buf, offset) {
109 Ok(0) => break,
110 Ok(n) => {
111 buf = &mut buf[n..];
112 offset += n as u64;
113 }
114 Err(e) => return Err(e),
115 }
116 }
117 if !buf.is_empty() { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
118 }
119
120 /// Seeks to a given position and reads some bytes into the buffer.
121 ///
122 /// This is equivalent to the [`seek_read`](FileExt::seek_read) method, except that it is passed
123 /// a [`BorrowedCursor`] rather than `&mut [u8]` to allow use with uninitialized buffers. The
124 /// new data will be appended to any existing contents of `buf`.
125 ///
126 /// Reading beyond the end of the file will always succeed without reading any bytes.
127 ///
128 /// # Examples
129 ///
130 #[cfg_attr(windows, doc = "```no_run")]
131 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
132 /// #![feature(core_io_borrowed_buf)]
133 /// #![feature(read_buf_at)]
134 ///
135 /// use std::io;
136 /// use std::io::BorrowedBuf;
137 /// use std::fs::File;
138 /// use std::mem::MaybeUninit;
139 /// use std::os::windows::prelude::*;
140 ///
141 /// fn main() -> io::Result<()> {
142 /// let mut file = File::open("pi.txt")?;
143 ///
144 /// // Read some bytes starting from offset 2
145 /// let mut buf: [MaybeUninit<u8>; 10] = [MaybeUninit::uninit(); 10];
146 /// let mut buf = BorrowedBuf::from(buf.as_mut_slice());
147 /// file.seek_read_buf(buf.unfilled(), 2)?;
148 ///
149 /// assert!(buf.filled().starts_with(b"1"));
150 ///
151 /// Ok(())
152 /// }
153 /// ```
154 #[unstable(feature = "read_buf_at", issue = "140771")]
155 fn seek_read_buf(&self, buf: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
156 io::default_read_buf(|b| self.seek_read(b, offset), buf)
157 }
158
159 /// Seeks to a given position and reads the exact number of bytes required to fill `buf`.
160 ///
161 /// This is equivalent to the [`seek_read_exact`](FileExt::seek_read_exact) method, except
162 /// that it is passed a [`BorrowedCursor`] rather than `&mut [u8]` to allow use with
163 /// uninitialized buffers. The new data will be appended to any existing contents of `buf`.
164 ///
165 /// Reading beyond the end of the file will always succeed without reading any bytes.
166 ///
167 /// # Examples
168 ///
169 #[cfg_attr(windows, doc = "```no_run")]
170 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
171 /// #![feature(core_io_borrowed_buf)]
172 /// #![feature(seek_read_exact_seek_write_all)]
173 ///
174 /// use std::io;
175 /// use std::io::BorrowedBuf;
176 /// use std::fs::File;
177 /// use std::mem::MaybeUninit;
178 /// use std::os::windows::prelude::*;
179 ///
180 /// fn main() -> io::Result<()> {
181 /// let mut file = File::open("pi.txt")?;
182 ///
183 /// // Read some bytes starting from offset 2
184 /// let mut buf: [MaybeUninit<u8>; 10] = [MaybeUninit::uninit(); 10];
185 /// let mut buf = BorrowedBuf::from(buf.as_mut_slice());
186 /// file.seek_read_buf_exact(buf.unfilled(), 2)?;
187 ///
188 /// assert!(buf.filled().starts_with(b"1"));
189 ///
190 /// Ok(())
191 /// }
192 /// ```
193 #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
194 fn seek_read_buf_exact(
195 &self,
196 mut buf: BorrowedCursor<'_, u8>,
197 mut offset: u64,
198 ) -> io::Result<()> {
199 while buf.capacity() > 0 {
200 let prev_written = buf.written();
201 match self.seek_read_buf(buf.reborrow(), offset) {
202 Ok(()) => {}
203 Err(e) => return Err(e),
204 }
205 let n = buf.written() - prev_written;
206 offset += n as u64;
207 if n == 0 {
208 return Err(io::Error::READ_EXACT_EOF);
209 }
210 }
211 Ok(())
212 }
213
214 /// Seeks to a given position and writes a number of bytes.
215 ///
216 /// Returns the number of bytes written.
217 ///
218 /// The offset is relative to the start of the file and thus independent
219 /// from the current cursor. The current cursor **is** affected by this
220 /// function, it is set to the end of the write.
221 ///
222 /// If the file was opened for appending (via [`OpenOptions::append`]), this is equivalent
223 /// to `write`: the `offset` is ignored, and `buf` is appended at the end of the file.
224 ///
225 /// When writing beyond the end of the file, the file is appropriately
226 /// extended and the intermediate bytes are set to zero.
227 ///
228 /// Note that similar to `File::write`, it is not an error to return a
229 /// short write. When returning from such a short write, the file pointer
230 /// is still updated.
231 ///
232 /// # Examples
233 ///
234 #[cfg_attr(windows, doc = "```no_run")]
235 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
236 /// use std::fs::File;
237 /// use std::os::windows::prelude::*;
238 ///
239 /// fn main() -> std::io::Result<()> {
240 /// let mut buffer = File::create("foo.txt")?;
241 ///
242 /// // Write a byte string starting 72 bytes from
243 /// // the start of the file.
244 /// buffer.seek_write(b"some bytes", 72)?;
245 /// Ok(())
246 /// }
247 /// ```
248 #[stable(feature = "file_offset", since = "1.15.0")]
249 fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
250
251 /// Seeks to a given position and attempts to write an entire buffer.
252 ///
253 /// The offset is relative to the start of the file and thus independent
254 /// from the current cursor. The current cursor **is** affected by this
255 /// function, it is set to the end of the write.
256 ///
257 /// This method will continuously call [`seek_write`] until there is no more data
258 /// to be written or an error of non-[`io::ErrorKind::Interrupted`] kind is
259 /// returned. This method will not return until the entire buffer has been
260 /// successfully written or such an error occurs. The first error that is
261 /// not of [`io::ErrorKind::Interrupted`] kind generated from this method will be
262 /// returned.
263 ///
264 /// # Errors
265 ///
266 /// This function will return the first error that [`seek_write`] returns.
267 ///
268 /// [`seek_write`]: FileExt::seek_write
269 ///
270 /// # Examples
271 ///
272 #[cfg_attr(windows, doc = "```no_run")]
273 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
274 /// #![feature(seek_read_exact_seek_write_all)]
275 ///
276 /// use std::fs::File;
277 /// use std::os::windows::prelude::*;
278 ///
279 /// fn main() -> std::io::Result<()> {
280 /// let mut buffer = File::create("foo.txt")?;
281 ///
282 /// // Write a byte string starting 72 bytes from
283 /// // the start of the file.
284 /// buffer.seek_write_all(b"some bytes", 72)?;
285 /// Ok(())
286 /// }
287 /// ```
288 #[unstable(feature = "seek_read_exact_seek_write_all", issue = "162868")]
289 fn seek_write_all(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
290 while !buf.is_empty() {
291 match self.seek_write(buf, offset) {
292 Ok(0) => {
293 return Err(io::Error::WRITE_ALL_EOF);
294 }
295 Ok(n) => {
296 buf = &buf[n..];
297 offset += n as u64
298 }
299 Err(e) => return Err(e),
300 }
301 }
302 Ok(())
303 }
304}
305
306#[stable(feature = "file_offset", since = "1.15.0")]
307impl FileExt for fs::File {
308 fn seek_read(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
309 self.as_inner().read_at(buf, offset)
310 }
311
312 fn seek_read_buf(&self, buf: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
313 self.as_inner().read_buf_at(buf, offset)
314 }
315
316 fn seek_write(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
317 self.as_inner().write_at(buf, offset)
318 }
319}
320
321/// Windows-specific extensions to [`fs::OpenOptions`].
322// WARNING: This trait is not sealed. DON'T add any new methods!
323// Add them to OpenOptionsExt2 instead.
324#[stable(feature = "open_options_ext", since = "1.10.0")]
325pub trait OpenOptionsExt {
326 /// Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`]
327 /// with the specified value.
328 ///
329 /// This will override the `read`, `write`, and `append` flags on the
330 /// `OpenOptions` structure. This method provides fine-grained control over
331 /// the permissions to read, write and append data, attributes (like hidden
332 /// and system), and extended attributes.
333 ///
334 /// # Examples
335 ///
336 #[cfg_attr(windows, doc = "```no_run")]
337 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
338 /// use std::fs::OpenOptions;
339 /// use std::os::windows::prelude::*;
340 ///
341 /// // Open without read and write permission, for example if you only need
342 /// // to call `stat` on the file
343 /// let file = OpenOptions::new().access_mode(0).open("foo.txt");
344 /// ```
345 ///
346 /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
347 #[stable(feature = "open_options_ext", since = "1.10.0")]
348 fn access_mode(&mut self, access: u32) -> &mut Self;
349
350 /// Overrides the `dwShareMode` argument to the call to [`CreateFile`] with
351 /// the specified value.
352 ///
353 /// By default `share_mode` is set to
354 /// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. This allows
355 /// other processes to read, write, and delete/rename the same file
356 /// while it is open. Removing any of the flags will prevent other
357 /// processes from performing the corresponding operation until the file
358 /// handle is closed.
359 ///
360 /// # Examples
361 ///
362 #[cfg_attr(windows, doc = "```no_run")]
363 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
364 /// use std::fs::OpenOptions;
365 /// use std::os::windows::prelude::*;
366 ///
367 /// // Do not allow others to read or modify this file while we have it open
368 /// // for writing.
369 /// let file = OpenOptions::new()
370 /// .write(true)
371 /// .share_mode(0)
372 /// .open("foo.txt");
373 /// ```
374 ///
375 /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
376 #[stable(feature = "open_options_ext", since = "1.10.0")]
377 fn share_mode(&mut self, val: u32) -> &mut Self;
378
379 /// Sets extra flags for the `dwFileFlags` argument to the call to
380 /// [`CreateFile2`] to the specified value (or combines it with
381 /// `attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes`
382 /// for [`CreateFile`]).
383 ///
384 /// Custom flags can only set flags, not remove flags set by Rust's options.
385 /// This option overwrites any previously set custom flags.
386 ///
387 /// # Examples
388 ///
389 #[cfg_attr(windows, doc = "```no_run")]
390 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
391 /// # #![allow(unexpected_cfgs)]
392 /// use std::fs::OpenOptions;
393 /// use std::os::windows::prelude::*;
394 ///
395 /// # pub const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x04000000;
396 ///
397 /// let file = OpenOptions::new()
398 /// .create(true)
399 /// .write(true)
400 /// .custom_flags(FILE_FLAG_DELETE_ON_CLOSE)
401 /// .open("foo.txt");
402 /// ```
403 ///
404 /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
405 /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
406 #[stable(feature = "open_options_ext", since = "1.10.0")]
407 fn custom_flags(&mut self, flags: u32) -> &mut Self;
408
409 /// Sets the `dwFileAttributes` argument to the call to [`CreateFile2`] to
410 /// the specified value (or combines it with `custom_flags` and
411 /// `security_qos_flags` to set the `dwFlagsAndAttributes` for
412 /// [`CreateFile`]).
413 ///
414 /// If a _new_ file is created because it does not yet exist and
415 /// `.create(true)` or `.create_new(true)` are specified, the new file is
416 /// given the attributes declared with `.attributes()`.
417 ///
418 /// If an _existing_ file is opened with `.create(true).truncate(true)`, its
419 /// existing attributes are preserved and combined with the ones declared
420 /// with `.attributes()`.
421 ///
422 /// In all other cases the attributes get ignored.
423 ///
424 /// # Examples
425 ///
426 #[cfg_attr(windows, doc = "```no_run")]
427 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
428 /// # #![allow(unexpected_cfgs)]
429 /// use std::fs::OpenOptions;
430 /// use std::os::windows::prelude::*;
431 ///
432 /// # pub const FILE_ATTRIBUTE_HIDDEN: u32 = 2;
433 ///
434 /// let file = OpenOptions::new()
435 /// .write(true)
436 /// .create(true)
437 /// .attributes(FILE_ATTRIBUTE_HIDDEN)
438 /// .open("foo.txt");
439 /// ```
440 ///
441 /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
442 /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
443 #[stable(feature = "open_options_ext", since = "1.10.0")]
444 fn attributes(&mut self, val: u32) -> &mut Self;
445
446 /// Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`] to
447 /// the specified value (or combines it with `custom_flags` and `attributes`
448 /// to set the `dwFlagsAndAttributes` for [`CreateFile`]).
449 ///
450 /// By default `security_qos_flags` is not set. It should be specified when
451 /// opening a named pipe, to control to which degree a server process can
452 /// act on behalf of a client process (security impersonation level).
453 ///
454 /// When `security_qos_flags` is not set, a malicious program can gain the
455 /// elevated privileges of a privileged Rust process when it allows opening
456 /// user-specified paths, by tricking it into opening a named pipe. So
457 /// arguably `security_qos_flags` should also be set when opening arbitrary
458 /// paths. However the bits can then conflict with other flags, specifically
459 /// `FILE_FLAG_OPEN_NO_RECALL`.
460 ///
461 /// For information about possible values, see [Impersonation Levels] on the
462 /// Windows Dev Center site. The `SECURITY_SQOS_PRESENT` flag is set
463 /// automatically when using this method.
464 ///
465 /// # Examples
466 ///
467 #[cfg_attr(windows, doc = "```no_run")]
468 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
469 /// # #![allow(unexpected_cfgs)]
470 /// use std::fs::OpenOptions;
471 /// use std::os::windows::prelude::*;
472 ///
473 /// # pub const SECURITY_IDENTIFICATION: u32 = 0;
474 ///
475 /// let file = OpenOptions::new()
476 /// .write(true)
477 /// .create(true)
478 /// .security_qos_flags(SECURITY_IDENTIFICATION)
479 /// .open(r"\\.\pipe\MyPipe");
480 /// ```
481 ///
482 /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
483 /// [`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
484 /// [Impersonation Levels]:
485 /// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level
486 #[stable(feature = "open_options_ext", since = "1.10.0")]
487 fn security_qos_flags(&mut self, flags: u32) -> &mut Self;
488}
489
490#[stable(feature = "open_options_ext", since = "1.10.0")]
491impl OpenOptionsExt for OpenOptions {
492 #[rustdoc_skip_body]
493 fn access_mode(&mut self, access: u32) -> &mut OpenOptions {
494 self.as_inner_mut().access_mode(access);
495 self
496 }
497
498 #[rustdoc_skip_body]
499 fn share_mode(&mut self, share: u32) -> &mut OpenOptions {
500 self.as_inner_mut().share_mode(share);
501 self
502 }
503
504 #[rustdoc_skip_body]
505 fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions {
506 self.as_inner_mut().custom_flags(flags);
507 self
508 }
509
510 #[rustdoc_skip_body]
511 fn attributes(&mut self, attributes: u32) -> &mut OpenOptions {
512 self.as_inner_mut().attributes(attributes);
513 self
514 }
515
516 #[rustdoc_skip_body]
517 fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions {
518 self.as_inner_mut().security_qos_flags(flags);
519 self
520 }
521}
522
523#[unstable(feature = "windows_freeze_file_times", issue = "149715")]
524pub impl(self) trait OpenOptionsExt2 {
525 /// If set to `true`, prevent the "last access time" of the file from being changed.
526 ///
527 /// Default to `false`.
528 #[unstable(feature = "windows_freeze_file_times", issue = "149715")]
529 fn freeze_last_access_time(&mut self, freeze: bool) -> &mut Self;
530
531 /// If set to `true`, prevent the "last write time" of the file from being changed.
532 ///
533 /// Default to `false`.
534 #[unstable(feature = "windows_freeze_file_times", issue = "149715")]
535 fn freeze_last_write_time(&mut self, freeze: bool) -> &mut Self;
536}
537
538#[unstable(feature = "windows_freeze_file_times", issue = "149715")]
539impl OpenOptionsExt2 for OpenOptions {
540 #[rustdoc_skip_body]
541 fn freeze_last_access_time(&mut self, freeze: bool) -> &mut Self {
542 self.as_inner_mut().freeze_last_access_time(freeze);
543 self
544 }
545
546 #[rustdoc_skip_body]
547 fn freeze_last_write_time(&mut self, freeze: bool) -> &mut Self {
548 self.as_inner_mut().freeze_last_write_time(freeze);
549 self
550 }
551}
552
553/// Windows-specific extensions to [`fs::Permissions`]. This extension trait
554/// provides extra utilities to shows what Windows file attributes are enabled
555/// in [`Permissions`] and to manually set file attributes on [`Permissions`].
556///
557/// See Microsoft's [`File Attribute Constants`] page to know what file
558/// attribute metadata are defined and stored on Windows files.
559///
560/// [`Permissions`]: fs::Permissions
561/// [`File Attribute Constants`]:
562/// https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
563///
564/// # Example
565///
566#[cfg_attr(windows, doc = "```no_run")]
567#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
568/// #![feature(windows_permissions_ext)]
569/// use std::fs::Permissions;
570/// use std::os::windows::fs::PermissionsExt;
571///
572/// const FILE_ATTRIBUTE_SYSTEM: u32 = 0x4;
573/// const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x20;
574/// let my_file_attr = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE;
575/// let mut permissions = Permissions::from_file_attributes(my_file_attr);
576/// assert_eq!(permissions.file_attributes(), my_file_attr);
577///
578/// const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
579/// let new_file_attr = permissions.file_attributes() | FILE_ATTRIBUTE_HIDDEN;
580/// permissions.set_file_attributes(new_file_attr);
581/// assert_eq!(permissions.file_attributes(), new_file_attr);
582/// ```
583#[unstable(feature = "windows_permissions_ext", issue = "152956")]
584pub impl(self) trait PermissionsExt {
585 /// Returns the file attribute bits.
586 #[unstable(feature = "windows_permissions_ext", issue = "152956")]
587 fn file_attributes(&self) -> u32;
588
589 /// Sets the file attribute bits.
590 #[unstable(feature = "windows_permissions_ext", issue = "152956")]
591 fn set_file_attributes(&mut self, mask: u32);
592
593 /// Creates a new instance from the given file attribute bits.
594 #[unstable(feature = "windows_permissions_ext", issue = "152956")]
595 fn from_file_attributes(mask: u32) -> Self;
596}
597
598#[unstable(feature = "windows_permissions_ext", issue = "152956")]
599impl PermissionsExt for fs::Permissions {
600 #[rustdoc_skip_body]
601 fn file_attributes(&self) -> u32 {
602 self.as_inner().file_attributes()
603 }
604
605 fn set_file_attributes(&mut self, mask: u32) {
606 *self = Permissions::from_inner(FromInner::from_inner(mask));
607 }
608
609 fn from_file_attributes(mask: u32) -> Self {
610 Permissions::from_inner(FromInner::from_inner(mask))
611 }
612}
613
614/// Windows-specific extensions to [`fs::Metadata`].
615///
616/// The data members that this trait exposes correspond to the members
617/// of the [`BY_HANDLE_FILE_INFORMATION`] structure.
618///
619/// [`BY_HANDLE_FILE_INFORMATION`]:
620/// https://docs.microsoft.com/windows/win32/api/fileapi/ns-fileapi-by_handle_file_information
621#[stable(feature = "metadata_ext", since = "1.1.0")]
622pub trait MetadataExt {
623 /// Returns the value of the `dwFileAttributes` field of this metadata.
624 ///
625 /// This field contains the file system attribute information for a file
626 /// or directory. For possible values and their descriptions, see
627 /// [File Attribute Constants] in the Windows Dev Center.
628 ///
629 /// # Examples
630 ///
631 #[cfg_attr(windows, doc = "```no_run")]
632 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
633 /// use std::io;
634 /// use std::fs;
635 /// use std::os::windows::prelude::*;
636 ///
637 /// fn main() -> io::Result<()> {
638 /// let metadata = fs::metadata("foo.txt")?;
639 /// let attributes = metadata.file_attributes();
640 /// Ok(())
641 /// }
642 /// ```
643 ///
644 /// [File Attribute Constants]:
645 /// https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
646 #[stable(feature = "metadata_ext", since = "1.1.0")]
647 fn file_attributes(&self) -> u32;
648
649 /// Returns the value of the `ftCreationTime` field of this metadata.
650 ///
651 /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
652 /// which represents the number of 100-nanosecond intervals since
653 /// January 1, 1601 (UTC). The struct is automatically
654 /// converted to a `u64` value, as that is the recommended way
655 /// to use it.
656 ///
657 /// If the underlying filesystem does not support creation time, the
658 /// returned value is 0.
659 ///
660 /// # Examples
661 ///
662 #[cfg_attr(windows, doc = "```no_run")]
663 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
664 /// use std::io;
665 /// use std::fs;
666 /// use std::os::windows::prelude::*;
667 ///
668 /// fn main() -> io::Result<()> {
669 /// let metadata = fs::metadata("foo.txt")?;
670 /// let creation_time = metadata.creation_time();
671 /// Ok(())
672 /// }
673 /// ```
674 ///
675 /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
676 #[stable(feature = "metadata_ext", since = "1.1.0")]
677 fn creation_time(&self) -> u64;
678
679 /// Returns the value of the `ftLastAccessTime` field of this metadata.
680 ///
681 /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
682 /// which represents the number of 100-nanosecond intervals since
683 /// January 1, 1601 (UTC). The struct is automatically
684 /// converted to a `u64` value, as that is the recommended way
685 /// to use it.
686 ///
687 /// For a file, the value specifies the last time that a file was read
688 /// from or written to. For a directory, the value specifies when
689 /// the directory was created. For both files and directories, the
690 /// specified date is correct, but the time of day is always set to
691 /// midnight.
692 ///
693 /// If the underlying filesystem does not support last access time, the
694 /// returned value is 0.
695 ///
696 /// # Examples
697 ///
698 #[cfg_attr(windows, doc = "```no_run")]
699 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
700 /// use std::io;
701 /// use std::fs;
702 /// use std::os::windows::prelude::*;
703 ///
704 /// fn main() -> io::Result<()> {
705 /// let metadata = fs::metadata("foo.txt")?;
706 /// let last_access_time = metadata.last_access_time();
707 /// Ok(())
708 /// }
709 /// ```
710 ///
711 /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
712 #[stable(feature = "metadata_ext", since = "1.1.0")]
713 fn last_access_time(&self) -> u64;
714
715 /// Returns the value of the `ftLastWriteTime` field of this metadata.
716 ///
717 /// The returned 64-bit value is equivalent to a [`FILETIME`] struct,
718 /// which represents the number of 100-nanosecond intervals since
719 /// January 1, 1601 (UTC). The struct is automatically
720 /// converted to a `u64` value, as that is the recommended way
721 /// to use it.
722 ///
723 /// For a file, the value specifies the last time that a file was written
724 /// to. For a directory, the structure specifies when the directory was
725 /// created.
726 ///
727 /// If the underlying filesystem does not support the last write time,
728 /// the returned value is 0.
729 ///
730 /// # Examples
731 ///
732 #[cfg_attr(windows, doc = "```no_run")]
733 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
734 /// use std::io;
735 /// use std::fs;
736 /// use std::os::windows::prelude::*;
737 ///
738 /// fn main() -> io::Result<()> {
739 /// let metadata = fs::metadata("foo.txt")?;
740 /// let last_write_time = metadata.last_write_time();
741 /// Ok(())
742 /// }
743 /// ```
744 ///
745 /// [`FILETIME`]: https://docs.microsoft.com/windows/win32/api/minwinbase/ns-minwinbase-filetime
746 #[stable(feature = "metadata_ext", since = "1.1.0")]
747 fn last_write_time(&self) -> u64;
748
749 /// Returns the value of the `nFileSize` fields of this
750 /// metadata.
751 ///
752 /// The returned value does not have meaning for directories.
753 ///
754 /// # Examples
755 ///
756 #[cfg_attr(windows, doc = "```no_run")]
757 #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
758 /// use std::io;
759 /// use std::fs;
760 /// use std::os::windows::prelude::*;
761 ///
762 /// fn main() -> io::Result<()> {
763 /// let metadata = fs::metadata("foo.txt")?;
764 /// let file_size = metadata.file_size();
765 /// Ok(())
766 /// }
767 /// ```
768 #[stable(feature = "metadata_ext", since = "1.1.0")]
769 fn file_size(&self) -> u64;
770
771 /// Returns the value of the `dwVolumeSerialNumber` field of this
772 /// metadata.
773 ///
774 /// This will return `None` if the `Metadata` instance was created from a
775 /// call to `DirEntry::metadata`. If this `Metadata` was created by using
776 /// `fs::metadata` or `File::metadata`, then this will return `Some`.
777 #[unstable(feature = "windows_by_handle", issue = "63010")]
778 fn volume_serial_number(&self) -> Option<u32>;
779
780 /// Returns the value of the `nNumberOfLinks` field of this
781 /// metadata.
782 ///
783 /// This will return `None` if the `Metadata` instance was created from a
784 /// call to `DirEntry::metadata`. If this `Metadata` was created by using
785 /// `fs::metadata` or `File::metadata`, then this will return `Some`.
786 #[unstable(feature = "windows_by_handle", issue = "63010")]
787 fn number_of_links(&self) -> Option<u32>;
788
789 /// Returns the value of the `nFileIndex` fields of this
790 /// metadata.
791 ///
792 /// This will return `None` if the `Metadata` instance was created from a
793 /// call to `DirEntry::metadata`. If this `Metadata` was created by using
794 /// `fs::metadata` or `File::metadata`, then this will return `Some`.
795 #[unstable(feature = "windows_by_handle", issue = "63010")]
796 fn file_index(&self) -> Option<u64>;
797
798 /// Returns the value of the `ChangeTime` fields of this metadata.
799 ///
800 /// `ChangeTime` is the last time file metadata was changed, such as
801 /// renames, attributes, etc.
802 ///
803 /// This will return `None` if `Metadata` instance was created from a call to
804 /// `DirEntry::metadata` or if the `target_vendor` is outside the current platform
805 /// support for this api.
806 #[unstable(feature = "windows_change_time", issue = "121478")]
807 fn change_time(&self) -> Option<u64>;
808}
809
810#[stable(feature = "metadata_ext", since = "1.1.0")]
811impl MetadataExt for Metadata {
812 #[rustdoc_skip_body]
813 fn file_attributes(&self) -> u32 {
814 self.as_inner().attrs()
815 }
816 #[rustdoc_skip_body]
817 fn creation_time(&self) -> u64 {
818 self.as_inner().created_u64()
819 }
820 #[rustdoc_skip_body]
821 fn last_access_time(&self) -> u64 {
822 self.as_inner().accessed_u64()
823 }
824 #[rustdoc_skip_body]
825 fn last_write_time(&self) -> u64 {
826 self.as_inner().modified_u64()
827 }
828 #[rustdoc_skip_body]
829 fn file_size(&self) -> u64 {
830 self.as_inner().size()
831 }
832 #[rustdoc_skip_body]
833 fn volume_serial_number(&self) -> Option<u32> {
834 self.as_inner().volume_serial_number()
835 }
836 #[rustdoc_skip_body]
837 fn number_of_links(&self) -> Option<u32> {
838 self.as_inner().number_of_links()
839 }
840 #[rustdoc_skip_body]
841 fn file_index(&self) -> Option<u64> {
842 self.as_inner().file_index()
843 }
844 #[rustdoc_skip_body]
845 fn change_time(&self) -> Option<u64> {
846 self.as_inner().changed_u64()
847 }
848}
849
850/// Windows-specific extensions to [`fs::FileType`].
851///
852/// On Windows, a symbolic link knows whether it is a file or directory.
853#[stable(feature = "windows_file_type_ext", since = "1.64.0")]
854pub impl(self) trait FileTypeExt {
855 /// Returns `true` if this file type is a symbolic link that is also a directory.
856 #[stable(feature = "windows_file_type_ext", since = "1.64.0")]
857 fn is_symlink_dir(&self) -> bool;
858 /// Returns `true` if this file type is a symbolic link that is also a file.
859 #[stable(feature = "windows_file_type_ext", since = "1.64.0")]
860 fn is_symlink_file(&self) -> bool;
861}
862
863#[stable(feature = "windows_file_type_ext", since = "1.64.0")]
864impl FileTypeExt for fs::FileType {
865 #[rustdoc_skip_body]
866 fn is_symlink_dir(&self) -> bool {
867 self.as_inner().is_symlink_dir()
868 }
869 #[rustdoc_skip_body]
870 fn is_symlink_file(&self) -> bool {
871 self.as_inner().is_symlink_file()
872 }
873}
874
875/// Windows-specific extensions to [`fs::FileTimes`].
876#[stable(feature = "file_set_times", since = "1.75.0")]
877pub impl(self) trait FileTimesExt {
878 /// Set the creation time of a file.
879 #[stable(feature = "file_set_times", since = "1.75.0")]
880 fn set_created(self, t: SystemTime) -> Self;
881}
882
883#[stable(feature = "file_set_times", since = "1.75.0")]
884impl FileTimesExt for fs::FileTimes {
885 #[rustdoc_skip_body]
886 fn set_created(mut self, t: SystemTime) -> Self {
887 self.as_inner_mut().set_created(t.into_inner());
888 self
889 }
890}
891
892/// Creates a new symlink to a non-directory file on the filesystem.
893///
894/// The `link` path will be a file symbolic link pointing to the `original`
895/// path.
896///
897/// The `original` path should not be a directory or a symlink to a directory,
898/// otherwise the symlink will be broken. Use [`symlink_dir`] for directories.
899///
900/// This function currently corresponds to [`CreateSymbolicLinkW`][CreateSymbolicLinkW].
901/// Note that this [may change in the future][changes].
902///
903/// [CreateSymbolicLinkW]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinkw
904/// [changes]: io#platform-specific-behavior
905///
906/// # Examples
907///
908#[cfg_attr(windows, doc = "```no_run")]
909#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
910/// use std::os::windows::fs;
911///
912/// fn main() -> std::io::Result<()> {
913/// fs::symlink_file("a.txt", "b.txt")?;
914/// Ok(())
915/// }
916/// ```
917///
918/// # Limitations
919///
920/// Windows treats symlink creation as a [privileged action][symlink-security],
921/// therefore this function is likely to fail unless the user makes changes to
922/// their system to permit symlink creation. Users can try enabling Developer
923/// Mode, granting the `SeCreateSymbolicLinkPrivilege` privilege, or running
924/// the process as an administrator.
925///
926/// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links
927#[doc(alias = "CreateSymbolicLink", alias = "CreateSymbolicLinkW")]
928#[stable(feature = "symlink", since = "1.1.0")]
929#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_file")]
930#[rustdoc_skip_body]
931pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
932 sys::fs::symlink_inner(original.as_ref(), link.as_ref(), false)
933}
934
935/// Creates a new symlink to a directory on the filesystem.
936///
937/// The `link` path will be a directory symbolic link pointing to the `original`
938/// path.
939///
940/// The `original` path must be a directory or a symlink to a directory,
941/// otherwise the symlink will be broken. Use [`symlink_file`] for other files.
942///
943/// This function currently corresponds to [`CreateSymbolicLinkW`][CreateSymbolicLinkW].
944/// Note that this [may change in the future][changes].
945///
946/// [CreateSymbolicLinkW]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsymboliclinkw
947/// [changes]: io#platform-specific-behavior
948///
949/// # Examples
950///
951#[cfg_attr(windows, doc = "```no_run")]
952#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
953/// use std::os::windows::fs;
954///
955/// fn main() -> std::io::Result<()> {
956/// fs::symlink_dir("a", "b")?;
957/// Ok(())
958/// }
959/// ```
960///
961/// # Limitations
962///
963/// Windows treats symlink creation as a [privileged action][symlink-security],
964/// therefore this function is likely to fail unless the user makes changes to
965/// their system to permit symlink creation. Users can try enabling Developer
966/// Mode, granting the `SeCreateSymbolicLinkPrivilege` privilege, or running
967/// the process as an administrator.
968///
969/// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links
970#[doc(alias = "CreateSymbolicLink", alias = "CreateSymbolicLinkW")]
971#[stable(feature = "symlink", since = "1.1.0")]
972#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_dir")]
973#[rustdoc_skip_body]
974pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
975 sys::fs::symlink_inner(original.as_ref(), link.as_ref(), true)
976}
977
978/// Creates a junction point.
979///
980/// The `link` path will be a directory junction pointing to the original path.
981/// If `link` is a relative path then it will be made absolute prior to creating the junction point.
982/// The `original` path must be a directory or a link to a directory, otherwise the junction point will be broken.
983///
984/// If either path is not a local file path then this will fail.
985#[unstable(feature = "junction_point", issue = "121709")]
986#[rustdoc_skip_body]
987pub fn junction_point<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
988 sys::fs::junction_point(original.as_ref(), link.as_ref())
989}