How to read a struct from a file in Rust?

Here you go: 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, … Read more

Reading from a TcpStream with Read::read_to_string hangs until the connection is closed by the remote end

Check out the docs for Read::read_to_string, emphasis mine: Read all bytes until EOF in this source, placing them into buf. Likewise for Read::read_to_end: Read all bytes until EOF in this source, placing them into buf. Notably, you aren’t reading 512 bytes in the first example, you are pre-allocating 512 bytes of space and then reading … Read more

How to idiomatically / efficiently pipe data from Read+Seek to Write?

You are looking for io::copy: use std::io::{self, prelude::*, SeekFrom}; pub fn assemble<I, O>(mut input: I, mut output: O) -> Result<(), io::Error> where I: Read + Seek, O: Write, { // first seek and output “hello”; io::copy(&mut input.by_ref().take(5), &mut output)?; // then output “world”; io::copy(&mut input.take(5), &mut output)?; Ok(()) } If you look at … Read more

MPI Reading from a text file

Text isn’t a great format for parallel processing exactly because you don’t know ahead of time where (say) line 25001 begins. So these sorts of problems are often dealt with ahead of time through some preprocessing step, either building an index or partitioning the file into the appropriate number of chunks for each process to … Read more

Read a file line by line in Prolog

You can use read to read the stream. Remember to invoke at_end_of_stream to ensure no syntax errors. Example: main :- open(‘myFile.txt’, read, Str), read_file(Str,Lines), close(Str), write(Lines), nl. read_file(Stream,[]) :- at_end_of_stream(Stream). read_file(Stream,[X|L]) :- \+ at_end_of_stream(Stream), read(Stream,X), read_file(Stream,L). myFile.txt ‘line 0’. ‘line 1’. ‘line 2’. ‘line 3’. ‘line 4’. ‘line 5’. ‘line 6’. ‘line 7’. ‘line … Read more