Struct File
struct File { ... }
An object providing access to an open file on the filesystem.
An instance of a File can be read and/or written depending on what options
it was opened with. Files also implement Seek to alter the logical cursor
that the file contains internally.
Files are automatically closed when they go out of scope. Errors detected
on closing are ignored by the implementation of Drop. Use the method
sync_all if these errors must be manually handled.
File does not buffer reads and writes. For efficiency, consider wrapping the
file in a BufReader or BufWriter when performing many small read
or write calls, unless unbuffered reads and writes are required.
Examples
Creates a new file and write bytes to it (you can also use write):
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
}
Reads the contents of a file into a String (you can also use read):
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::open("foo.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");
Ok(())
}
Using a buffered Reader:
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let file = File::open("foo.txt")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");
Ok(())
}
Note that, although read and write methods require a &mut File, because
of the interfaces for Read and Write, the holder of a &File can
still modify the file, either through methods that take &File or by
retrieving the underlying OS object and modifying the file that way.
Additionally, many operating systems allow concurrent modification of files
by different processes. Avoid assuming that holding a &File means that the
file will not change.
Platform-specific behavior
On Windows, the implementation of Read and Write traits for File
perform synchronous I/O operations. Therefore the underlying file must not
have been opened for asynchronous I/O (e.g. by using FILE_FLAG_OVERLAPPED).
Implementations
impl File
fn open<P: AsRef<Path>>(path: P) -> io::Result<File>Attempts to open a file in read-only mode.
See the
OpenOptions::openmethod for more details.If you only need to read the entire file contents, consider [
std::fs::read()][self::read] or [std::fs::read_to_string()][self::read_to_string] instead.Errors
This function will return an error if
pathdoes not already exist. Other errors may also be returned according toOpenOptions::open.Examples
use std::fs::File; use std::io::Read; fn main() -> std::io::Result<()> { let mut f = File::open("foo.txt")?; let mut data = vec![]; f.read_to_end(&mut data)?; Ok(()) }fn open_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufReader<File>>Attempts to open a file in read-only mode with buffering.
See the
OpenOptions::openmethod, the [BufReader][io::BufReader] type, and the [BufRead][io::BufRead] trait for more details.If you only need to read the entire file contents, consider [
std::fs::read()][self::read] or [std::fs::read_to_string()][self::read_to_string] instead.Errors
This function will return an error if
pathdoes 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)] use std::fs::File; use std::io::BufRead; fn main() -> std::io::Result<()> { let mut f = File::open_buffered("foo.txt")?; assert!(f.capacity() > 0); for (line, i) in f.lines().zip(1..) { println!("{i:6}: {}", line?); } Ok(()) }fn create<P: AsRef<Path>>(path: P) -> io::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 the full directory path does not exist. See the
OpenOptions::openfunction for more details.See also [
std::fs::write()][self::write] for a simple function to create a file with some given data.Examples
use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(&1234_u32.to_be_bytes())?; Ok(()) }fn create_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufWriter<File>>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 the full directory path does not exist.
See the
OpenOptions::openmethod and the [BufWriter][io::BufWriter] type for more details.See also [
std::fs::write()][self::write] for a simple function to create a file with some given data.Examples
#![feature(file_buffered)] use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let mut f = File::create_buffered("foo.txt")?; assert!(f.capacity() > 0); for i in 0..100 { writeln!(&mut f, "{i}")?; } f.flush()?; Ok(()) }fn create_new<P: AsRef<Path>>(path: P) -> io::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. This way, 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 with
AlreadyExistsor another error based on the situation. SeeOpenOptions::openfor a non-exhaustive list of likely errors.This option is useful because it is atomic. Otherwise between checking whether a file exists and creating a new one, the file may have been created by another process (a TOCTOU race condition / attack).
This can also be written using
File::options().read(true).write(true).create_new(true).open(...).Examples
use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let mut f = File::create_new("foo.txt")?; f.write_all("Hello, world!".as_bytes())?; Ok(()) }fn options() -> OpenOptionsReturns a new OpenOptions object.
This function returns a new OpenOptions object that you can use to open or create a file with specific options if
open()orcreate()are not appropriate.It is equivalent to
OpenOptions::new(), but allows you to write more readable code. Instead ofOpenOptions::new().append(true).open("example.log"), you can writeFile::options().append(true).open("example.log"). This also avoids the need to importOpenOptions.See the
OpenOptions::newfunction for more details.Examples
use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let mut f = File::options().append(true).open("example.log")?; writeln!(&mut f, "new line")?; Ok(()) }fn sync_all(self: &Self) -> io::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 the filesystem before returning.
This can be used to handle errors that would otherwise only be caught when the
Fileis closed, as dropping aFilewill ignore all errors. Note, however, thatsync_allis generally more expensive than closing a file by dropping it, because the latter is not required to block until the data has been written to the filesystem.If synchronizing the metadata is not required, use
sync_datainstead.Examples
use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(b"Hello, world!")?; f.sync_all()?; Ok(()) }fn sync_data(self: &Self) -> io::Result<()>This function is similar to
sync_all, except that it might not synchronize file metadata to the filesystem.This is intended for use cases that must synchronize content, but don't need the metadata on disk. The goal of this method is to reduce disk operations.
Note that some platforms may simply implement this in terms of
sync_all.Examples
use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(b"Hello, world!")?; f.sync_data()?; Ok(()) }fn lock(self: &Self) -> io::Result<()>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 with
lock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions with other methods, such asreadandwriteare platform specific, and it may or may not cause non-lockholders to block.If this file handle/descriptor, or a clone of it, already holds a lock the exact behavior is 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 is 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/handles duplicated or inherited from it) is closed, or if the
unlockmethod is called.Platform-specific behavior
This function currently corresponds to the
flockfunction on Unix with theLOCK_EXflag, and theLockFileExfunction on Windows with theLOCKFILE_EXCLUSIVE_LOCKflag. Note that, this may 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
use std::fs::File; fn main() -> std::io::Result<()> { let f = File::create("foo.txt")?; f.lock()?; Ok(()) }fn lock_shared(self: &Self) -> io::Result<()>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 may hold an exclusive lock at the same time.
This lock may be advisory or mandatory. This lock is meant to interact with
lock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions with other methods, such asreadandwriteare platform specific, and it may or may not cause non-lockholders to block.If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior is 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/handles duplicated or inherited from it) is closed, or if the
unlockmethod is called.Platform-specific behavior
This function currently corresponds to the
flockfunction on Unix with theLOCK_SHflag, and theLockFileExfunction on Windows. Note that, this may 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
use std::fs::File; fn main() -> std::io::Result<()> { let f = File::open("foo.txt")?; f.lock_shared()?; Ok(()) }fn try_lock(self: &Self) -> Result<(), TryLockError>Try to acquire an exclusive lock on the file.
Returns
Err(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 with
lock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions with other methods, such asreadandwriteare platform specific, and it may or may not cause non-lockholders to block.If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior is unspecified and platform dependent, including the possibility that it will deadlock. However, if this method returns
Ok(()), then it has acquired an exclusive lock.If the file is 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/handles duplicated or inherited from it) is closed, or if the
unlockmethod is called.Platform-specific behavior
This function currently corresponds to the
flockfunction on Unix with theLOCK_EXandLOCK_NBflags, and theLockFileExfunction on Windows with theLOCKFILE_EXCLUSIVE_LOCKandLOCKFILE_FAIL_IMMEDIATELYflags. Note that, this may 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
use std::fs::{File, TryLockError}; fn main() -> std::io::Result<()> { let f = File::create("foo.txt")?; // Explicit handling of the WouldBlock error match f.try_lock() { Ok(_) => (), Err(TryLockError::WouldBlock) => (), // Lock not acquired Err(TryLockError::Error(err)) => return Err(err), } // Alternately, propagate the error as an io::Error f.try_lock()?; Ok(()) }fn try_lock_shared(self: &Self) -> Result<(), TryLockError>Try to acquire a shared (non-exclusive) lock on the file.
Returns
Err(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 may hold an exclusive lock at the same time.
This lock may be advisory or mandatory. This lock is meant to interact with
lock,try_lock,lock_shared,try_lock_shared, andunlock. Its interactions with other methods, such asreadandwriteare platform specific, and it may or may not cause non-lockholders to block.If this file handle, or a clone of it, already holds a lock, the exact behavior is unspecified and platform dependent, including the possibility that it will deadlock. However, if this method returns
Ok(()), then it has acquired a shared lock.The lock will be released when this file (along with any other file descriptors/handles duplicated or inherited from it) is closed, or if the
unlockmethod is called.Platform-specific behavior
This function currently corresponds to the
flockfunction on Unix with theLOCK_SHandLOCK_NBflags, and theLockFileExfunction on Windows with theLOCKFILE_FAIL_IMMEDIATELYflag. Note that, this may 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
use std::fs::{File, TryLockError}; fn main() -> std::io::Result<()> { let f = File::open("foo.txt")?; // Explicit handling of the WouldBlock error match f.try_lock_shared() { Ok(_) => (), Err(TryLockError::WouldBlock) => (), // Lock not acquired Err(TryLockError::Error(err)) => return Err(err), } // Alternately, propagate the error as an io::Error f.try_lock_shared()?; Ok(()) }fn unlock(self: &Self) -> io::Result<()>Release all locks on the file.
All locks are released when the file (along with any other file descriptors/handles duplicated or inherited from it) is closed. This method allows releasing locks without closing the file.
If no lock is currently held via this file descriptor/handle, this method may return an error, or may return successfully without taking any action.
Platform-specific behavior
This function currently corresponds to the
flockfunction on Unix with theLOCK_UNflag, and theUnlockFilefunction on Windows. Note that, this may 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
use std::fs::File; fn main() -> std::io::Result<()> { let f = File::open("foo.txt")?; f.lock()?; f.unlock()?; Ok(()) }fn set_len(self: &Self, size: u64) -> io::Result<()>Truncates or extends the underlying file, updating the size of this file to become
size.If the
sizeis less than the current file's size, then the file will be shrunk. If it is greater than the current file's size, then the file will be extended tosizeand have all of the intermediate data filled in with 0s.The file's cursor isn't changed. In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past 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 to the implementation specifics.Examples
use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.set_len(10)?; Ok(()) }Note that this method alters the content of the underlying file, even though it takes
&selfrather than&mut self.fn metadata(self: &Self) -> io::Result<Metadata>Queries metadata about the underlying file.
Examples
use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::open("foo.txt")?; let metadata = f.metadata()?; Ok(()) }fn try_clone(self: &Self) -> io::Result<File>Creates a new
Fileinstance that shares the same underlying file handle as the existingFileinstance. Reads, writes, and seeks will affect bothFileinstances simultaneously.Examples
Creates two handles for a file named
foo.txt:use std::fs::File; fn main() -> std::io::Result<()> { let mut file = File::open("foo.txt")?; let file_copy = file.try_clone()?; Ok(()) }Assuming there’s a file named
foo.txtwith contentsabcdef\n, create two handles, seek one of them, and read the remaining bytes from the other handle:use std::fs::File; use std::io::SeekFrom; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut file = File::open("foo.txt")?; let mut file_copy = file.try_clone()?; file.seek(SeekFrom::Start(3))?; let mut contents = vec![]; file_copy.read_to_end(&mut contents)?; assert_eq!(contents, b"def\n"); Ok(()) }fn set_permissions(self: &Self, perm: Permissions) -> io::Result<()>Changes the permissions on the underlying file.
Platform-specific behavior
This function currently corresponds to the
fchmodfunction on Unix and theSetFileInformationByHandlefunction on Windows. Note that, this may change in the future.Errors
This function will return an error if the user lacks permission change attributes on the underlying file. It may also return an error in other os-specific unspecified cases.
Examples
fn main() -> std::io::Result<()> { use std::fs::File; let file = File::open("foo.txt")?; let mut perms = 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
&selfrather than&mut self.fn set_times(self: &Self, times: FileTimes) -> io::Result<()>Changes the timestamps of the underlying file.
Platform-specific behavior
This function currently corresponds to the
futimensfunction on Unix (falling back tofutimeson macOS before 10.13) and theSetFileTimefunction on Windows. Note that this may change in the future.On most platforms, including UNIX and Windows platforms, this function can also change the timestamps of a directory. To get a
Filerepresenting a directory in order to callset_times, open the directory withFile::openwithout attempting to obtain write permission.Errors
This function will return an error if the user lacks permission to change timestamps on the underlying 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 or more of the timestamps set in the
FileTimesstructure.Examples
fn main() -> std::io::Result<()> { use std::fs::{self, File, FileTimes}; let src = fs::metadata("src")?; let dest = File::open("dest")?; let times = FileTimes::new() .set_accessed(src.accessed()?) .set_modified(src.modified()?); dest.set_times(times)?; Ok(()) }fn set_modified(self: &Self, time: SystemTime) -> io::Result<()>Changes the modification time of the underlying file.
This is an alias for
set_times(FileTimes::new().set_modified(time)).
impl AsFd for fs::File
fn as_fd(self: &Self) -> BorrowedFd<'_>
impl AsHandle for fs::File
fn as_handle(self: &Self) -> BorrowedHandle<'_>
impl AsRawFd for fs::File
fn as_raw_fd(self: &Self) -> RawFd
impl AsRawHandle for fs::File
fn as_raw_handle(self: &Self) -> RawHandle
impl Debug for File
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl FileExt for crate::fs::File
fn read_at(self: &Self, buf: &mut [u8], offset: u64) -> io::Result<usize>fn read_buf_at(self: &Self, buf: BorrowedCursor<'_>, offset: u64) -> io::Result<()>fn read_vectored_at(self: &Self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize>fn write_at(self: &Self, buf: &[u8], offset: u64) -> io::Result<usize>fn write_vectored_at(self: &Self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize>
impl FileExt for fs::File
fn seek_read(self: &Self, buf: &mut [u8], offset: u64) -> io::Result<usize>fn seek_read_buf(self: &Self, buf: BorrowedCursor<'_>, offset: u64) -> io::Result<()>fn seek_write(self: &Self, buf: &[u8], offset: u64) -> io::Result<usize>
impl FileExt for fs::File
fn read_at(self: &Self, buf: &mut [u8], offset: u64) -> io::Result<usize>fn read_buf_at(self: &Self, buf: BorrowedCursor<'_>, offset: u64) -> io::Result<()>fn read_vectored_at(self: &Self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize>fn write_at(self: &Self, buf: &[u8], offset: u64) -> io::Result<usize>fn write_vectored_at(self: &Self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize>
impl Freeze for File
impl From for fs::File
fn from(owned_fd: OwnedFd) -> SelfReturns a
Filethat takes ownership of the given file descriptor.
impl From for fs::File
fn from(owned: OwnedHandle) -> SelfReturns a
Filethat takes ownership of the given handle.
impl FromRawFd for fs::File
unsafe fn from_raw_fd(fd: RawFd) -> fs::File
impl FromRawHandle for fs::File
unsafe fn from_raw_handle(handle: RawHandle) -> fs::File
impl IntoRawFd for fs::File
fn into_raw_fd(self: Self) -> RawFd
impl IntoRawHandle for fs::File
fn into_raw_handle(self: Self) -> RawHandle
impl IsTerminal for crate::fs::File
fn is_terminal(self: &Self) -> bool
impl Read for File
fn read(self: &mut Self, buf: &mut [u8]) -> io::Result<usize>fn read_vectored(self: &mut Self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>fn read_buf(self: &mut Self, cursor: BorrowedCursor<'_>) -> io::Result<()>fn is_read_vectored(self: &Self) -> boolfn read_to_end(self: &mut Self, buf: &mut Vec<u8>) -> io::Result<usize>fn read_to_string(self: &mut Self, buf: &mut String) -> io::Result<usize>
impl RefUnwindSafe for File
impl Seek for File
fn seek(self: &mut Self, pos: SeekFrom) -> io::Result<u64>fn stream_len(self: &mut Self) -> io::Result<u64>fn stream_position(self: &mut Self) -> io::Result<u64>
impl Send for File
impl Sync for File
impl Unpin for File
impl UnwindSafe for File
impl Write for File
fn write(self: &mut Self, buf: &[u8]) -> io::Result<usize>fn write_vectored(self: &mut Self, bufs: &[IoSlice<'_>]) -> io::Result<usize>fn is_write_vectored(self: &Self) -> boolfn flush(self: &mut Self) -> io::Result<()>
impl<T> Any for File
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for File
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for File
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for File
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for File
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for File
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for File
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>