Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to asynchronously read a file?

Tags:

rust

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.

like image 786
uwu Avatar asked Oct 19 '22 19:10

uwu


1 Answers

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);
}
like image 57
xx1xx Avatar answered Oct 21 '22 20:10

xx1xx