1 //! Unix-specific extensions to primitives in the `std::fs` module.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 use crate::fs::{self, OpenOptions, Permissions};
9 use crate::sys::platform::fs::MetadataExt as UnixMetadataExt;
10 use crate::sys_common::{AsInner, AsInnerMut, FromInner};
12 /// Unix-specific extensions to [`File`].
14 /// [`File`]: ../../../../std/fs/struct.File.html
15 #[stable(feature = "file_offset", since = "1.15.0")]
17 /// Reads a number of bytes starting from a given offset.
19 /// Returns the number of bytes read.
21 /// The offset is relative to the start of the file and thus independent
22 /// from the current cursor.
24 /// The current file cursor is not affected by this function.
26 /// Note that similar to [`File::read`], it is not an error to return with a
29 /// [`File::read`]: ../../../../std/fs/struct.File.html#method.read
35 /// use std::fs::File;
36 /// use std::os::unix::prelude::FileExt;
38 /// fn main() -> io::Result<()> {
39 /// let mut buf = [0u8; 8];
40 /// let file = File::open("foo.txt")?;
42 /// // We now read 8 bytes from the offset 10.
43 /// let num_bytes_read = file.read_at(&mut buf, 10)?;
44 /// println!("read {} bytes: {:?}", num_bytes_read, buf);
48 #[stable(feature = "file_offset", since = "1.15.0")]
49 fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
51 /// Reads the exact number of byte required to fill `buf` from the given offset.
53 /// The offset is relative to the start of the file and thus independent
54 /// from the current cursor.
56 /// The current file cursor is not affected by this function.
58 /// Similar to [`Read::read_exact`] but uses [`read_at`] instead of `read`.
60 /// [`Read::read_exact`]: ../../../../std/io/trait.Read.html#method.read_exact
61 /// [`read_at`]: #tymethod.read_at
65 /// If this function encounters an error of the kind
66 /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
69 /// If this function encounters an "end of file" before completely filling
70 /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
71 /// The contents of `buf` are unspecified in this case.
73 /// If any other read error is encountered then this function immediately
74 /// returns. The contents of `buf` are unspecified in this case.
76 /// If this function returns an error, it is unspecified how many bytes it
77 /// has read, but it will never read more than would be necessary to
78 /// completely fill the buffer.
80 /// [`ErrorKind::Interrupted`]: ../../../../std/io/enum.ErrorKind.html#variant.Interrupted
81 /// [`ErrorKind::UnexpectedEof`]: ../../../../std/io/enum.ErrorKind.html#variant.UnexpectedEof
87 /// use std::fs::File;
88 /// use std::os::unix::prelude::FileExt;
90 /// fn main() -> io::Result<()> {
91 /// let mut buf = [0u8; 8];
92 /// let file = File::open("foo.txt")?;
94 /// // We now read exactly 8 bytes from the offset 10.
95 /// file.read_exact_at(&mut buf, 10)?;
96 /// println!("read {} bytes: {:?}", buf.len(), buf);
100 #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
101 fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
102 while !buf.is_empty() {
103 match self.read_at(buf, offset) {
110 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
111 Err(e) => return Err(e),
115 Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
121 /// Writes a number of bytes starting from a given offset.
123 /// Returns the number of bytes written.
125 /// The offset is relative to the start of the file and thus independent
126 /// from the current cursor.
128 /// The current file cursor is not affected by this function.
130 /// When writing beyond the end of the file, the file is appropriately
131 /// extended and the intermediate bytes are initialized with the value 0.
133 /// Note that similar to [`File::write`], it is not an error to return a
136 /// [`File::write`]: ../../../../std/fs/struct.File.html#write.v
141 /// use std::fs::File;
143 /// use std::os::unix::prelude::FileExt;
145 /// fn main() -> io::Result<()> {
146 /// let file = File::open("foo.txt")?;
148 /// // We now write at the offset 10.
149 /// file.write_at(b"sushi", 10)?;
153 #[stable(feature = "file_offset", since = "1.15.0")]
154 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
156 /// Attempts to write an entire buffer starting from a given offset.
158 /// The offset is relative to the start of the file and thus independent
159 /// from the current cursor.
161 /// The current file cursor is not affected by this function.
163 /// This method will continuously call [`write_at`] until there is no more data
164 /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
165 /// returned. This method will not return until the entire buffer has been
166 /// successfully written or such an error occurs. The first error that is
167 /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
172 /// This function will return the first error of
173 /// non-[`ErrorKind::Interrupted`] kind that [`write_at`] returns.
175 /// [`ErrorKind::Interrupted`]: ../../../../std/io/enum.ErrorKind.html#variant.Interrupted
176 /// [`write_at`]: #tymethod.write_at
181 /// use std::fs::File;
183 /// use std::os::unix::prelude::FileExt;
185 /// fn main() -> io::Result<()> {
186 /// let file = File::open("foo.txt")?;
188 /// // We now write at the offset 10.
189 /// file.write_all_at(b"sushi", 10)?;
193 #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
194 fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
195 while !buf.is_empty() {
196 match self.write_at(buf, offset) {
198 return Err(io::Error::new(
199 io::ErrorKind::WriteZero,
200 "failed to write whole buffer",
207 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
208 Err(e) => return Err(e),
215 #[stable(feature = "file_offset", since = "1.15.0")]
216 impl FileExt for fs::File {
217 fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
218 self.as_inner().read_at(buf, offset)
220 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
221 self.as_inner().write_at(buf, offset)
225 /// Unix-specific extensions to [`fs::Permissions`].
227 /// [`fs::Permissions`]: ../../../../std/fs/struct.Permissions.html
228 #[stable(feature = "fs_ext", since = "1.1.0")]
229 pub trait PermissionsExt {
230 /// Returns the underlying raw `st_mode` bits that contain the standard
231 /// Unix permissions for this file.
236 /// use std::fs::File;
237 /// use std::os::unix::fs::PermissionsExt;
239 /// fn main() -> std::io::Result<()> {
240 /// let f = File::create("foo.txt")?;
241 /// let metadata = f.metadata()?;
242 /// let permissions = metadata.permissions();
244 /// println!("permissions: {:o}", permissions.mode());
248 #[stable(feature = "fs_ext", since = "1.1.0")]
249 fn mode(&self) -> u32;
251 /// Sets the underlying raw bits for this set of permissions.
256 /// use std::fs::File;
257 /// use std::os::unix::fs::PermissionsExt;
259 /// fn main() -> std::io::Result<()> {
260 /// let f = File::create("foo.txt")?;
261 /// let metadata = f.metadata()?;
262 /// let mut permissions = metadata.permissions();
264 /// permissions.set_mode(0o644); // Read/write for owner and read for others.
265 /// assert_eq!(permissions.mode(), 0o644);
269 #[stable(feature = "fs_ext", since = "1.1.0")]
270 fn set_mode(&mut self, mode: u32);
272 /// Creates a new instance of `Permissions` from the given set of Unix
278 /// use std::fs::Permissions;
279 /// use std::os::unix::fs::PermissionsExt;
281 /// // Read/write for owner and read for others.
282 /// let permissions = Permissions::from_mode(0o644);
283 /// assert_eq!(permissions.mode(), 0o644);
285 #[stable(feature = "fs_ext", since = "1.1.0")]
286 fn from_mode(mode: u32) -> Self;
289 #[stable(feature = "fs_ext", since = "1.1.0")]
290 impl PermissionsExt for Permissions {
291 fn mode(&self) -> u32 {
292 self.as_inner().mode()
295 fn set_mode(&mut self, mode: u32) {
296 *self = Permissions::from_inner(FromInner::from_inner(mode));
299 fn from_mode(mode: u32) -> Permissions {
300 Permissions::from_inner(FromInner::from_inner(mode))
304 /// Unix-specific extensions to [`fs::OpenOptions`].
306 /// [`fs::OpenOptions`]: ../../../../std/fs/struct.OpenOptions.html
307 #[stable(feature = "fs_ext", since = "1.1.0")]
308 pub trait OpenOptionsExt {
309 /// Sets the mode bits that a new file will be created with.
311 /// If a new file is created as part of an `OpenOptions::open` call then this
312 /// specified `mode` will be used as the permission bits for the new file.
313 /// If no `mode` is set, the default of `0o666` will be used.
314 /// The operating system masks out bits with the system's `umask`, to produce
315 /// the final permissions.
320 /// use std::fs::OpenOptions;
321 /// use std::os::unix::fs::OpenOptionsExt;
324 /// let mut options = OpenOptions::new();
325 /// options.mode(0o644); // Give read/write for owner and read for others.
326 /// let file = options.open("foo.txt");
329 #[stable(feature = "fs_ext", since = "1.1.0")]
330 fn mode(&mut self, mode: u32) -> &mut Self;
332 /// Pass custom flags to the `flags` argument of `open`.
334 /// The bits that define the access mode are masked out with `O_ACCMODE`, to
335 /// ensure they do not interfere with the access mode set by Rusts options.
337 /// Custom flags can only set flags, not remove flags set by Rusts options.
338 /// This options overwrites any previously set custom flags.
343 /// # #![feature(rustc_private)]
344 /// extern crate libc;
345 /// use std::fs::OpenOptions;
346 /// use std::os::unix::fs::OpenOptionsExt;
349 /// let mut options = OpenOptions::new();
350 /// options.write(true);
352 /// options.custom_flags(libc::O_NOFOLLOW);
354 /// let file = options.open("foo.txt");
357 #[stable(feature = "open_options_ext", since = "1.10.0")]
358 fn custom_flags(&mut self, flags: i32) -> &mut Self;
361 #[stable(feature = "fs_ext", since = "1.1.0")]
362 impl OpenOptionsExt for OpenOptions {
363 fn mode(&mut self, mode: u32) -> &mut OpenOptions {
364 self.as_inner_mut().mode(mode);
368 fn custom_flags(&mut self, flags: i32) -> &mut OpenOptions {
369 self.as_inner_mut().custom_flags(flags);
374 /// Unix-specific extensions to [`fs::Metadata`].
376 /// [`fs::Metadata`]: ../../../../std/fs/struct.Metadata.html
377 #[stable(feature = "metadata_ext", since = "1.1.0")]
378 pub trait MetadataExt {
379 /// Returns the ID of the device containing the file.
386 /// use std::os::unix::fs::MetadataExt;
388 /// fn main() -> io::Result<()> {
389 /// let meta = fs::metadata("some_file")?;
390 /// let dev_id = meta.dev();
394 #[stable(feature = "metadata_ext", since = "1.1.0")]
395 fn dev(&self) -> u64;
396 /// Returns the inode number.
402 /// use std::os::unix::fs::MetadataExt;
405 /// fn main() -> io::Result<()> {
406 /// let meta = fs::metadata("some_file")?;
407 /// let inode = meta.ino();
411 #[stable(feature = "metadata_ext", since = "1.1.0")]
412 fn ino(&self) -> u64;
413 /// Returns the rights applied to this file.
419 /// use std::os::unix::fs::MetadataExt;
422 /// fn main() -> io::Result<()> {
423 /// let meta = fs::metadata("some_file")?;
424 /// let mode = meta.mode();
425 /// let user_has_write_access = mode & 0o200;
426 /// let user_has_read_write_access = mode & 0o600;
427 /// let group_has_read_access = mode & 0o040;
428 /// let others_have_exec_access = mode & 0o001;
432 #[stable(feature = "metadata_ext", since = "1.1.0")]
433 fn mode(&self) -> u32;
434 /// Returns the number of hard links pointing to this file.
440 /// use std::os::unix::fs::MetadataExt;
443 /// fn main() -> io::Result<()> {
444 /// let meta = fs::metadata("some_file")?;
445 /// let nb_hard_links = meta.nlink();
449 #[stable(feature = "metadata_ext", since = "1.1.0")]
450 fn nlink(&self) -> u64;
451 /// Returns the user ID of the owner of this file.
457 /// use std::os::unix::fs::MetadataExt;
460 /// fn main() -> io::Result<()> {
461 /// let meta = fs::metadata("some_file")?;
462 /// let user_id = meta.uid();
466 #[stable(feature = "metadata_ext", since = "1.1.0")]
467 fn uid(&self) -> u32;
468 /// Returns the group ID of the owner of this file.
474 /// use std::os::unix::fs::MetadataExt;
477 /// fn main() -> io::Result<()> {
478 /// let meta = fs::metadata("some_file")?;
479 /// let group_id = meta.gid();
483 #[stable(feature = "metadata_ext", since = "1.1.0")]
484 fn gid(&self) -> u32;
485 /// Returns the device ID of this file (if it is a special one).
491 /// use std::os::unix::fs::MetadataExt;
494 /// fn main() -> io::Result<()> {
495 /// let meta = fs::metadata("some_file")?;
496 /// let device_id = meta.rdev();
500 #[stable(feature = "metadata_ext", since = "1.1.0")]
501 fn rdev(&self) -> u64;
502 /// Returns the total size of this file in bytes.
508 /// use std::os::unix::fs::MetadataExt;
511 /// fn main() -> io::Result<()> {
512 /// let meta = fs::metadata("some_file")?;
513 /// let file_size = meta.size();
517 #[stable(feature = "metadata_ext", since = "1.1.0")]
518 fn size(&self) -> u64;
519 /// Returns the last access time of the file, in seconds since Unix Epoch.
525 /// use std::os::unix::fs::MetadataExt;
528 /// fn main() -> io::Result<()> {
529 /// let meta = fs::metadata("some_file")?;
530 /// let last_access_time = meta.atime();
534 #[stable(feature = "metadata_ext", since = "1.1.0")]
535 fn atime(&self) -> i64;
536 /// Returns the last access time of the file, in nanoseconds since [`atime`].
538 /// [`atime`]: #tymethod.atime
544 /// use std::os::unix::fs::MetadataExt;
547 /// fn main() -> io::Result<()> {
548 /// let meta = fs::metadata("some_file")?;
549 /// let nano_last_access_time = meta.atime_nsec();
553 #[stable(feature = "metadata_ext", since = "1.1.0")]
554 fn atime_nsec(&self) -> i64;
555 /// Returns the last modification time of the file, in seconds since Unix Epoch.
561 /// use std::os::unix::fs::MetadataExt;
564 /// fn main() -> io::Result<()> {
565 /// let meta = fs::metadata("some_file")?;
566 /// let last_modification_time = meta.mtime();
570 #[stable(feature = "metadata_ext", since = "1.1.0")]
571 fn mtime(&self) -> i64;
572 /// Returns the last modification time of the file, in nanoseconds since [`mtime`].
574 /// [`mtime`]: #tymethod.mtime
580 /// use std::os::unix::fs::MetadataExt;
583 /// fn main() -> io::Result<()> {
584 /// let meta = fs::metadata("some_file")?;
585 /// let nano_last_modification_time = meta.mtime_nsec();
589 #[stable(feature = "metadata_ext", since = "1.1.0")]
590 fn mtime_nsec(&self) -> i64;
591 /// Returns the last status change time of the file, in seconds since Unix Epoch.
597 /// use std::os::unix::fs::MetadataExt;
600 /// fn main() -> io::Result<()> {
601 /// let meta = fs::metadata("some_file")?;
602 /// let last_status_change_time = meta.ctime();
606 #[stable(feature = "metadata_ext", since = "1.1.0")]
607 fn ctime(&self) -> i64;
608 /// Returns the last status change time of the file, in nanoseconds since [`ctime`].
610 /// [`ctime`]: #tymethod.ctime
616 /// use std::os::unix::fs::MetadataExt;
619 /// fn main() -> io::Result<()> {
620 /// let meta = fs::metadata("some_file")?;
621 /// let nano_last_status_change_time = meta.ctime_nsec();
625 #[stable(feature = "metadata_ext", since = "1.1.0")]
626 fn ctime_nsec(&self) -> i64;
627 /// Returns the blocksize for filesystem I/O.
633 /// use std::os::unix::fs::MetadataExt;
636 /// fn main() -> io::Result<()> {
637 /// let meta = fs::metadata("some_file")?;
638 /// let blocksize = meta.blksize();
642 #[stable(feature = "metadata_ext", since = "1.1.0")]
643 fn blksize(&self) -> u64;
644 /// Returns the number of blocks allocated to the file, in 512-byte units.
646 /// Please note that this may be smaller than `st_size / 512` when the file has holes.
652 /// use std::os::unix::fs::MetadataExt;
655 /// fn main() -> io::Result<()> {
656 /// let meta = fs::metadata("some_file")?;
657 /// let blocks = meta.blocks();
661 #[stable(feature = "metadata_ext", since = "1.1.0")]
662 fn blocks(&self) -> u64;
665 #[stable(feature = "metadata_ext", since = "1.1.0")]
666 impl MetadataExt for fs::Metadata {
667 fn dev(&self) -> u64 {
670 fn ino(&self) -> u64 {
673 fn mode(&self) -> u32 {
676 fn nlink(&self) -> u64 {
679 fn uid(&self) -> u32 {
682 fn gid(&self) -> u32 {
685 fn rdev(&self) -> u64 {
688 fn size(&self) -> u64 {
691 fn atime(&self) -> i64 {
694 fn atime_nsec(&self) -> i64 {
697 fn mtime(&self) -> i64 {
700 fn mtime_nsec(&self) -> i64 {
703 fn ctime(&self) -> i64 {
706 fn ctime_nsec(&self) -> i64 {
709 fn blksize(&self) -> u64 {
712 fn blocks(&self) -> u64 {
717 /// Unix-specific extensions for [`FileType`].
719 /// Adds support for special Unix file types such as block/character devices,
720 /// pipes, and sockets.
722 /// [`FileType`]: ../../../../std/fs/struct.FileType.html
723 #[stable(feature = "file_type_ext", since = "1.5.0")]
724 pub trait FileTypeExt {
725 /// Returns `true` if this file type is a block device.
731 /// use std::os::unix::fs::FileTypeExt;
734 /// fn main() -> io::Result<()> {
735 /// let meta = fs::metadata("block_device_file")?;
736 /// let file_type = meta.file_type();
737 /// assert!(file_type.is_block_device());
741 #[stable(feature = "file_type_ext", since = "1.5.0")]
742 fn is_block_device(&self) -> bool;
743 /// Returns `true` if this file type is a char device.
749 /// use std::os::unix::fs::FileTypeExt;
752 /// fn main() -> io::Result<()> {
753 /// let meta = fs::metadata("char_device_file")?;
754 /// let file_type = meta.file_type();
755 /// assert!(file_type.is_char_device());
759 #[stable(feature = "file_type_ext", since = "1.5.0")]
760 fn is_char_device(&self) -> bool;
761 /// Returns `true` if this file type is a fifo.
767 /// use std::os::unix::fs::FileTypeExt;
770 /// fn main() -> io::Result<()> {
771 /// let meta = fs::metadata("fifo_file")?;
772 /// let file_type = meta.file_type();
773 /// assert!(file_type.is_fifo());
777 #[stable(feature = "file_type_ext", since = "1.5.0")]
778 fn is_fifo(&self) -> bool;
779 /// Returns `true` if this file type is a socket.
785 /// use std::os::unix::fs::FileTypeExt;
788 /// fn main() -> io::Result<()> {
789 /// let meta = fs::metadata("unix.socket")?;
790 /// let file_type = meta.file_type();
791 /// assert!(file_type.is_socket());
795 #[stable(feature = "file_type_ext", since = "1.5.0")]
796 fn is_socket(&self) -> bool;
799 #[stable(feature = "file_type_ext", since = "1.5.0")]
800 impl FileTypeExt for fs::FileType {
801 fn is_block_device(&self) -> bool {
802 self.as_inner().is(libc::S_IFBLK)
804 fn is_char_device(&self) -> bool {
805 self.as_inner().is(libc::S_IFCHR)
807 fn is_fifo(&self) -> bool {
808 self.as_inner().is(libc::S_IFIFO)
810 fn is_socket(&self) -> bool {
811 self.as_inner().is(libc::S_IFSOCK)
815 /// Unix-specific extension methods for [`fs::DirEntry`].
817 /// [`fs::DirEntry`]: ../../../../std/fs/struct.DirEntry.html
818 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
819 pub trait DirEntryExt {
820 /// Returns the underlying `d_ino` field in the contained `dirent`
827 /// use std::os::unix::fs::DirEntryExt;
829 /// if let Ok(entries) = fs::read_dir(".") {
830 /// for entry in entries {
831 /// if let Ok(entry) = entry {
832 /// // Here, `entry` is a `DirEntry`.
833 /// println!("{:?}: {}", entry.file_name(), entry.ino());
838 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
839 fn ino(&self) -> u64;
842 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
843 impl DirEntryExt for fs::DirEntry {
844 fn ino(&self) -> u64 {
845 self.as_inner().ino()
849 /// Creates a new symbolic link on the filesystem.
851 /// The `dst` path will be a symbolic link pointing to the `src` path.
855 /// On Windows, you must specify whether a symbolic link points to a file
856 /// or directory. Use `os::windows::fs::symlink_file` to create a
857 /// symbolic link to a file, or `os::windows::fs::symlink_dir` to create a
858 /// symbolic link to a directory. Additionally, the process must have
859 /// `SeCreateSymbolicLinkPrivilege` in order to be able to create a
865 /// use std::os::unix::fs;
867 /// fn main() -> std::io::Result<()> {
868 /// fs::symlink("a.txt", "b.txt")?;
872 #[stable(feature = "symlink", since = "1.1.0")]
873 pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
874 sys::fs::symlink(src.as_ref(), dst.as_ref())
877 /// Unix-specific extensions to [`fs::DirBuilder`].
879 /// [`fs::DirBuilder`]: ../../../../std/fs/struct.DirBuilder.html
880 #[stable(feature = "dir_builder", since = "1.6.0")]
881 pub trait DirBuilderExt {
882 /// Sets the mode to create new directories with. This option defaults to
888 /// use std::fs::DirBuilder;
889 /// use std::os::unix::fs::DirBuilderExt;
891 /// let mut builder = DirBuilder::new();
892 /// builder.mode(0o755);
894 #[stable(feature = "dir_builder", since = "1.6.0")]
895 fn mode(&mut self, mode: u32) -> &mut Self;
898 #[stable(feature = "dir_builder", since = "1.6.0")]
899 impl DirBuilderExt for fs::DirBuilder {
900 fn mode(&mut self, mode: u32) -> &mut fs::DirBuilder {
901 self.as_inner_mut().set_mode(mode);