Why file.read() is reading file by 2 bytes at a time?

I'm trying to read a file, but it reads only 2 bytes at a time.
Though I'm reading documentation and it says:

Read bytes, up to the length of buf and place them in buf.

Is there mistake in my code or I'm missing something?

use std::fs::File;
use std::io::Read;
use std::error::Error;

fn main()
{
    let mut file = match File::open("file.txt")
    {
        Ok(file) => file,
        Err(e) => panic!("Error: {}", Error::description(&e))
    };

    read_file(&mut file);
}

fn get_file_size(file: &File) -> u64
{
    match file.metadata()
    {
        Ok(metadata) => metadata.len(),
        Err(e) => panic!("Error: {}", Error::description(&e))
    }
}

fn read_file(file: &mut File)
{
    let file_size = get_file_size(&file);

    let mut buffer = [0u8, 255];
    let mut bytes_read = 0u64;

    while bytes_read < file_size
    {
        match file.read(&mut buffer)
        {
            Ok(count) =>
            {
                bytes_read += count as u64;
                println!("Read {} bytes. Sum of read bytes {}.", count, bytes_read);
            },
            Err(e) => panic!("Error: {}", Error::description(&e))
        }
    }
}
1 Like

It's a simple typo to make!

This is an array of two elements:

let mut buffer = [0u8, 255];

you maybe want this (array of 255 elements)

let mut buffer = [0u8; 255];
2 Likes

Arghh, I'm feeling dumb right now :smile:

2 Likes