io - 如何从 Rust 中的文件中读取结构?

标签 io rust

在 Rust 中,有没有一种方法可以直接从文件中读取结构?我的代码是:

use std::fs::File;

struct Configuration {
    item1: u8,
    item2: u16,
    item3: i32,
    item4: [char; 8],
}

fn main() {
    let file = File::open("config_file").unwrap();

    let mut config: Configuration;
    // How to read struct from file?
}

如何将我的配置从文件中直接读入config?这可能吗?

最佳答案

给你:

use std::io::Read;
use std::mem;
use std::slice;

#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
struct Configuration {
    item1: u8,
    item2: u16,
    item3: i32,
    item4: [char; 8],
}

const CONFIG_DATA: &[u8] = &[
    0xfd, // u8
    0xb4, 0x50, // u16
    0x45, 0xcd, 0x3c, 0x15, // i32
    0x71, 0x3c, 0x87, 0xff, // char
    0xe8, 0x5d, 0x20, 0xe7, // char
    0x5f, 0x38, 0x05, 0x4a, // char
    0xc4, 0x58, 0x8f, 0xdc, // char
    0x67, 0x1d, 0xb4, 0x64, // char
    0xf2, 0xc5, 0x2c, 0x15, // char
    0xd8, 0x9a, 0xae, 0x23, // char
    0x7d, 0xce, 0x4b, 0xeb, // char
];

fn main() {
    let mut buffer = CONFIG_DATA;

    let mut config: Configuration = unsafe { mem::zeroed() };

    let config_size = mem::size_of::<Configuration>();
    unsafe {
        let config_slice = slice::from_raw_parts_mut(&mut config as *mut _ as *mut u8, config_size);
        // `read_exact()` comes from `Read` impl for `&[u8]`
        buffer.read_exact(config_slice).unwrap();
    }

    println!("Read structure: {:#?}", config);
}

Try it here (针对 Rust 1.38 更新)

但是,您需要小心,因为不安全的代码确实不安全。在 slice::from_raw_parts_mut() 调用之后,同一数据同时存在两个可变句柄,这违反了 Rust 别名规则。因此,您希望尽可能短地保留从结构中创建的可变切片。我还假设您了解字节序问题 - 上面的代码绝不是可移植的,如果在不同类型的机器(例如 ARM 与 x86)上编译和运行,将会返回不同的结果。

如果您可以选择格式并且想要紧凑的二进制格式,请考虑使用 bincode .否则,如果您需要,例如解析一些预定义的二进制结构,byteorder箱子是要走的路。

关于io - 如何从 Rust 中的文件中读取结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25410028/

相关文章:

grails - 如何使用gsp模板创建文本文件?

c - 将一些数据写入文件后出现段错误

c - 无法从文本文件中读取数据。

assembly - 如何将AVR GCC风格的C内联汇编转换为Rust内联汇编?

rust - 如何使用 Rust 跟踪获取/存储跨度持续时间?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - CommPortIdentifier.getPortIdentifier() 导致程序崩溃

rust - 使用带有 iter().map() 的函数 - 作为命名函数 vs 作为闭包

random - 如何使用字符串或数字在 Rust 中为随机数生成器提供种子

rust - 关系的渴望