Rust Reference ยท Standard Library Modules
The std::fs module
Reference for std::fs: read_to_string, write, File, OpenOptions, create_dir_all, read_dir, remove_file, metadata, rename and copy, with errors and pitfalls.
std::fs is Rust's interface to the filesystem. It has two layers: convenience functions that do a whole job in one call (fs::read_to_string, fs::write, fs::create_dir_all, fs::remove_file) and the File type for streaming access together with OpenOptions for fine control over how a file is opened.
Almost every function returns io::Result<T>; failure (missing file, permission denied, directory not empty) is a normal result you handle with ? or match, never a panic. Paths are anything that implements AsRef<Path>, so &str, String and PathBuf all work.
let text = std::fs::read_to_string("notes.txt")?; std::fs::write("copy.txt", text)?;
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
| Function | Signature (simplified) | Description |
|---|---|---|
read |
fn read(path) -> io::Result<Vec<u8>> |
Whole file as bytes. |
read_to_string |
fn read_to_string(path) -> io::Result<String> |
Whole file as UTF-8; invalid UTF-8 is an InvalidData error. |
write |
fn write(path, contents) -> io::Result<()> |
Create or truncate, then write everything. |
copy |
fn copy(from, to) -> io::Result<u64> |
Copy contents and permissions; returns bytes copied. |
rename |
fn rename(from, to) -> io::Result<()> |
Move or rename; may fail across filesystems. |
remove_file |
fn remove_file(path) -> io::Result<()> |
Delete a file or symlink. |
create_dir, create_dir_all |
fn(path) -> io::Result<()> |
One level, or all missing parents (no error if it exists). |
remove_dir, remove_dir_all |
fn(path) -> io::Result<()> |
Empty directory only, or a whole tree. |
read_dir |
fn read_dir(path) -> io::Result<ReadDir> |
Iterator of io::Result<DirEntry>, in unspecified order. |
metadata, symlink_metadata |
fn(path) -> io::Result<Metadata> |
Size, type, times, permissions (the second does not follow symlinks). |
canonicalize |
fn(path) -> io::Result<PathBuf> |
Absolute path with symlinks resolved; the path must exist. |
exists on Path, fs::exists |
-> io::Result<bool> |
fs::exists (Rust 1.81) reports errors instead of hiding them. |
Types: File (open, create, create_new, metadata, sync_all, set_len), OpenOptions (read, write, append, truncate, create, create_new), DirEntry (path, file_name, file_type, metadata), Metadata, Permissions and FileType.
Errors and edge cases: NotFound, PermissionDenied, AlreadyExists, InvalidData, DirectoryNotEmpty and IsADirectory are the usual ErrorKind values. Reading a directory with read_to_string fails.
Usage notes
Fileis unbuffered. Wrap it inBufReaderorBufWriterfor many small reads or writes; see std::io.- A
Filecloses when dropped, ignoring close errors. Callsync_all()when you must know data reached the disk. fs::writereplaces the file. UseOpenOptions::new().append(true)to add to it, andcreate_new(true)to fail instead of overwriting (atomic existence check).- Checking
Path::exists()and then opening is a race (time-of-check to time-of-use). Just try the operation and handle the error. - Writing a new file then
renameover the target is the standard way to update a file atomically. - Relative paths resolve against the process's current directory, see std::env.
- The browser runner gives each program a scratch directory that disappears afterward, so examples create and clean up their own files.