3 ms·
>Can you point out an example on reading a bunch of structs from a file? Without std? Now I'm really curious. Not really, but here is really simple example:
by throwaway8948 5y ago
>Can you point out an example on reading a bunch of structs from a file? Without std? Now I'm really curious.
Not really, but here is really simple example:
use std::fs::File;
use std::io::Read;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn bytes2point(buf: [u8; 8]) -> Point {
Point {
// Slices to arrays is a bit unwieldy...
x: i32::from_le_bytes(buf[..4].try_into().unwrap()),
y: i32::from_le_bytes(buf[4..].try_into().unwrap()),
}
}
fn main() {
let mut buf: [u8; 8] = [0; 8];
let mut file: File = File::open("data.txt").unwrap();
Read::read(&mut file, &mut buf).unwrap();
let point: Point = bytes2point(buf);
println!("{:?}", point);
}
It doesn't do any extra i/o compared to C. Std is only used for filesystem access and printing. It does require extra buffer.
- scoutt 5y agoThank you. I see. I'm looking now at how to load DOOM WAD files in Rust (https://github.com/bjt0/rs_wad/blob/master/src/wad.rs#L105 https://github.com/bjt0/rs_wad/blob/master/src/wad.rs#L105) as an example, and I see it uses your method (even if it seems to store each piece in individual variables to then copy them into the struct). It's not as straightforward as one would expect (as you say, it requires an extra buffer and parsing, but no extra IO). I surely wouldn't get to the solution by myself.