How to read a specified number of bytes from a file into Vec

I want to read a defined at runtime number of bytes from a file. I do not know how to do this, the closest I have gotten is by doing this:

fn get_rand_bytes<const S: usize>() -> [u8; S] {
    let mut f = File::open("/dev/urandom").unwrap();
    let mut buffer = [0; S]; buffer).unwrap();


The issue with this is that I cannot determine the number of bytes to read at runtime, as the S must be a constant. I do not currently know of any equivalent way of doing this with a Vec. I cant use fs::read_to_end because /dev/urandom has no end and would overflow the stack given enough time. I don't want to use the rand crate because I want to learn how to do this on my own.

Here's one option:

fn get_rand_bytes(s: usize) -> Vec<u8> {
    let mut f = File::open("/dev/urandom").unwrap();
    let mut buffer = vec![0; s];

    f.read_exact(&mut buffer).unwrap();


Note that I also changed read to read_exact, because read might not fill the provided buffer. You should normally only call read in a loop (or use functions like read_to_end or read_exact that do this for you).

Alternately, you could do something with Read::take, like:

    let mut buffer = Vec::with_capacity(s);
    f.take(s as u64).read_to_end(&mut buffer).unwrap();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.