uwu
uwu

Reputation: 1738

How to asynchronously read a file?

I could create a separate thread to act as an I/O queue, but I'm not sure whether this is the best way. It looks like the best.

I do not know how to load a local file with mio.

Upvotes: 9

Views: 7894

Answers (2)

xx1xx
xx1xx

Reputation: 2089

Use tokio::fs::read:

use tokio::prelude::Future;

fn main() {
    let task = tokio::fs::read("/proc/cpuinfo").map(|data| {
        // do something with the contents of the file ...
        println!("contains {} bytes", data.len());
        println!("{:?}", String::from_utf8(data));
    }).map_err(|e| {
        // handle errors
        eprintln!("IO error: {:?}", e);
    });
    tokio::run(task);
}

Upvotes: 6

Leonora Tindall
Leonora Tindall

Reputation: 1521

I would suggest simply spinning off another thread yourself. io is not planning to do this, and making your own async loader allows you to have complete control over how and when reads/writes happen, which is important if performance is your goal (as I would imagine it is, if you need async disk I/O). You can choose whether to write/read single bytes, single lines, or to accumulate blocks and write those. If you application is waiting on something else at other times, like the network, you could choose to write to disk then, for example.

Upvotes: 2

Related Questions