[Solved]Passing std::io::File has a function parameter input


#1

I am a newbie learning Rust… i am trying a test project by reading and processing a binary file. i am trying to pass a file io to a function (inspect_file())… the program compiles and runs but the file passed is not correctly.

If i pass the file string (&args[0]) to the function and do the File::open inside the function then it works.
Can someone tell me what is going wrong here?

Thanks
bosscar

use std::env;
use std::fs::File;
use std::io::{Cursor, SeekFrom};
use std::io::prelude::{Read, Seek};
use byteorder::{LittleEndian, ReadBytesExt};

fn main() {
let args: Vec<String> = env::args().collect();
let file = File::open(&args[0]).expect(“file not found”);
let (result, num_items) = inspect_isf(file);
println!(“The result: {}”, result);
println!(“Num of items: {}”, num_items);
}

fn inspect_isf(mut file: std::fs::File) -> (bool,u32) {
let mut result = true;
let mut num_items = 0;
let magic_header = 0xAB;
let magic_footer = 0xAC;
let mut buf = [0; 4];
file.read_exact(&mut buf).expect(“read error”);
let mut rdr = Cursor::new(buf);
let isf_header = rdr.read_u32::<LittleEndian>().unwrap();
if isf_header != magic_header { result = false }
file.seek(SeekFrom::End(-4)).expect(“seek failure”);
file.read_exact(&mut buf).expect(“read error”);
rdr = Cursor::new(buf);
let isf_footer = rdr.read_u32::<LittleEndian>().unwrap();
if isf_footer != magic_footer { result = false }
if result {
file.seek(SeekFrom::End(-8)).expect(“seek failure”);
file.read_exact(&mut buf).expect(“read error”);
rdr = Cursor::new(buf);
num_items = rdr.read_u32::<LittleEndian>().unwrap();
}
(result, num_items)
}


#2

please ignore this question… i found the issue :slight_smile:


#3

Next time you post code please use the playground or

```rust
// your code here
```

To format your code


#4

Thank you for the feedback