linuxoperating-systemrust

How to open and close a device in Rust such as "/dev/something"?


In C I can use the function open to open a file or anything else such as /dev/something. And there's close as well. How can I open and close /dev/something in Rust?

In fact, I also need to write to and read from it. How can I do that?


Solution

  • std::fs::File should work for "/dev/something" as well. You can use File::open for reading files.

    Below is example for reading from /dev/null.

    use std::fs::File;
    use std::io::Read;
    let mut f = File::open("/dev/null")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    println!("s:'{}'", s);