How to read bytes into a buffer with a non constant length

Hello everyone,

I try to read bytes from a file without knowing the number of bytes I have to read at compile time. I explain, the length of the bytes to be read is calculated dynamically. I tried many ways but I do not found any solution. Here is my code, I have an error, "non-constant value".

fn read(mut file : File) -> io::Result<()> {
    
    let mut flag : u8 = 0;
    
    while ((flag >> 7) & 1) != 1 {
        
        let mut buffer = [0;1];
        
        let _ = file.read_exact(&mut buffer)?;
        
        flag = buffer[0];
        
        let block_type = flag & 0x7F;
        
        println!("block_type : {:?}", block_type);
        
        let mut buffer = [0;3];
        
        let _ = file.read_exact(&mut buffer)?;
        
        let length = usize::from(buffer[0]) << 16 | usize::from(buffer[1]) << 8 | usize::from(buffer[2]);
        
        println!("length : {:?}", length);
        
        let mut buffer = [0;length];
        
        let _ = file.read_exact(&mut buffer)?;
    }
    
    Ok(())
}

Thank you for your help. Vincent

If the size of the file can only be known at runtime, you want to use vec![0; length] instead of [0; length]. That will allocate the required space on the heap instead of the stack.

1 Like

Don't use an array as a buffer for reading files. You'll overflow the stack.

Thank you very much, you save me !

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.