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,
item3: i32,
item4: [char; 8],
}
fn main() {
let file = File::open("config_file").unwrap();
let mut config: Configuration;
// How to read struct from file?
}
How would I read my configuration directly into config
from the file? Is this even possible?
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:
I've ignored the
[char; 8]
for a few reasons:char
is a 32-bit type and it's unclear if your file has actual Unicode code points or C-style 8-bit values.Note: updated for the stable Rust (1.10 as of now).
Here you go:
Try it here
You need to be careful, however, as unsafe code is, well, unsafe. Here in particular after
slice::from_raw_parts_mut()
invocation there exist two mutable handles to the same data at the same time, which is a violation of Rust aliasing rules. Therefore you would want to keep the mutable slice created out of a structure for the shortest possible time. I also assume that you know about endianness issues - the code above is by no means portable, and will return different results if compiled and run on different kinds of machines (ARM vs x86, for example).If you can choose the format and you want a compact binary one, consider using bincode. Otherwise, if you need e.g. to parse some pre-defined binary structure, byteorder crate is the way to go.
Note that the following code does not take into account any endianness or padding issues and is intended to be used with POD types.
struct Configuration
should be safe in this case.Here is a function that can read a struct (of a pod type) from a file:
If you want to read a sequence of structs from a file, you can execute
read_struct
multiple times or read all the file at once: