Slurp: read content of a text file into a string

slurp read_to_string

People who programmed in Perl are probably familiar with what was called slurp mode that was later converted to a function called slurp. The whole idea was to make it easy to read the content of a text file into memory, to slurp it in.

In Rust there is a function called read_to_string that does this.

examples/slurp/src/main.rs

use std::fs::read_to_string;

fn main() {
    let filename = "data.txt";
    let content = read_to_string(filename).unwrap();
    println!("------");
    print!("{}", content);
    println!("------");
}

It is nice and easy to use, you just have to remember that this will read the whole file into memory which is not going to work well for huge files.

Related Pages

Keep you data safe using advisory lock on your files
Files - dealing with files in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo