std-function

fs::read_to_string: read UTF-8 file

Load a small UTF-8 text file. Binary bytes with invalid UTF-8 cause failure. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): 8 4 Common mistake: Assuming file size counts characters.

Formal Syntax & Structure

rust syntaxrust
fs::read_to_string(path) -> io::Result<String>

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File, OpenOptions};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("use a fresh disposable directory");    let p = std::path::Path::new("bm-fixture").join("note.txt");    File::create_new(&p).unwrap().write_all("سلام".as_bytes()).unwrap();    let s = fs::read_to_string(&p).unwrap();    println!("{} {}", s.len(), s.chars().count());}
Rust Reference