thomas-shirley.com

Reading from Files

First off. The filesystem module is not included in the Rust prelude. So we need to include it:

 use std::fs;

Quick as a flash, we can then read a file in as:

    let my_file =       fs::read_to_string("path_to_the_file.txt").unwrap();

Notice we're performing an unwrap function here. I still don't know why, but I hope it'll make sense later.

Sometimes, we might need to look at a file loaded, row by row:

    let my_file =       fs::read_to_string("path_to_the_file.txt").unwrap();

for line in my_file.lines(){
    println!("{}", line);
}

The lines() method exists on the str Struct, which breaks apart a string by the \n or \r\n delimiters.

Using this funciton is great. But when we are reading data that isn't just string data, like a video file for example, we need to read the data as bytes, by just using the read() function:

let read_data = fs::read("path_to_the_file.txt").unwrap();
println!("Data is {:?}", read_data);

This reads the data in as a vector of u8 values. The println! macro can't print these values, so we pass the debug operator into the {} as :?, to dump the values.

07-11-2021