2

The only way I know reading up to n bytes from file is this:

use std::fs::File;
use std::io;
use std::io::prelude::*;

fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut buffer = [0; 10];

    // read exactly 10 bytes
    f.read_exact(&mut buffer)?;
    Ok(())
}

What I would like to implement is: user gives a buffer and the parameter n, I put up to n bytes into that buffer.

fn read_n_bytes(f: &File, n: usize, dst: &mut Vec<u8>) {
    let mut buffer = [0; n]; // error here, n isn't a constant
    f.read_exact(&mut buffer);
    // concat content of buffer to dst...
}

How to I tell read_exact to read up to n bytes into dst directly?

fn read_n_bytes(f: &File, n: usize, dst: &mut Vec<u8>) {
    f.read_exact(dst, n);
}
hellow
  • 12,430
  • 7
  • 56
  • 79
JACK M
  • 2,627
  • 3
  • 25
  • 43
  • 1
    Please see [my edit](https://stackoverflow.com/posts/57203009/revisions) on your other question and try to avoid the same thing again. In this case: don't put the programming language into the title. That's what tags are for. – hellow Jul 26 '19 at 07:16
  • What about `let mut v = vec![0; 100]; f.read_exact(&mut v[..n])`? Passing a `n` is IMHO very unrusty, because the slice knows how big it is. So why bothering and passing a dedicated `n` to the function? – hellow Jul 26 '19 at 07:22

0 Answers0