Movatterモバイル変換


[0]ホーム

URL:


std::fs

StructFile

1.0.0 ·Source
pub struct File {/* private fields */ }
Expand description

An object providing access to an open file on the filesystem.

An instance of aFile can be read and/or written depending on what optionsit was opened with. Files also implementSeek to alter the logical cursorthat the file contains internally.

Files are automatically closed when they go out of scope. Errors detectedon closing are ignored by the implementation ofDrop. Use the methodsync_all if these errors must be manually handled.

File does not buffer reads and writes. For efficiency, consider wrapping thefile in aBufReader orBufWriter when performing many smallreadorwrite calls, unless unbuffered reads and writes are required.

§Examples

Creates a new file and write bytes to it (you can also usewrite):

usestd::fs::File;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letmutfile = File::create("foo.txt")?;    file.write_all(b"Hello, world!")?;Ok(())}

Reads the contents of a file into aString (you can also useread):

usestd::fs::File;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letmutfile = File::open("foo.txt")?;letmutcontents = String::new();    file.read_to_string(&mutcontents)?;assert_eq!(contents,"Hello, world!");Ok(())}

Using a bufferedReader:

usestd::fs::File;usestd::io::BufReader;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letfile = File::open("foo.txt")?;letmutbuf_reader = BufReader::new(file);letmutcontents = String::new();    buf_reader.read_to_string(&mutcontents)?;assert_eq!(contents,"Hello, world!");Ok(())}

Note that, although read and write methods require a&mut File, becauseof the interfaces forRead andWrite, the holder of a&File canstill modify the file, either through methods that take&File or byretrieving the underlying OS object and modifying the file that way.Additionally, many operating systems allow concurrent modification of filesby different processes. Avoid assuming that holding a&File means that thefile will not change.

§Platform-specific behavior

On Windows, the implementation ofRead andWrite traits forFileperform synchronous I/O operations. Therefore the underlying file must nothave been opened for asynchronous I/O (e.g. by usingFILE_FLAG_OVERLAPPED).

Implementations§

Source§

implFile

1.0.0 ·Source

pub fnopen<P:AsRef<Path>>(path: P) ->Result<File>

Attempts to open a file in read-only mode.

See theOpenOptions::open method for more details.

If you only need to read the entire file contents,considerstd::fs::read() orstd::fs::read_to_string() instead.

§Errors

This function will return an error ifpath does not already exist.Other errors may also be returned according toOpenOptions::open.

§Examples
usestd::fs::File;usestd::io::Read;fnmain() -> std::io::Result<()> {letmutf = File::open("foo.txt")?;letmutdata =vec![];    f.read_to_end(&mutdata)?;Ok(())}
Source

pub fnopen_buffered<P:AsRef<Path>>(path: P) ->Result<BufReader<File>>

🔬This is a nightly-only experimental API. (file_buffered #130804)

Attempts to open a file in read-only mode with buffering.

See theOpenOptions::open method, theBufReader type,and theBufRead trait for more details.

If you only need to read the entire file contents,considerstd::fs::read() orstd::fs::read_to_string() instead.

§Errors

This function will return an error ifpath does not already exist,or if memory allocation fails for the new buffer.Other errors may also be returned according toOpenOptions::open.

§Examples
#![feature(file_buffered)]usestd::fs::File;usestd::io::BufRead;fnmain() -> std::io::Result<()> {letmutf = File::open_buffered("foo.txt")?;assert!(f.capacity() >0);for(line, i)inf.lines().zip(1..) {println!("{i:6}: {}", line?);    }Ok(())}
1.0.0 ·Source

pub fncreate<P:AsRef<Path>>(path: P) ->Result<File>

Opens a file in write-only mode.

This function will create a file if it does not exist,and will truncate it if it does.

Depending on the platform, this function may fail if thefull directory path does not exist.See theOpenOptions::open function for more details.

See alsostd::fs::write() for a simple function tocreate a file with some given data.

§Examples
usestd::fs::File;usestd::io::Write;fnmain() -> std::io::Result<()> {letmutf = File::create("foo.txt")?;    f.write_all(&1234_u32.to_be_bytes())?;Ok(())}
Source

pub fncreate_buffered<P:AsRef<Path>>(path: P) ->Result<BufWriter<File>>

🔬This is a nightly-only experimental API. (file_buffered #130804)

Opens a file in write-only mode with buffering.

This function will create a file if it does not exist,and will truncate it if it does.

Depending on the platform, this function may fail if thefull directory path does not exist.

See theOpenOptions::open method and theBufWriter type for more details.

See alsostd::fs::write() for a simple function tocreate a file with some given data.

§Examples
#![feature(file_buffered)]usestd::fs::File;usestd::io::Write;fnmain() -> std::io::Result<()> {letmutf = File::create_buffered("foo.txt")?;assert!(f.capacity() >0);foriin0..100{writeln!(&mutf,"{i}")?;    }    f.flush()?;Ok(())}
1.77.0 ·Source

pub fncreate_new<P:AsRef<Path>>(path: P) ->Result<File>

Creates a new file in read-write mode; error if the file exists.

This function will create a file if it does not exist, or return an error if it does. Thisway, if the call succeeds, the file returned is guaranteed to be new.If a file exists at the target location, creating a new file will fail withAlreadyExistsor another error based on the situation. SeeOpenOptions::open for anon-exhaustive list of likely errors.

This option is useful because it is atomic. Otherwise between checking whether a fileexists and creating a new one, the file may have been created by another process (a TOCTOUrace condition / attack).

This can also be written usingFile::options().read(true).write(true).create_new(true).open(...).

§Examples
usestd::fs::File;usestd::io::Write;fnmain() -> std::io::Result<()> {letmutf = File::create_new("foo.txt")?;    f.write_all("Hello, world!".as_bytes())?;Ok(())}
1.58.0 ·Source

pub fnoptions() ->OpenOptions

Returns a new OpenOptions object.

This function returns a new OpenOptions object that you can use toopen or create a file with specific options ifopen() orcreate()are not appropriate.

It is equivalent toOpenOptions::new(), but allows you to write morereadable code. Instead ofOpenOptions::new().append(true).open("example.log"),you can writeFile::options().append(true).open("example.log"). Thisalso avoids the need to importOpenOptions.

See theOpenOptions::new function for more details.

§Examples
usestd::fs::File;usestd::io::Write;fnmain() -> std::io::Result<()> {letmutf = File::options().append(true).open("example.log")?;writeln!(&mutf,"new line")?;Ok(())}
1.0.0 ·Source

pub fnsync_all(&self) ->Result<()>

Attempts to sync all OS-internal file content and metadata to disk.

This function will attempt to ensure that all in-memory data reaches thefilesystem before returning.

This can be used to handle errors that would otherwise only be caughtwhen theFile is closed, as dropping aFile will ignore all errors.Note, however, thatsync_all is generally more expensive than closinga file by dropping it, because the latter is not required to block untilthe data has been written to the filesystem.

If synchronizing the metadata is not required, usesync_data instead.

§Examples
usestd::fs::File;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letmutf = File::create("foo.txt")?;    f.write_all(b"Hello, world!")?;    f.sync_all()?;Ok(())}
1.0.0 ·Source

pub fnsync_data(&self) ->Result<()>

This function is similar tosync_all, except that it might notsynchronize file metadata to the filesystem.

This is intended for use cases that must synchronize content, but don’tneed the metadata on disk. The goal of this method is to reduce diskoperations.

Note that some platforms may simply implement this in terms ofsync_all.

§Examples
usestd::fs::File;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letmutf = File::create("foo.txt")?;    f.write_all(b"Hello, world!")?;    f.sync_data()?;Ok(())}
Source

pub fnlock(&self) ->Result<()>

🔬This is a nightly-only experimental API. (file_lock #130994)

Acquire an exclusive lock on the file. Blocks until the lock can be acquired.

This acquires an exclusive lock; no other file handle to this file may acquire another lock.

This lock may be advisory or mandatory. This lock is meant to interact withlock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions withother methods, such asread andwrite are platform specific, and it may or may notcause non-lockholders to block.

If this file handle/descriptor, or a clone of it, already holds an lock the exact behavioris unspecified and platform dependent, including the possibility that it will deadlock.However, if this method returns, then an exclusive lock is held.

If the file not open for writing, it is unspecified whether this function returns an error.

The lock will be released when this file (along with any other file descriptors/handlesduplicated or inherited from it) is closed, or if theunlock method is called.

§Platform-specific behavior

This function currently corresponds to theflock function on Unix with theLOCK_EX flag,and theLockFileEx function on Windows with theLOCKFILE_EXCLUSIVE_LOCK flag. Note that,thismay change in the future.

On Windows, locking a file will fail if the file is opened only for append. To lock a file,open it with one of.read(true),.read(true).append(true), or.write(true).

§Examples
#![feature(file_lock)]usestd::fs::File;fnmain() -> std::io::Result<()> {letf = File::create("foo.txt")?;    f.lock()?;Ok(())}
Source

pub fnlock_shared(&self) ->Result<()>

🔬This is a nightly-only experimental API. (file_lock #130994)

Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.

This acquires a shared lock; more than one file handle may hold a shared lock, but none mayhold an exclusive lock at the same time.

This lock may be advisory or mandatory. This lock is meant to interact withlock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions withother methods, such asread andwrite are platform specific, and it may or may notcause non-lockholders to block.

If this file handle/descriptor, or a clone of it, already holds an lock, the exact behavioris unspecified and platform dependent, including the possibility that it will deadlock.However, if this method returns, then a shared lock is held.

The lock will be released when this file (along with any other file descriptors/handlesduplicated or inherited from it) is closed, or if theunlock method is called.

§Platform-specific behavior

This function currently corresponds to theflock function on Unix with theLOCK_SH flag,and theLockFileEx function on Windows. Note that, thismay change in the future.

On Windows, locking a file will fail if the file is opened only for append. To lock a file,open it with one of.read(true),.read(true).append(true), or.write(true).

§Examples
#![feature(file_lock)]usestd::fs::File;fnmain() -> std::io::Result<()> {letf = File::open("foo.txt")?;    f.lock_shared()?;Ok(())}
Source

pub fntry_lock(&self) ->Result<(),TryLockError>

🔬This is a nightly-only experimental API. (file_lock #130994)

Try to acquire an exclusive lock on the file.

ReturnsErr(TryLockError::WouldBlock) if a different lock is already held on this file(via another handle/descriptor).

This acquires an exclusive lock; no other file handle to this file may acquire another lock.

This lock may be advisory or mandatory. This lock is meant to interact withlock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions withother methods, such asread andwrite are platform specific, and it may or may notcause non-lockholders to block.

If this file handle/descriptor, or a clone of it, already holds an lock, the exact behavioris unspecified and platform dependent, including the possibility that it will deadlock.However, if this method returnsOk(true), then it has acquired an exclusive lock.

If the file not open for writing, it is unspecified whether this function returns an error.

The lock will be released when this file (along with any other file descriptors/handlesduplicated or inherited from it) is closed, or if theunlock method is called.

§Platform-specific behavior

This function currently corresponds to theflock function on Unix with theLOCK_EX andLOCK_NB flags, and theLockFileEx function on Windows with theLOCKFILE_EXCLUSIVE_LOCKandLOCKFILE_FAIL_IMMEDIATELY flags. Note that, thismay change in the future.

On Windows, locking a file will fail if the file is opened only for append. To lock a file,open it with one of.read(true),.read(true).append(true), or.write(true).

§Examples
#![feature(file_lock)]usestd::fs::{File, TryLockError};fnmain() -> std::io::Result<()> {letf = File::create("foo.txt")?;matchf.try_lock() {Ok(_) => (),Err(TryLockError::WouldBlock) => (),// Lock not acquiredErr(TryLockError::Error(err)) =>returnErr(err),    }Ok(())}
Source

pub fntry_lock_shared(&self) ->Result<(),TryLockError>

🔬This is a nightly-only experimental API. (file_lock #130994)

Try to acquire a shared (non-exclusive) lock on the file.

ReturnsErr(TryLockError::WouldBlock) if a different lock is already held on this file(via another handle/descriptor).

This acquires a shared lock; more than one file handle may hold a shared lock, but none mayhold an exclusive lock at the same time.

This lock may be advisory or mandatory. This lock is meant to interact withlock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions withother methods, such asread andwrite are platform specific, and it may or may notcause non-lockholders to block.

If this file handle, or a clone of it, already holds an lock, the exact behavior isunspecified and platform dependent, including the possibility that it will deadlock.However, if this method returnsOk(true), then it has acquired a shared lock.

The lock will be released when this file (along with any other file descriptors/handlesduplicated or inherited from it) is closed, or if theunlock method is called.

§Platform-specific behavior

This function currently corresponds to theflock function on Unix with theLOCK_SH andLOCK_NB flags, and theLockFileEx function on Windows with theLOCKFILE_FAIL_IMMEDIATELY flag. Note that, thismay change in the future.

On Windows, locking a file will fail if the file is opened only for append. To lock a file,open it with one of.read(true),.read(true).append(true), or.write(true).

§Examples
#![feature(file_lock)]usestd::fs::{File, TryLockError};fnmain() -> std::io::Result<()> {letf = File::open("foo.txt")?;matchf.try_lock_shared() {Ok(_) => (),Err(TryLockError::WouldBlock) => (),// Lock not acquiredErr(TryLockError::Error(err)) =>returnErr(err),    }Ok(())}
Source

pub fnunlock(&self) ->Result<()>

🔬This is a nightly-only experimental API. (file_lock #130994)

Release all locks on the file.

All locks are released when the file (along with any other file descriptors/handlesduplicated or inherited from it) is closed. This method allows releasing locks withoutclosing the file.

If no lock is currently held via this file descriptor/handle, this method may return anerror, or may return successfully without taking any action.

§Platform-specific behavior

This function currently corresponds to theflock function on Unix with theLOCK_UN flag,and theUnlockFile function on Windows. Note that, thismay change in the future.

On Windows, locking a file will fail if the file is opened only for append. To lock a file,open it with one of.read(true),.read(true).append(true), or.write(true).

§Examples
#![feature(file_lock)]usestd::fs::File;fnmain() -> std::io::Result<()> {letf = File::open("foo.txt")?;    f.lock()?;    f.unlock()?;Ok(())}
1.0.0 ·Source

pub fnset_len(&self, size:u64) ->Result<()>

Truncates or extends the underlying file, updating the size ofthis file to becomesize.

If thesize is less than the current file’s size, then the file willbe shrunk. If it is greater than the current file’s size, then the filewill be extended tosize and have all of the intermediate data filledin with 0s.

The file’s cursor isn’t changed. In particular, if the cursor was at theend and the file is shrunk using this operation, the cursor will now bepast the end.

§Errors

This function will return an error if the file is not opened for writing.Also,std::io::ErrorKind::InvalidInputwill be returned if the desired length would cause an overflow due tothe implementation specifics.

§Examples
usestd::fs::File;fnmain() -> std::io::Result<()> {letmutf = File::create("foo.txt")?;    f.set_len(10)?;Ok(())}

Note that this method alters the content of the underlying file, eventhough it takes&self rather than&mut self.

1.0.0 ·Source

pub fnmetadata(&self) ->Result<Metadata>

Queries metadata about the underlying file.

§Examples
usestd::fs::File;fnmain() -> std::io::Result<()> {letmutf = File::open("foo.txt")?;letmetadata = f.metadata()?;Ok(())}
1.9.0 ·Source

pub fntry_clone(&self) ->Result<File>

Creates a newFile instance that shares the same underlying file handleas the existingFile instance. Reads, writes, and seeks will affectbothFile instances simultaneously.

§Examples

Creates two handles for a file namedfoo.txt:

usestd::fs::File;fnmain() -> std::io::Result<()> {letmutfile = File::open("foo.txt")?;letfile_copy = file.try_clone()?;Ok(())}

Assuming there’s a file namedfoo.txt with contentsabcdef\n, createtwo handles, seek one of them, and read the remaining bytes from theother handle:

usestd::fs::File;usestd::io::SeekFrom;usestd::io::prelude::*;fnmain() -> std::io::Result<()> {letmutfile = File::open("foo.txt")?;letmutfile_copy = file.try_clone()?;    file.seek(SeekFrom::Start(3))?;letmutcontents =vec![];    file_copy.read_to_end(&mutcontents)?;assert_eq!(contents,b"def\n");Ok(())}
1.16.0 ·Source

pub fnset_permissions(&self, perm:Permissions) ->Result<()>

Changes the permissions on the underlying file.

§Platform-specific behavior

This function currently corresponds to thefchmod function on Unix andtheSetFileInformationByHandle function on Windows. Note that, thismay change in the future.

§Errors

This function will return an error if the user lacks permission changeattributes on the underlying file. It may also return an error in otheros-specific unspecified cases.

§Examples
fnmain() -> std::io::Result<()> {usestd::fs::File;letfile = File::open("foo.txt")?;letmutperms = file.metadata()?.permissions();    perms.set_readonly(true);    file.set_permissions(perms)?;Ok(())}

Note that this method alters the permissions of the underlying file,even though it takes&self rather than&mut self.

1.75.0 ·Source

pub fnset_times(&self, times:FileTimes) ->Result<()>

Changes the timestamps of the underlying file.

§Platform-specific behavior

This function currently corresponds to thefutimens function on Unix (falling back tofutimes on macOS before 10.13) and theSetFileTime function on Windows. Note that thismay change in the future.

§Errors

This function will return an error if the user lacks permission to change timestamps on theunderlying file. It may also return an error in other os-specific unspecified cases.

This function may return an error if the operating system lacks support to change one ormore of the timestamps set in theFileTimes structure.

§Examples
fnmain() -> std::io::Result<()> {usestd::fs::{self, File, FileTimes};letsrc = fs::metadata("src")?;letdest = File::options().write(true).open("dest")?;lettimes = FileTimes::new()        .set_accessed(src.accessed()?)        .set_modified(src.modified()?);    dest.set_times(times)?;Ok(())}
1.75.0 ·Source

pub fnset_modified(&self, time:SystemTime) ->Result<()>

Changes the modification time of the underlying file.

This is an alias forset_times(FileTimes::new().set_modified(time)).

Trait Implementations§

1.63.0 ·Source§

implAsFd forFile

Source§

fnas_fd(&self) ->BorrowedFd<'_>

Borrows the file descriptor.Read more
1.63.0 ·Source§

implAsHandle forFile

Available onWindows only.
Source§

fnas_handle(&self) ->BorrowedHandle<'_>

Borrows the handle.Read more
1.0.0 ·Source§

implAsRawFd forFile

Source§

fnas_raw_fd(&self) ->RawFd

Extracts the raw file descriptor.Read more
1.0.0 ·Source§

implAsRawHandle forFile

Available onWindows only.
Source§

fnas_raw_handle(&self) ->RawHandle

Extracts the raw handle.Read more
1.0.0 ·Source§

implDebug forFile

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result

Formats the value using the given formatter.Read more
1.15.0 ·Source§

implFileExt forFile

Available onUnix only.
Source§

fnread_at(&self, buf: &mut [u8], offset:u64) ->Result<usize>

Reads a number of bytes starting from a given offset.Read more
Source§

fnread_vectored_at( &self, bufs: &mut [IoSliceMut<'_>], offset:u64,) ->Result<usize>

🔬This is a nightly-only experimental API. (unix_file_vectored_at #89517)
Likeread_at, except that it reads into a slice of buffers.Read more
Source§

fnwrite_at(&self, buf: &[u8], offset:u64) ->Result<usize>

Writes a number of bytes starting from a given offset.Read more
Source§

fnwrite_vectored_at(&self, bufs: &[IoSlice<'_>], offset:u64) ->Result<usize>

🔬This is a nightly-only experimental API. (unix_file_vectored_at #89517)
Likewrite_at, except that it writes from a slice of buffers.Read more
1.33.0 ·Source§

fnread_exact_at(&self, buf: &mut [u8], offset:u64) ->Result<()>

Reads the exact number of bytes required to fillbuf from the given offset.Read more
1.33.0 ·Source§

fnwrite_all_at(&self, buf: &[u8], offset:u64) ->Result<()>

Attempts to write an entire buffer starting from a given offset.Read more
Source§

implFileExt forFile

Available onWASI only.
Source§

fnread_vectored_at( &self, bufs: &mut [IoSliceMut<'_>], offset:u64,) ->Result<usize>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Reads a number of bytes starting from a given offset.Read more
Source§

fnwrite_vectored_at(&self, bufs: &[IoSlice<'_>], offset:u64) ->Result<usize>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Writes a number of bytes starting from a given offset.Read more
Source§

fnfdstat_set_flags(&self, flags:u16) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Adjusts the flags associated with this file.Read more
Source§

fnfdstat_set_rights(&self, rights:u64, inheriting:u64) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Adjusts the rights associated with this file.Read more
Source§

fnadvise(&self, offset:u64, len:u64, advice:u8) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Provides file advisory information on a file descriptor.Read more
Source§

fnallocate(&self, offset:u64, len:u64) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Forces the allocation of space in a file.Read more
Source§

fncreate_directory<P:AsRef<Path>>(&self, dir: P) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Creates a directory.Read more
Source§

fnread_link<P:AsRef<Path>>(&self, path: P) ->Result<PathBuf>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Reads the contents of a symbolic link.Read more
Source§

fnmetadata_at<P:AsRef<Path>>( &self, lookup_flags:u32, path: P,) ->Result<Metadata>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Returns the attributes of a file or directory.Read more
Source§

fnremove_file<P:AsRef<Path>>(&self, path: P) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Unlinks a file.Read more
Source§

fnremove_directory<P:AsRef<Path>>(&self, path: P) ->Result<()>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Removes a directory.Read more
Source§

fnread_at(&self, buf: &mut [u8], offset:u64) ->Result<usize>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Reads a number of bytes starting from a given offset.Read more
1.33.0 ·Source§

fnread_exact_at(&self, buf: &mut [u8], offset:u64) ->Result<()>

Reads the exact number of byte required to fillbuf from the given offset.Read more
Source§

fnwrite_at(&self, buf: &[u8], offset:u64) ->Result<usize>

🔬This is a nightly-only experimental API. (wasi_ext #71213)
Writes a number of bytes starting from a given offset.Read more
1.33.0 ·Source§

fnwrite_all_at(&self, buf: &[u8], offset:u64) ->Result<()>

Attempts to write an entire buffer starting from a given offset.Read more
1.15.0 ·Source§

implFileExt forFile

Available onWindows only.
Source§

fnseek_read(&self, buf: &mut [u8], offset:u64) ->Result<usize>

Seeks to a given position and reads a number of bytes.Read more
Source§

fnseek_write(&self, buf: &[u8], offset:u64) ->Result<usize>

Seeks to a given position and writes a number of bytes.Read more
1.63.0 ·Source§

implFrom<File> forOwnedFd

Source§

fnfrom(file:File) ->OwnedFd

Takes ownership of aFile’s underlying file descriptor.

1.63.0 ·Source§

implFrom<File> forOwnedHandle

Available onWindows only.
Source§

fnfrom(file:File) ->OwnedHandle

Takes ownership of aFile’s underlying file handle.

1.20.0 ·Source§

implFrom<File> forStdio

Source§

fnfrom(file:File) ->Stdio

Converts aFile into aStdio.

§Examples

File will be converted toStdio usingStdio::from under the hood.

usestd::fs::File;usestd::process::Command;// With the `foo.txt` file containing "Hello, world!"letfile = File::open("foo.txt")?;letreverse = Command::new("rev")    .stdin(file)// Implicit File conversion into a Stdio.output()?;assert_eq!(reverse.stdout,b"!dlrow ,olleH");
1.63.0 ·Source§

implFrom<OwnedFd> forFile

Source§

fnfrom(owned_fd:OwnedFd) -> Self

Returns aFile that takes ownership of the givenfile descriptor.

1.63.0 ·Source§

implFrom<OwnedHandle> forFile

Available onWindows only.
Source§

fnfrom(owned:OwnedHandle) -> Self

Returns aFile that takes ownership of the given handle.

1.1.0 ·Source§

implFromRawFd forFile

Source§

unsafe fnfrom_raw_fd(fd:RawFd) ->File

Constructs a new instance ofSelf from the given raw filedescriptor.Read more
1.1.0 ·Source§

implFromRawHandle forFile

Available onWindows only.
Source§

unsafe fnfrom_raw_handle(handle:RawHandle) ->File

Constructs a new I/O object from the specified raw handle.Read more
1.4.0 ·Source§

implIntoRawFd forFile

Source§

fninto_raw_fd(self) ->RawFd

Consumes this object, returning the raw underlying file descriptor.Read more
1.4.0 ·Source§

implIntoRawHandle forFile

Available onWindows only.
Source§

fninto_raw_handle(self) ->RawHandle

Consumes this object, returning the raw underlying handle.Read more
1.70.0 ·Source§

implIsTerminal forFile

Source§

fnis_terminal(&self) ->bool

Returnstrue if the descriptor/handle refers to a terminal/tty.Read more
1.0.0 ·Source§

implRead for &File

Source§

fnread(&mut self, buf: &mut [u8]) ->Result<usize>

Reads some bytes from the file.

SeeRead::read docs for more info.

§Platform-specific behavior

This function currently corresponds to theread function on Unix andtheNtReadFile function on Windows. Note that thismay change inthe future.

Source§

fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>

Likeread, except that it reads into a slice of buffers.

SeeRead::read_vectored docs for more info.

§Platform-specific behavior

This function currently corresponds to thereadv function on Unix andfalls back to theread implementation on Windows. Note that thismay change in the future.

Source§

fnis_read_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)

Determines ifFile has an efficientread_vectored implementation.

SeeRead::is_read_vectored docs for more info.

§Platform-specific behavior

This function currently returnstrue on Unix anfalse on Windows.Note that thismay change in the future.

Source§

fnread_buf(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Pull some bytes from this source into the specified buffer.Read more
Source§

fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>

Reads all bytes until EOF in this source, placing them intobuf.Read more
Source§

fnread_to_string(&mut self, buf: &mutString) ->Result<usize>

Reads all bytes until EOF in this source, appending them tobuf.Read more
1.6.0 ·Source§

fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>

Reads the exact number of bytes required to fillbuf.Read more
Source§

fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Reads the exact number of bytes required to fillcursor.Read more
1.0.0 ·Source§

fnby_ref(&mut self) -> &mut Self
where Self:Sized,

Creates a “by reference” adaptor for this instance ofRead.Read more
1.0.0 ·Source§

fnbytes(self) ->Bytes<Self>
where Self:Sized,

Transforms thisRead instance to anIterator over its bytes.Read more
1.0.0 ·Source§

fnchain<R:Read>(self, next: R) ->Chain<Self, R>
where Self:Sized,

Creates an adapter which will chain this stream with another.Read more
1.0.0 ·Source§

fntake(self, limit:u64) ->Take<Self>
where Self:Sized,

Creates an adapter which will read at mostlimit bytes from it.Read more
1.0.0 ·Source§

implRead forFile

Source§

fnread(&mut self, buf: &mut [u8]) ->Result<usize>

Pull some bytes from this source into the specified buffer, returninghow many bytes were read.Read more
Source§

fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>

Likeread, except that it reads into a slice of buffers.Read more
Source§

fnread_buf(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Pull some bytes from this source into the specified buffer.Read more
Source§

fnis_read_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)
Determines if thisReader has an efficientread_vectoredimplementation.Read more
Source§

fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>

Reads all bytes until EOF in this source, placing them intobuf.Read more
Source§

fnread_to_string(&mut self, buf: &mutString) ->Result<usize>

Reads all bytes until EOF in this source, appending them tobuf.Read more
1.6.0 ·Source§

fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>

Reads the exact number of bytes required to fillbuf.Read more
Source§

fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>

🔬This is a nightly-only experimental API. (read_buf #78485)
Reads the exact number of bytes required to fillcursor.Read more
1.0.0 ·Source§

fnby_ref(&mut self) -> &mut Self
where Self:Sized,

Creates a “by reference” adaptor for this instance ofRead.Read more
1.0.0 ·Source§

fnbytes(self) ->Bytes<Self>
where Self:Sized,

Transforms thisRead instance to anIterator over its bytes.Read more
1.0.0 ·Source§

fnchain<R:Read>(self, next: R) ->Chain<Self, R>
where Self:Sized,

Creates an adapter which will chain this stream with another.Read more
1.0.0 ·Source§

fntake(self, limit:u64) ->Take<Self>
where Self:Sized,

Creates an adapter which will read at mostlimit bytes from it.Read more
1.0.0 ·Source§

implSeek for &File

Source§

fnseek(&mut self, pos:SeekFrom) ->Result<u64>

Seek to an offset, in bytes, in a stream.Read more
Source§

fnstream_position(&mut self) ->Result<u64>

Returns the current seek position from the start of the stream.Read more
1.55.0 ·Source§

fnrewind(&mut self) ->Result<()>

Rewind to the beginning of a stream.Read more
Source§

fnstream_len(&mut self) ->Result<u64>

🔬This is a nightly-only experimental API. (seek_stream_len #59359)
Returns the length of this stream (in bytes).Read more
1.80.0 ·Source§

fnseek_relative(&mut self, offset:i64) ->Result<()>

Seeks relative to the current position.Read more
1.0.0 ·Source§

implSeek forFile

Source§

fnseek(&mut self, pos:SeekFrom) ->Result<u64>

Seek to an offset, in bytes, in a stream.Read more
Source§

fnstream_position(&mut self) ->Result<u64>

Returns the current seek position from the start of the stream.Read more
1.55.0 ·Source§

fnrewind(&mut self) ->Result<()>

Rewind to the beginning of a stream.Read more
Source§

fnstream_len(&mut self) ->Result<u64>

🔬This is a nightly-only experimental API. (seek_stream_len #59359)
Returns the length of this stream (in bytes).Read more
1.80.0 ·Source§

fnseek_relative(&mut self, offset:i64) ->Result<()>

Seeks relative to the current position.Read more
1.0.0 ·Source§

implWrite for &File

Source§

fnwrite(&mut self, buf: &[u8]) ->Result<usize>

Writes some bytes to the file.

SeeWrite::write docs for more info.

§Platform-specific behavior

This function currently corresponds to thewrite function on Unix andtheNtWriteFile function on Windows. Note that thismay change inthe future.

Source§

fnwrite_vectored(&mut self, bufs: &[IoSlice<'_>]) ->Result<usize>

Likewrite, except that it writes into a slice of buffers.

SeeWrite::write_vectored docs for more info.

§Platform-specific behavior

This function currently corresponds to thewritev function on Unixand falls back to thewrite implementation on Windows. Note that thismay change in the future.

Source§

fnis_write_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)

Determines ifFile has an efficientwrite_vectored implementation.

SeeWrite::is_write_vectored docs for more info.

§Platform-specific behavior

This function currently returnstrue on Unix anfalse on Windows.Note that thismay change in the future.

Source§

fnflush(&mut self) ->Result<()>

Flushes the file, ensuring that all intermediately buffered contentsreach their destination.

SeeWrite::flush docs for more info.

§Platform-specific behavior

Since aFile structure doesn’t contain any buffers, this function iscurrently a no-op on Unix and Windows. Note that thismay change inthe future.

1.0.0 ·Source§

fnwrite_all(&mut self, buf: &[u8]) ->Result<()>

Attempts to write an entire buffer into this writer.Read more
Source§

fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>

🔬This is a nightly-only experimental API. (write_all_vectored #70436)
Attempts to write multiple buffers into this writer.Read more
1.0.0 ·Source§

fnwrite_fmt(&mut self, args:Arguments<'_>) ->Result<()>

Writes a formatted string into this writer, returning any errorencountered.Read more
1.0.0 ·Source§

fnby_ref(&mut self) -> &mut Self
where Self:Sized,

Creates a “by reference” adapter for this instance ofWrite.Read more
1.0.0 ·Source§

implWrite forFile

Source§

fnwrite(&mut self, buf: &[u8]) ->Result<usize>

Writes a buffer into this writer, returning how many bytes were written.Read more
Source§

fnwrite_vectored(&mut self, bufs: &[IoSlice<'_>]) ->Result<usize>

Likewrite, except that it writes from a slice of buffers.Read more
Source§

fnis_write_vectored(&self) ->bool

🔬This is a nightly-only experimental API. (can_vector #69941)
Determines if thisWriter has an efficientwrite_vectoredimplementation.Read more
Source§

fnflush(&mut self) ->Result<()>

Flushes this output stream, ensuring that all intermediately bufferedcontents reach their destination.Read more
1.0.0 ·Source§

fnwrite_all(&mut self, buf: &[u8]) ->Result<()>

Attempts to write an entire buffer into this writer.Read more
Source§

fnwrite_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) ->Result<()>

🔬This is a nightly-only experimental API. (write_all_vectored #70436)
Attempts to write multiple buffers into this writer.Read more
1.0.0 ·Source§

fnwrite_fmt(&mut self, args:Arguments<'_>) ->Result<()>

Writes a formatted string into this writer, returning any errorencountered.Read more
1.0.0 ·Source§

fnby_ref(&mut self) -> &mut Self
where Self:Sized,

Creates a “by reference” adapter for this instance ofWrite.Read more

Auto Trait Implementations§

§

implFreeze forFile

§

implRefUnwindSafe forFile

§

implSend forFile

§

implSync forFile

§

implUnpin forFile

§

implUnwindSafe forFile

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2025 Movatter.jp