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}
;
11 // Used for `File::read` on intra-doc links
12 #[allow(unused_imports)]
13 use io
::{Read, Write}
;
15 /// Unix-specific extensions to [`fs::File`].
16 #[stable(feature = "file_offset", since = "1.15.0")]
18 /// Reads a number of bytes starting from a given offset.
20 /// Returns the number of bytes read.
22 /// The offset is relative to the start of the file and thus independent
23 /// from the current cursor.
25 /// The current file cursor is not affected by this function.
27 /// Note that similar to [`File::read`], it is not an error to return with a
30 /// [`File::read`]: fs::File::read
36 /// use std::fs::File;
37 /// use std::os::unix::prelude::FileExt;
39 /// fn main() -> io::Result<()> {
40 /// let mut buf = [0u8; 8];
41 /// let file = File::open("foo.txt")?;
43 /// // We now read 8 bytes from the offset 10.
44 /// let num_bytes_read = file.read_at(&mut buf, 10)?;
45 /// println!("read {} bytes: {:?}", num_bytes_read, buf);
49 #[stable(feature = "file_offset", since = "1.15.0")]
50 fn read_at(&self, buf
: &mut [u8], offset
: u64) -> io
::Result
<usize>;
52 /// Reads the exact number of byte required to fill `buf` from the given offset.
54 /// The offset is relative to the start of the file and thus independent
55 /// from the current cursor.
57 /// The current file cursor is not affected by this function.
59 /// Similar to [`io::Read::read_exact`] but uses [`read_at`] instead of `read`.
61 /// [`read_at`]: FileExt::read_at
65 /// If this function encounters an error of the kind
66 /// [`io::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 [`io::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.
84 /// use std::fs::File;
85 /// use std::os::unix::prelude::FileExt;
87 /// fn main() -> io::Result<()> {
88 /// let mut buf = [0u8; 8];
89 /// let file = File::open("foo.txt")?;
91 /// // We now read exactly 8 bytes from the offset 10.
92 /// file.read_exact_at(&mut buf, 10)?;
93 /// println!("read {} bytes: {:?}", buf.len(), buf);
97 #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
98 fn read_exact_at(&self, mut buf
: &mut [u8], mut offset
: u64) -> io
::Result
<()> {
99 while !buf
.is_empty() {
100 match self.read_at(buf
, offset
) {
107 Err(ref e
) if e
.kind() == io
::ErrorKind
::Interrupted
=> {}
108 Err(e
) => return Err(e
),
112 Err(io
::Error
::new(io
::ErrorKind
::UnexpectedEof
, "failed to fill whole buffer"))
118 /// Writes a number of bytes starting from a given offset.
120 /// Returns the number of bytes written.
122 /// The offset is relative to the start of the file and thus independent
123 /// from the current cursor.
125 /// The current file cursor is not affected by this function.
127 /// When writing beyond the end of the file, the file is appropriately
128 /// extended and the intermediate bytes are initialized with the value 0.
130 /// Note that similar to [`File::write`], it is not an error to return a
133 /// [`File::write`]: fs::File::write
138 /// use std::fs::File;
140 /// use std::os::unix::prelude::FileExt;
142 /// fn main() -> io::Result<()> {
143 /// let file = File::open("foo.txt")?;
145 /// // We now write at the offset 10.
146 /// file.write_at(b"sushi", 10)?;
150 #[stable(feature = "file_offset", since = "1.15.0")]
151 fn write_at(&self, buf
: &[u8], offset
: u64) -> io
::Result
<usize>;
153 /// Attempts to write an entire buffer starting from a given offset.
155 /// The offset is relative to the start of the file and thus independent
156 /// from the current cursor.
158 /// The current file cursor is not affected by this function.
160 /// This method will continuously call [`write_at`] until there is no more data
161 /// to be written or an error of non-[`io::ErrorKind::Interrupted`] kind is
162 /// returned. This method will not return until the entire buffer has been
163 /// successfully written or such an error occurs. The first error that is
164 /// not of [`io::ErrorKind::Interrupted`] kind generated from this method will be
169 /// This function will return the first error of
170 /// non-[`io::ErrorKind::Interrupted`] kind that [`write_at`] returns.
172 /// [`write_at`]: FileExt::write_at
177 /// use std::fs::File;
179 /// use std::os::unix::prelude::FileExt;
181 /// fn main() -> io::Result<()> {
182 /// let file = File::open("foo.txt")?;
184 /// // We now write at the offset 10.
185 /// file.write_all_at(b"sushi", 10)?;
189 #[stable(feature = "rw_exact_all_at", since = "1.33.0")]
190 fn write_all_at(&self, mut buf
: &[u8], mut offset
: u64) -> io
::Result
<()> {
191 while !buf
.is_empty() {
192 match self.write_at(buf
, offset
) {
194 return Err(io
::Error
::new(
195 io
::ErrorKind
::WriteZero
,
196 "failed to write whole buffer",
203 Err(ref e
) if e
.kind() == io
::ErrorKind
::Interrupted
=> {}
204 Err(e
) => return Err(e
),
211 #[stable(feature = "file_offset", since = "1.15.0")]
212 impl FileExt
for fs
::File
{
213 fn read_at(&self, buf
: &mut [u8], offset
: u64) -> io
::Result
<usize> {
214 self.as_inner().read_at(buf
, offset
)
216 fn write_at(&self, buf
: &[u8], offset
: u64) -> io
::Result
<usize> {
217 self.as_inner().write_at(buf
, offset
)
221 /// Unix-specific extensions to [`fs::Permissions`].
222 #[stable(feature = "fs_ext", since = "1.1.0")]
223 pub trait PermissionsExt
{
224 /// Returns the underlying raw `st_mode` bits that contain the standard
225 /// Unix permissions for this file.
230 /// use std::fs::File;
231 /// use std::os::unix::fs::PermissionsExt;
233 /// fn main() -> std::io::Result<()> {
234 /// let f = File::create("foo.txt")?;
235 /// let metadata = f.metadata()?;
236 /// let permissions = metadata.permissions();
238 /// println!("permissions: {:o}", permissions.mode());
242 #[stable(feature = "fs_ext", since = "1.1.0")]
243 fn mode(&self) -> u32;
245 /// Sets the underlying raw bits for this set of permissions.
250 /// use std::fs::File;
251 /// use std::os::unix::fs::PermissionsExt;
253 /// fn main() -> std::io::Result<()> {
254 /// let f = File::create("foo.txt")?;
255 /// let metadata = f.metadata()?;
256 /// let mut permissions = metadata.permissions();
258 /// permissions.set_mode(0o644); // Read/write for owner and read for others.
259 /// assert_eq!(permissions.mode(), 0o644);
263 #[stable(feature = "fs_ext", since = "1.1.0")]
264 fn set_mode(&mut self, mode
: u32);
266 /// Creates a new instance of `Permissions` from the given set of Unix
272 /// use std::fs::Permissions;
273 /// use std::os::unix::fs::PermissionsExt;
275 /// // Read/write for owner and read for others.
276 /// let permissions = Permissions::from_mode(0o644);
277 /// assert_eq!(permissions.mode(), 0o644);
279 #[stable(feature = "fs_ext", since = "1.1.0")]
280 fn from_mode(mode
: u32) -> Self;
283 #[stable(feature = "fs_ext", since = "1.1.0")]
284 impl PermissionsExt
for Permissions
{
285 fn mode(&self) -> u32 {
286 self.as_inner().mode()
289 fn set_mode(&mut self, mode
: u32) {
290 *self = Permissions
::from_inner(FromInner
::from_inner(mode
));
293 fn from_mode(mode
: u32) -> Permissions
{
294 Permissions
::from_inner(FromInner
::from_inner(mode
))
298 /// Unix-specific extensions to [`fs::OpenOptions`].
299 #[stable(feature = "fs_ext", since = "1.1.0")]
300 pub trait OpenOptionsExt
{
301 /// Sets the mode bits that a new file will be created with.
303 /// If a new file is created as part of an `OpenOptions::open` call then this
304 /// specified `mode` will be used as the permission bits for the new file.
305 /// If no `mode` is set, the default of `0o666` will be used.
306 /// The operating system masks out bits with the system's `umask`, to produce
307 /// the final permissions.
312 /// use std::fs::OpenOptions;
313 /// use std::os::unix::fs::OpenOptionsExt;
316 /// let mut options = OpenOptions::new();
317 /// options.mode(0o644); // Give read/write for owner and read for others.
318 /// let file = options.open("foo.txt");
321 #[stable(feature = "fs_ext", since = "1.1.0")]
322 fn mode(&mut self, mode
: u32) -> &mut Self;
324 /// Pass custom flags to the `flags` argument of `open`.
326 /// The bits that define the access mode are masked out with `O_ACCMODE`, to
327 /// ensure they do not interfere with the access mode set by Rusts options.
329 /// Custom flags can only set flags, not remove flags set by Rusts options.
330 /// This options overwrites any previously set custom flags.
335 /// # #![feature(rustc_private)]
336 /// extern crate libc;
337 /// use std::fs::OpenOptions;
338 /// use std::os::unix::fs::OpenOptionsExt;
341 /// let mut options = OpenOptions::new();
342 /// options.write(true);
344 /// options.custom_flags(libc::O_NOFOLLOW);
346 /// let file = options.open("foo.txt");
349 #[stable(feature = "open_options_ext", since = "1.10.0")]
350 fn custom_flags(&mut self, flags
: i32) -> &mut Self;
353 #[stable(feature = "fs_ext", since = "1.1.0")]
354 impl OpenOptionsExt
for OpenOptions
{
355 fn mode(&mut self, mode
: u32) -> &mut OpenOptions
{
356 self.as_inner_mut().mode(mode
);
360 fn custom_flags(&mut self, flags
: i32) -> &mut OpenOptions
{
361 self.as_inner_mut().custom_flags(flags
);
366 /// Unix-specific extensions to [`fs::Metadata`].
367 #[stable(feature = "metadata_ext", since = "1.1.0")]
368 pub trait MetadataExt
{
369 /// Returns the ID of the device containing the file.
376 /// use std::os::unix::fs::MetadataExt;
378 /// fn main() -> io::Result<()> {
379 /// let meta = fs::metadata("some_file")?;
380 /// let dev_id = meta.dev();
384 #[stable(feature = "metadata_ext", since = "1.1.0")]
385 fn dev(&self) -> u64;
386 /// Returns the inode number.
392 /// use std::os::unix::fs::MetadataExt;
395 /// fn main() -> io::Result<()> {
396 /// let meta = fs::metadata("some_file")?;
397 /// let inode = meta.ino();
401 #[stable(feature = "metadata_ext", since = "1.1.0")]
402 fn ino(&self) -> u64;
403 /// Returns the rights applied to this file.
409 /// use std::os::unix::fs::MetadataExt;
412 /// fn main() -> io::Result<()> {
413 /// let meta = fs::metadata("some_file")?;
414 /// let mode = meta.mode();
415 /// let user_has_write_access = mode & 0o200;
416 /// let user_has_read_write_access = mode & 0o600;
417 /// let group_has_read_access = mode & 0o040;
418 /// let others_have_exec_access = mode & 0o001;
422 #[stable(feature = "metadata_ext", since = "1.1.0")]
423 fn mode(&self) -> u32;
424 /// Returns the number of hard links pointing to this file.
430 /// use std::os::unix::fs::MetadataExt;
433 /// fn main() -> io::Result<()> {
434 /// let meta = fs::metadata("some_file")?;
435 /// let nb_hard_links = meta.nlink();
439 #[stable(feature = "metadata_ext", since = "1.1.0")]
440 fn nlink(&self) -> u64;
441 /// Returns the user ID of the owner of this file.
447 /// use std::os::unix::fs::MetadataExt;
450 /// fn main() -> io::Result<()> {
451 /// let meta = fs::metadata("some_file")?;
452 /// let user_id = meta.uid();
456 #[stable(feature = "metadata_ext", since = "1.1.0")]
457 fn uid(&self) -> u32;
458 /// Returns the group ID of the owner of this file.
464 /// use std::os::unix::fs::MetadataExt;
467 /// fn main() -> io::Result<()> {
468 /// let meta = fs::metadata("some_file")?;
469 /// let group_id = meta.gid();
473 #[stable(feature = "metadata_ext", since = "1.1.0")]
474 fn gid(&self) -> u32;
475 /// Returns the device ID of this file (if it is a special one).
481 /// use std::os::unix::fs::MetadataExt;
484 /// fn main() -> io::Result<()> {
485 /// let meta = fs::metadata("some_file")?;
486 /// let device_id = meta.rdev();
490 #[stable(feature = "metadata_ext", since = "1.1.0")]
491 fn rdev(&self) -> u64;
492 /// Returns the total size of this file in bytes.
498 /// use std::os::unix::fs::MetadataExt;
501 /// fn main() -> io::Result<()> {
502 /// let meta = fs::metadata("some_file")?;
503 /// let file_size = meta.size();
507 #[stable(feature = "metadata_ext", since = "1.1.0")]
508 fn size(&self) -> u64;
509 /// Returns the last access time of the file, in seconds since Unix Epoch.
515 /// use std::os::unix::fs::MetadataExt;
518 /// fn main() -> io::Result<()> {
519 /// let meta = fs::metadata("some_file")?;
520 /// let last_access_time = meta.atime();
524 #[stable(feature = "metadata_ext", since = "1.1.0")]
525 fn atime(&self) -> i64;
526 /// Returns the last access time of the file, in nanoseconds since [`atime`].
528 /// [`atime`]: MetadataExt::atime
534 /// use std::os::unix::fs::MetadataExt;
537 /// fn main() -> io::Result<()> {
538 /// let meta = fs::metadata("some_file")?;
539 /// let nano_last_access_time = meta.atime_nsec();
543 #[stable(feature = "metadata_ext", since = "1.1.0")]
544 fn atime_nsec(&self) -> i64;
545 /// Returns the last modification time of the file, in seconds since Unix Epoch.
551 /// use std::os::unix::fs::MetadataExt;
554 /// fn main() -> io::Result<()> {
555 /// let meta = fs::metadata("some_file")?;
556 /// let last_modification_time = meta.mtime();
560 #[stable(feature = "metadata_ext", since = "1.1.0")]
561 fn mtime(&self) -> i64;
562 /// Returns the last modification time of the file, in nanoseconds since [`mtime`].
564 /// [`mtime`]: MetadataExt::mtime
570 /// use std::os::unix::fs::MetadataExt;
573 /// fn main() -> io::Result<()> {
574 /// let meta = fs::metadata("some_file")?;
575 /// let nano_last_modification_time = meta.mtime_nsec();
579 #[stable(feature = "metadata_ext", since = "1.1.0")]
580 fn mtime_nsec(&self) -> i64;
581 /// Returns the last status change time of the file, in seconds since Unix Epoch.
587 /// use std::os::unix::fs::MetadataExt;
590 /// fn main() -> io::Result<()> {
591 /// let meta = fs::metadata("some_file")?;
592 /// let last_status_change_time = meta.ctime();
596 #[stable(feature = "metadata_ext", since = "1.1.0")]
597 fn ctime(&self) -> i64;
598 /// Returns the last status change time of the file, in nanoseconds since [`ctime`].
600 /// [`ctime`]: MetadataExt::ctime
606 /// use std::os::unix::fs::MetadataExt;
609 /// fn main() -> io::Result<()> {
610 /// let meta = fs::metadata("some_file")?;
611 /// let nano_last_status_change_time = meta.ctime_nsec();
615 #[stable(feature = "metadata_ext", since = "1.1.0")]
616 fn ctime_nsec(&self) -> i64;
617 /// Returns the block size for filesystem I/O.
623 /// use std::os::unix::fs::MetadataExt;
626 /// fn main() -> io::Result<()> {
627 /// let meta = fs::metadata("some_file")?;
628 /// let block_size = meta.blksize();
632 #[stable(feature = "metadata_ext", since = "1.1.0")]
633 fn blksize(&self) -> u64;
634 /// Returns the number of blocks allocated to the file, in 512-byte units.
636 /// Please note that this may be smaller than `st_size / 512` when the file has holes.
642 /// use std::os::unix::fs::MetadataExt;
645 /// fn main() -> io::Result<()> {
646 /// let meta = fs::metadata("some_file")?;
647 /// let blocks = meta.blocks();
651 #[stable(feature = "metadata_ext", since = "1.1.0")]
652 fn blocks(&self) -> u64;
653 #[cfg(target_os = "vxworks")]
654 #[stable(feature = "metadata_ext", since = "1.1.0")]
655 fn attrib(&self) -> u8;
658 #[stable(feature = "metadata_ext", since = "1.1.0")]
659 impl MetadataExt
for fs
::Metadata
{
660 fn dev(&self) -> u64 {
663 fn ino(&self) -> u64 {
666 fn mode(&self) -> u32 {
669 fn nlink(&self) -> u64 {
672 fn uid(&self) -> u32 {
675 fn gid(&self) -> u32 {
678 fn rdev(&self) -> u64 {
681 fn size(&self) -> u64 {
684 fn atime(&self) -> i64 {
687 fn atime_nsec(&self) -> i64 {
690 fn mtime(&self) -> i64 {
693 fn mtime_nsec(&self) -> i64 {
696 fn ctime(&self) -> i64 {
699 fn ctime_nsec(&self) -> i64 {
702 fn blksize(&self) -> u64 {
705 fn blocks(&self) -> u64 {
708 #[cfg(target_os = "vxworks")]
709 fn attrib(&self) -> u8 {
714 /// Unix-specific extensions for [`fs::FileType`].
716 /// Adds support for special Unix file types such as block/character devices,
717 /// pipes, and sockets.
718 #[stable(feature = "file_type_ext", since = "1.5.0")]
719 pub trait FileTypeExt
{
720 /// Returns `true` if this file type is a block device.
726 /// use std::os::unix::fs::FileTypeExt;
729 /// fn main() -> io::Result<()> {
730 /// let meta = fs::metadata("block_device_file")?;
731 /// let file_type = meta.file_type();
732 /// assert!(file_type.is_block_device());
736 #[stable(feature = "file_type_ext", since = "1.5.0")]
737 fn is_block_device(&self) -> bool
;
738 /// Returns `true` if this file type is a char device.
744 /// use std::os::unix::fs::FileTypeExt;
747 /// fn main() -> io::Result<()> {
748 /// let meta = fs::metadata("char_device_file")?;
749 /// let file_type = meta.file_type();
750 /// assert!(file_type.is_char_device());
754 #[stable(feature = "file_type_ext", since = "1.5.0")]
755 fn is_char_device(&self) -> bool
;
756 /// Returns `true` if this file type is a fifo.
762 /// use std::os::unix::fs::FileTypeExt;
765 /// fn main() -> io::Result<()> {
766 /// let meta = fs::metadata("fifo_file")?;
767 /// let file_type = meta.file_type();
768 /// assert!(file_type.is_fifo());
772 #[stable(feature = "file_type_ext", since = "1.5.0")]
773 fn is_fifo(&self) -> bool
;
774 /// Returns `true` if this file type is a socket.
780 /// use std::os::unix::fs::FileTypeExt;
783 /// fn main() -> io::Result<()> {
784 /// let meta = fs::metadata("unix.socket")?;
785 /// let file_type = meta.file_type();
786 /// assert!(file_type.is_socket());
790 #[stable(feature = "file_type_ext", since = "1.5.0")]
791 fn is_socket(&self) -> bool
;
794 #[stable(feature = "file_type_ext", since = "1.5.0")]
795 impl FileTypeExt
for fs
::FileType
{
796 fn is_block_device(&self) -> bool
{
797 self.as_inner().is(libc
::S_IFBLK
)
799 fn is_char_device(&self) -> bool
{
800 self.as_inner().is(libc
::S_IFCHR
)
802 fn is_fifo(&self) -> bool
{
803 self.as_inner().is(libc
::S_IFIFO
)
805 fn is_socket(&self) -> bool
{
806 self.as_inner().is(libc
::S_IFSOCK
)
810 /// Unix-specific extension methods for [`fs::DirEntry`].
811 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
812 pub trait DirEntryExt
{
813 /// Returns the underlying `d_ino` field in the contained `dirent`
820 /// use std::os::unix::fs::DirEntryExt;
822 /// if let Ok(entries) = fs::read_dir(".") {
823 /// for entry in entries {
824 /// if let Ok(entry) = entry {
825 /// // Here, `entry` is a `DirEntry`.
826 /// println!("{:?}: {}", entry.file_name(), entry.ino());
831 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
832 fn ino(&self) -> u64;
835 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
836 impl DirEntryExt
for fs
::DirEntry
{
837 fn ino(&self) -> u64 {
838 self.as_inner().ino()
842 /// Creates a new symbolic link on the filesystem.
844 /// The `dst` path will be a symbolic link pointing to the `src` path.
849 /// use std::os::unix::fs;
851 /// fn main() -> std::io::Result<()> {
852 /// fs::symlink("a.txt", "b.txt")?;
856 #[stable(feature = "symlink", since = "1.1.0")]
857 pub fn symlink
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(src
: P
, dst
: Q
) -> io
::Result
<()> {
858 sys
::fs
::symlink(src
.as_ref(), dst
.as_ref())
861 /// Unix-specific extensions to [`fs::DirBuilder`].
862 #[stable(feature = "dir_builder", since = "1.6.0")]
863 pub trait DirBuilderExt
{
864 /// Sets the mode to create new directories with. This option defaults to
870 /// use std::fs::DirBuilder;
871 /// use std::os::unix::fs::DirBuilderExt;
873 /// let mut builder = DirBuilder::new();
874 /// builder.mode(0o755);
876 #[stable(feature = "dir_builder", since = "1.6.0")]
877 fn mode(&mut self, mode
: u32) -> &mut Self;
880 #[stable(feature = "dir_builder", since = "1.6.0")]
881 impl DirBuilderExt
for fs
::DirBuilder
{
882 fn mode(&mut self, mode
: u32) -> &mut fs
::DirBuilder
{
883 self.as_inner_mut().set_mode(mode
);