tokio::fs
- Rust course
- Advanced
- Lesson 10/81
- 4 min
Do async file I/O with tokio::fs.
tokio::fs
tokio::fs offers async functions with the same names as std::fs. Behind the scenes it runs the operations on a separate thread pool, so the task scheduler doesn't block:
use tokio::fs;
fs::write("selam.txt", "merhaba").await?;
let icerik = fs::read_to_string("selam.txt").await?;
println!("{} bayt", icerik.len());For many small file operations, calling std in bulk inside spawn_blocking is often faster.
The same operation with std
In the exercise we do the same steps with std; the APIs being identical makes moving code to async easy:
use std::{env, fs, io};
fn main() -> io::Result<()> {
let yol = env::temp_dir().join("selam.txt");
fs::write(&yol, "merhaba")?;
let icerik = fs::read_to_string(&yol)?;
println!("{} bayt", icerik.len());
Ok(())
}Practice Write and read
Let main return io::Result<()>. Write "merhaba" to selam.txt in the temp folder, read it back and print N bayt.
Starter code
use std::{env, fs, io};
fn main() {
// buraya yaz
}Sample solution
use std::{env, fs, io};
fn main() -> io::Result<()> {
let yol = env::temp_dir().join("selam.txt");
fs::write(&yol, "merhaba")?;
let icerik = fs::read_to_string(&yol)?;
println!("{} bayt", icerik.len());
Ok(())
}Expected output
7 bayt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does the operating system not offer a truly asynchronous interface for file I/O (on most platforms)?
- Rust doesn't support it
- There's no need
- Classic file calls are blocking; tokio runs them on a thread pool Correct answer
- Files are too small
Explanation: Network sockets are waited on without blocking via epoll/kqueue; for files there are newer interfaces like io_uring.
2 Async read
let icerik = tokio::fs::read_to_string("selam.txt").____?;
let icerik = tokio::fs::read_to_string("selam.txt").await?;
Explanation: tokio::fs functions return futures; they're awaited with .await.
3 std and tokio counterpart
| Term | Meaning |
|---|---|
std::fs::write |
tokio::fs::write(..).await |
std::thread::sleep |
tokio::time::sleep(..).await |
std::net::TcpListener |
tokio::net::TcpListener |
thread::spawn |
tokio::spawn |