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