Rust Reference ยท Standard Library Modules
Rust File and OpenOptions types
Reference for std::fs::File and OpenOptions: open, create, create_new, append, truncate, reading and writing, seek, metadata, set_len, sync_all and io::Error kinds.
std::fs::File is an open handle to a file on disk. It implements Read, Write and Seek (and the same traits for &File), and closes itself when dropped. File::open opens an existing file read-only, File::create creates or truncates a file for writing, and File::create_new creates a file only if it does not exist yet.
OpenOptions is the builder for every other combination: append, read and write at once, create but do not truncate, and so on. Reads and writes on a File go straight to the operating system without buffering, so wrap it in BufReader or BufWriter when you do many small operations.
use std::fs::File; use std::io::Write; let mut f = File::create("notes.txt")?; f.write_all(b"hello\n")?;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl File { pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File>; pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File>; pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File>; pub fn options() -> OpenOptions; pub fn metadata(&self) -> io::Result<Metadata>; pub fn set_len(&self, size: u64) -> io::Result<()>; pub fn sync_all(&self) -> io::Result<()>; pub fn sync_data(&self) -> io::Result<()>; pub fn try_clone(&self) -> io::Result<File>; } impl OpenOptions { pub fn new() -> OpenOptions; pub fn read(&mut self, on: bool) -> &mut OpenOptions; pub fn write(&mut self, on: bool) -> &mut OpenOptions; pub fn append(&mut self, on: bool) -> &mut OpenOptions; pub fn truncate(&mut self, on: bool) -> &mut OpenOptions; pub fn create(&mut self, on: bool) -> &mut OpenOptions; pub fn create_new(&mut self, on: bool) -> &mut OpenOptions; pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File>; }
| Option | Meaning |
|---|---|
read |
Allow reading. |
write |
Allow writing at the current position; the file keeps its other contents. |
append |
Every write goes to the end. Implies write access. |
truncate |
Set the length to zero on open. Needs write(true). |
create |
Create the file if it does not exist. Needs write or append. |
create_new |
Create it and fail with AlreadyExists if it exists. Atomic, so it also protects against races and symlink tricks. Overrides create and truncate. |
Returns. An io::Result. File::open equals OpenOptions::new().read(true).open(p). File::create equals write(true).create(true).truncate(true).
Errors and panics. Nothing panics, but everything can fail: NotFound, PermissionDenied, AlreadyExists, InvalidInput (for example truncate without write), or an OS error such as a full disk. Use e.kind() to branch and the Display of the error for a message.
Usage notes
- Drop closes the file, but ignores errors. Errors from the final flush to disk are lost on drop. If the data matters, call
sync_all()and check its result before dropping. - Unbuffered.
read_lineis not even available on a bareFile. For line-based work wrap it in aBufReader; for many small writes use aBufWriterand remember toflush. - Shortcuts for small files.
fs::read_to_string,fs::read,fs::writeandfs::copyopen, transfer and close in one call. Use them when the whole file fits in memory. - Shared cursor.
try_cloneduplicates the handle but both copies share one position and one set of permissions. - Atomic replace. To update a file safely, write to a temporary file in the same directory and
fs::renameit over the old one. - Check-then-open is racy.
if path.exists() { File::open(..) }can fail anyway. Just open it and handle the error. - Platform extras.
std::os::unix::fs::OpenOptionsExtaddsmode, and Windows hasshare_mode; these are not portable. - Paths can be
&str,String,PathorPathBuf, anything implementingAsRef<Path>. - Sandbox note. Our runner may not let you write outside a temporary directory; use
std::env::temp_dir()as the examples do.