Skip to content

Instantly share code, notes, and snippets.

@MarkusH
Last active January 6, 2022 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkusH/0b94b19c0f58691d234dbcdc98515388 to your computer and use it in GitHub Desktop.
Save MarkusH/0b94b19c0f58691d234dbcdc98515388 to your computer and use it in GitHub Desktop.
use std::fs::File;
use std::io::prelude::*;
const BYTES_PER_LINE: usize = 16;
fn main() {
let mut f= File::open("/tmp/file.txt").unwrap();
let mut pos = 0;
let mut buffer = [0; BYTES_PER_LINE];
while let Ok(_) = f.read_exact(&mut buffer) {
print!("[0x{:08x}] ", pos);
for byte in &buffer {
match *byte {
0x00 => print!(". "),
0xff => print!("XX "),
_ => print!("{:02x}", byte),
}
}
println!("");
pos += BYTES_PER_LINE;
}
}

Actual output

$ cargo build
   Compiling foo v0.1.0 (/tmp/foo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.64s
$ echo -n "0123456789abcdef" > /tmp/file.txt                
$ ./target/debug/foo
[0x00000000] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 
$ echo -n "0123456789abcdef0123456789abcdef" > /tmp/file.txt    
$ ./target/debug/foo                                        
[0x00000000] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 
[0x00000010] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 
$ echo -n "0123456789abcdef0123456789abcdef0123" > /tmp/file.txt
$ ./target/debug/foo
[0x00000000] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 
[0x00000010] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66

Expected output (for the last call)

$ echo -n "0123456789abcdef0123456789abcdef0123" > /tmp/file.txt
$ ./target/debug/foo
[0x00000000] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66 
[0x00000010] 30 31 32 33 34 35 36 37 38 39 61 62 63 64 65 66
[0x00000020] 30 31 32 33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment