How to read a struct from a file in Rust?

前端 未结 3 624
心在旅途
心在旅途 2020-12-01 12:23

Is there a way I can read a structure directly from a file in Rust? My code is:

use std::fs::File;

struct Configuration {
    item1: u8,
    item2: u16,
            


        
3条回答
  •  无人及你
    2020-12-01 13:03

    As Vladimir Matveev mentions, using the byteorder crate is often the best solution. This way, you account for endianness issues, don't have to deal with any unsafe code, or worry about alignment or padding:

    use byteorder::{LittleEndian, ReadBytesExt}; // 1.2.7
    use std::{
        fs::File,
        io::{self, Read},
    };
    
    struct Configuration {
        item1: u8,
        item2: u16,
        item3: i32,
    }
    
    impl Configuration {
        fn from_reader(mut rdr: impl Read) -> io::Result {
            let item1 = rdr.read_u8()?;
            let item2 = rdr.read_u16::()?;
            let item3 = rdr.read_i32::()?;
    
            Ok(Configuration {
                item1,
                item2,
                item3,
            })
        }
    }
    
    fn main() {
        let file = File::open("/dev/random").unwrap();
    
        let config = Configuration::from_reader(file);
        // How to read struct from file?
    }
    

    I've ignored the [char; 8] for a few reasons:

    1. Rust's char is a 32-bit type and it's unclear if your file has actual Unicode code points or C-style 8-bit values.
    2. You can't easily parse an array with byteorder, you have to parse N values and then build the array yourself.

提交回复
热议问题